repo
stringclasses
10 values
instance_id
stringlengths
18
32
html_url
stringlengths
41
55
feature_patch
stringlengths
805
8.42M
test_patch
stringlengths
548
207k
doc_changes
listlengths
0
92
version
stringclasses
57 values
base_commit
stringlengths
40
40
PASS2PASS
listlengths
0
3.51k
FAIL2PASS
listlengths
0
5.17k
augmentations
dict
mask_doc_diff
listlengths
0
92
problem_statement
stringlengths
0
54.8k
scikit-learn/scikit-learn
scikit-learn__scikit-learn-22255
https://github.com/scikit-learn/scikit-learn/pull/22255
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 61e074e56a657..ef2308997f898 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -95,6 +95,10 @@ Changelog See :func:`cluster.spectral_clustering` for more details. :pr:`21148` by :user:`Andrew Knyazev <lobpcg>` +- |Enhancement| Adds :term:`get_feature_names_out` to :class:`cluster.Birch`, + :class:`cluster.FeatureAgglomeration`, :class:`cluster.KMeans`, + :class:`cluster.MiniBatchKMeans`. :pr:`22255` by `Thomas Fan`_. + - |Efficiency| In :class:`cluster.KMeans`, the default ``algorithm`` is now ``"lloyd"`` which is the full classical EM-style algorithm. Both ``"auto"`` and ``"full"`` are deprecated and will be removed in version 1.3. They are diff --git a/sklearn/cluster/_agglomerative.py b/sklearn/cluster/_agglomerative.py index 4bc49ea2301e6..68ab834202753 100644 --- a/sklearn/cluster/_agglomerative.py +++ b/sklearn/cluster/_agglomerative.py @@ -14,7 +14,7 @@ from scipy import sparse from scipy.sparse.csgraph import connected_components -from ..base import BaseEstimator, ClusterMixin +from ..base import BaseEstimator, ClusterMixin, _ClassNamePrefixFeaturesOutMixin from ..metrics.pairwise import paired_distances from ..metrics import DistanceMetric from ..metrics._dist_metrics import METRIC_MAPPING @@ -1054,7 +1054,9 @@ def fit_predict(self, X, y=None): return super().fit_predict(X, y) -class FeatureAgglomeration(AgglomerativeClustering, AgglomerationTransform): +class FeatureAgglomeration( + _ClassNamePrefixFeaturesOutMixin, AgglomerativeClustering, AgglomerationTransform +): """Agglomerate features. Recursively merges pair of clusters of features. @@ -1236,6 +1238,7 @@ def fit(self, X, y=None): """ X = self._validate_data(X, ensure_min_features=2) super()._fit(X.T) + self._n_features_out = self.n_clusters_ return self @property diff --git a/sklearn/cluster/_birch.py b/sklearn/cluster/_birch.py index 8e86d8dd6ba08..3e47cc7b74492 100644 --- a/sklearn/cluster/_birch.py +++ b/sklearn/cluster/_birch.py @@ -11,7 +11,12 @@ from ..metrics import pairwise_distances_argmin from ..metrics.pairwise import euclidean_distances -from ..base import TransformerMixin, ClusterMixin, BaseEstimator +from ..base import ( + TransformerMixin, + ClusterMixin, + BaseEstimator, + _ClassNamePrefixFeaturesOutMixin, +) from ..utils.extmath import row_norms from ..utils import check_scalar, deprecated from ..utils.validation import check_is_fitted @@ -342,7 +347,9 @@ def radius(self): return sqrt(max(0, sq_radius)) -class Birch(ClusterMixin, TransformerMixin, BaseEstimator): +class Birch( + _ClassNamePrefixFeaturesOutMixin, ClusterMixin, TransformerMixin, BaseEstimator +): """Implements the BIRCH clustering algorithm. It is a memory-efficient, online-learning algorithm provided as an @@ -599,6 +606,7 @@ def _fit(self, X, partial): centroids = np.concatenate([leaf.centroids_ for leaf in self._get_leaves()]) self.subcluster_centers_ = centroids + self._n_features_out = self.subcluster_centers_.shape[0] self._global_clustering(X) return self diff --git a/sklearn/cluster/_kmeans.py b/sklearn/cluster/_kmeans.py index b631b1f77b26a..51d87044f5496 100644 --- a/sklearn/cluster/_kmeans.py +++ b/sklearn/cluster/_kmeans.py @@ -16,7 +16,12 @@ import numpy as np import scipy.sparse as sp -from ..base import BaseEstimator, ClusterMixin, TransformerMixin +from ..base import ( + BaseEstimator, + ClusterMixin, + TransformerMixin, + _ClassNamePrefixFeaturesOutMixin, +) from ..metrics.pairwise import euclidean_distances from ..metrics.pairwise import _euclidean_distances from ..utils.extmath import row_norms, stable_cumsum @@ -767,7 +772,9 @@ def _labels_inertia_threadpool_limit( return labels, inertia -class KMeans(TransformerMixin, ClusterMixin, BaseEstimator): +class KMeans( + _ClassNamePrefixFeaturesOutMixin, TransformerMixin, ClusterMixin, BaseEstimator +): """K-Means clustering. Read more in the :ref:`User Guide <k_means>`. @@ -1240,6 +1247,7 @@ def fit(self, X, y=None, sample_weight=None): ) self.cluster_centers_ = best_centers + self._n_features_out = self.cluster_centers_.shape[0] self.labels_ = best_labels self.inertia_ = best_inertia self.n_iter_ = best_n_iter @@ -2020,6 +2028,7 @@ def fit(self, X, y=None, sample_weight=None): break self.cluster_centers_ = centers + self._n_features_out = self.cluster_centers_.shape[0] self.n_steps_ = i + 1 self.n_iter_ = int(np.ceil(((i + 1) * self._batch_size) / n_samples)) @@ -2134,6 +2143,7 @@ def partial_fit(self, X, y=None, sample_weight=None): ) self.n_steps_ += 1 + self._n_features_out = self.cluster_centers_.shape[0] return self
diff --git a/sklearn/cluster/tests/test_birch.py b/sklearn/cluster/tests/test_birch.py index 5d8a3222ef156..4e64524e2cb11 100644 --- a/sklearn/cluster/tests/test_birch.py +++ b/sklearn/cluster/tests/test_birch.py @@ -219,3 +219,14 @@ def test_birch_params_validation(params, err_type, err_msg): X, _ = make_blobs(n_samples=80, centers=4) with pytest.raises(err_type, match=err_msg): Birch(**params).fit(X) + + +def test_feature_names_out(): + """Check `get_feature_names_out` for `Birch`.""" + X, _ = make_blobs(n_samples=80, n_features=4, random_state=0) + brc = Birch(n_clusters=4) + brc.fit(X) + n_clusters = brc.subcluster_centers_.shape[0] + + names_out = brc.get_feature_names_out() + assert_array_equal([f"birch{i}" for i in range(n_clusters)], names_out) diff --git a/sklearn/cluster/tests/test_feature_agglomeration.py b/sklearn/cluster/tests/test_feature_agglomeration.py index 6d9a942e3dcfe..1f61093a9568d 100644 --- a/sklearn/cluster/tests/test_feature_agglomeration.py +++ b/sklearn/cluster/tests/test_feature_agglomeration.py @@ -4,8 +4,11 @@ # Authors: Sergul Aydore 2017 import numpy as np import pytest + +from numpy.testing import assert_array_equal from sklearn.cluster import FeatureAgglomeration from sklearn.utils._testing import assert_array_almost_equal +from sklearn.datasets import make_blobs def test_feature_agglomeration(): @@ -41,3 +44,16 @@ def test_feature_agglomeration(): assert_array_almost_equal(agglo_mean.transform(X_full_mean), Xt_mean) assert_array_almost_equal(agglo_median.transform(X_full_median), Xt_median) + + +def test_feature_agglomeration_feature_names_out(): + """Check `get_feature_names_out` for `FeatureAgglomeration`.""" + X, _ = make_blobs(n_features=6, random_state=0) + agglo = FeatureAgglomeration(n_clusters=3) + agglo.fit(X) + n_clusters = agglo.n_clusters_ + + names_out = agglo.get_feature_names_out() + assert_array_equal( + [f"featureagglomeration{i}" for i in range(n_clusters)], names_out + ) diff --git a/sklearn/cluster/tests/test_k_means.py b/sklearn/cluster/tests/test_k_means.py index 6e395778418c8..2d62aaaba96e9 100644 --- a/sklearn/cluster/tests/test_k_means.py +++ b/sklearn/cluster/tests/test_k_means.py @@ -1205,3 +1205,18 @@ def test_is_same_clustering(): # mapped to a same value labels3 = np.array([1, 0, 0, 2, 2, 0, 2, 1], dtype=np.int32) assert not _is_same_clustering(labels1, labels3, 3) + + [email protected]( + "Klass, method", + [(KMeans, "fit"), (MiniBatchKMeans, "fit"), (MiniBatchKMeans, "partial_fit")], +) +def test_feature_names_out(Klass, method): + """Check `feature_names_out` for `KMeans` and `MiniBatchKMeans`.""" + class_name = Klass.__name__.lower() + kmeans = Klass() + getattr(kmeans, method)(X) + n_clusters = kmeans.cluster_centers_.shape[0] + + names_out = kmeans.get_feature_names_out() + assert_array_equal([f"{class_name}{i}" for i in range(n_clusters)], names_out) diff --git a/sklearn/tests/test_common.py b/sklearn/tests/test_common.py index a8178a4219485..7f6f99dcc8b67 100644 --- a/sklearn/tests/test_common.py +++ b/sklearn/tests/test_common.py @@ -380,7 +380,6 @@ def test_pandas_column_name_consistency(estimator): # TODO: As more modules support get_feature_names_out they should be removed # from this list to be tested GET_FEATURES_OUT_MODULES_TO_IGNORE = [ - "cluster", "ensemble", "isotonic", "kernel_approximation",
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 61e074e56a657..ef2308997f898 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -95,6 +95,10 @@ Changelog\n See :func:`cluster.spectral_clustering` for more details.\n :pr:`21148` by :user:`Andrew Knyazev <lobpcg>`\n \n+- |Enhancement| Adds :term:`get_feature_names_out` to :class:`cluster.Birch`,\n+ :class:`cluster.FeatureAgglomeration`, :class:`cluster.KMeans`,\n+ :class:`cluster.MiniBatchKMeans`. :pr:`22255` by `Thomas Fan`_.\n+\n - |Efficiency| In :class:`cluster.KMeans`, the default ``algorithm`` is now\n ``\"lloyd\"`` which is the full classical EM-style algorithm. Both ``\"auto\"``\n and ``\"full\"`` are deprecated and will be removed in version 1.3. They are\n" } ]
1.01
49043fc769d0affc92e3641d2d5f8f8de2421611
[ "sklearn/cluster/tests/test_birch.py::test_birch_params_validation[params0-ValueError-threshold == -1.0, must be > 0.0.]", "sklearn/cluster/tests/test_birch.py::test_birch_params_validation[params6-ValueError-n_clusters == 0, must be >= 1.]", "sklearn/cluster/tests/test_birch.py::test_birch_fit_attributes_deprecated[fit_]", "sklearn/cluster/tests/test_birch.py::test_birch_n_clusters_long_int", "sklearn/cluster/tests/test_birch.py::test_birch_params_validation[params7-TypeError-n_clusters must be an instance of <class 'numbers.Integral'>, not <class 'float'>.]", "sklearn/cluster/tests/test_birch.py::test_n_samples_leaves_roots", "sklearn/cluster/tests/test_birch.py::test_sparse_X", "sklearn/cluster/tests/test_birch.py::test_branching_factor", "sklearn/cluster/tests/test_birch.py::test_birch_params_validation[params5-ValueError-branching_factor == -2, must be > 1.]", "sklearn/cluster/tests/test_birch.py::test_birch_params_validation[params3-ValueError-branching_factor == 1, must be > 1.]", "sklearn/cluster/tests/test_birch.py::test_birch_params_validation[params1-ValueError-threshold == 0.0, must be > 0.0.]", "sklearn/cluster/tests/test_birch.py::test_partial_fit", "sklearn/cluster/tests/test_birch.py::test_threshold", "sklearn/cluster/tests/test_birch.py::test_partial_fit_second_call_error_checks", "sklearn/cluster/tests/test_birch.py::test_birch_params_validation[params8-TypeError-n_clusters should be an instance of ClusterMixin or an int]", "sklearn/cluster/tests/test_birch.py::test_birch_predict", "sklearn/cluster/tests/test_birch.py::test_birch_params_validation[params2-ValueError-branching_factor == 0, must be > 1.]", "sklearn/cluster/tests/test_birch.py::test_birch_params_validation[params9-ValueError-n_clusters == -3, must be >= 1.]", "sklearn/cluster/tests/test_birch.py::test_n_clusters", "sklearn/cluster/tests/test_birch.py::test_birch_fit_attributes_deprecated[partial_fit_]", "sklearn/cluster/tests/test_birch.py::test_birch_params_validation[params4-TypeError-branching_factor must be an instance of <class 'numbers.Integral'>, not <class 'float'>.]" ]
[ "sklearn/cluster/tests/test_feature_agglomeration.py::test_feature_agglomeration_feature_names_out", "sklearn/cluster/tests/test_birch.py::test_feature_names_out" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 61e074e56a657..ef2308997f898 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -95,6 +95,10 @@ Changelog\n See :func:`cluster.spectral_clustering` for more details.\n :pr:`<PRID>` by :user:`<NAME>`\n \n+- |Enhancement| Adds :term:`get_feature_names_out` to :class:`cluster.Birch`,\n+ :class:`cluster.FeatureAgglomeration`, :class:`cluster.KMeans`,\n+ :class:`cluster.MiniBatchKMeans`. :pr:`<PRID>` by `<NAME>`_.\n+\n - |Efficiency| In :class:`cluster.KMeans`, the default ``algorithm`` is now\n ``\"lloyd\"`` which is the full classical EM-style algorithm. Both ``\"auto\"``\n and ``\"full\"`` are deprecated and will be removed in version 1.3. They are\n" } ]
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 61e074e56a657..ef2308997f898 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -95,6 +95,10 @@ Changelog See :func:`cluster.spectral_clustering` for more details. :pr:`<PRID>` by :user:`<NAME>` +- |Enhancement| Adds :term:`get_feature_names_out` to :class:`cluster.Birch`, + :class:`cluster.FeatureAgglomeration`, :class:`cluster.KMeans`, + :class:`cluster.MiniBatchKMeans`. :pr:`<PRID>` by `<NAME>`_. + - |Efficiency| In :class:`cluster.KMeans`, the default ``algorithm`` is now ``"lloyd"`` which is the full classical EM-style algorithm. Both ``"auto"`` and ``"full"`` are deprecated and will be removed in version 1.3. They are
scikit-learn/scikit-learn
scikit-learn__scikit-learn-20811
https://github.com/scikit-learn/scikit-learn/pull/20811
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 61d5c64255f71..eb7133b510c81 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -210,6 +210,12 @@ Changelog :mod:`sklearn.ensemble` ....................... +- |Enhancement| :class:`ensemble.HistGradientBoostingClassifier` is faster, + for binary and in particular for multiclass problems thanks to the new private loss + function module. + :pr:`20811`, :pr:`20567` and :pr:`21814` by + :user:`Christian Lorentzen <lorentzenchr>`. + - |API| Changed the default of :func:`max_features` to 1.0 for :class:`ensemble.RandomForestRegressor` and to `"sqrt"` for :class:`ensemble.RandomForestClassifier`. Note that these give the same fit diff --git a/sklearn/_loss/loss.py b/sklearn/_loss/loss.py index d883c0e1bd190..1a2353d18df3b 100644 --- a/sklearn/_loss/loss.py +++ b/sklearn/_loss/loss.py @@ -427,7 +427,7 @@ def fit_intercept_only(self, y_true, sample_weight=None): Returns ------- - raw_prediction : float or (n_classes,) + raw_prediction : numpy scalar or array of shape (n_classes,) Raw predictions of an intercept-only model. """ # As default, take weighted average of the target over the samples @@ -461,6 +461,57 @@ def constant_to_optimal_zero(self, y_true, sample_weight=None): """ return np.zeros_like(y_true) + def init_gradient_and_hessian(self, n_samples, dtype=np.float64, order="F"): + """Initialize arrays for gradients and hessians. + + Unless hessians are constant, arrays are initialized with undefined values. + + Parameters + ---------- + n_samples : int + The number of samples, usually passed to `fit()`. + dtype : {np.float64, np.float32}, default=np.float64 + The dtype of the arrays gradient and hessian. + order : {'C', 'F'}, default='F' + Order of the arrays gradient and hessian. The default 'F' makes the arrays + contiguous along samples. + + Returns + ------- + gradient : C-contiguous array of shape (n_samples,) or array of shape \ + (n_samples, n_classes) + Empty array (allocated but not initialized) to be used as argument + gradient_out. + hessian : C-contiguous array of shape (n_samples,), array of shape + (n_samples, n_classes) or shape (1,) + Empty (allocated but not initialized) array to be used as argument + hessian_out. + If constant_hessian is True (e.g. `HalfSquaredError`), the array is + initialized to ``1``. + """ + if dtype not in (np.float32, np.float64): + raise ValueError( + "Valid options for 'dtype' are np.float32 and np.float64. " + f"Got dtype={dtype} instead." + ) + + if self.is_multiclass: + shape = (n_samples, self.n_classes) + else: + shape = (n_samples,) + gradient = np.empty(shape=shape, dtype=dtype, order=order) + + if self.constant_hessian: + # If the hessians are constant, we consider them equal to 1. + # - This is correct for HalfSquaredError + # - For AbsoluteError, hessians are actually 0, but they are + # always ignored anyway. + hessian = np.ones(shape=(1,), dtype=dtype) + else: + hessian = np.empty(shape=shape, dtype=dtype, order=order) + + return gradient, hessian + # Note: Naturally, we would inherit in the following order # class HalfSquaredError(IdentityLink, CyHalfSquaredError, BaseLoss) diff --git a/sklearn/ensemble/_hist_gradient_boosting/_loss.pyx b/sklearn/ensemble/_hist_gradient_boosting/_loss.pyx deleted file mode 100644 index 23e7d2841443b..0000000000000 --- a/sklearn/ensemble/_hist_gradient_boosting/_loss.pyx +++ /dev/null @@ -1,219 +0,0 @@ -# Author: Nicolas Hug - -cimport cython -from cython.parallel import prange -import numpy as np -cimport numpy as np - -from libc.math cimport exp, log - -from .common cimport Y_DTYPE_C -from .common cimport G_H_DTYPE_C - -np.import_array() - - -def _update_gradients_least_squares( - G_H_DTYPE_C [::1] gradients, # OUT - const Y_DTYPE_C [::1] y_true, # IN - const Y_DTYPE_C [::1] raw_predictions, # IN - int n_threads, # IN -): - - cdef: - int n_samples - int i - - n_samples = raw_predictions.shape[0] - for i in prange(n_samples, schedule='static', nogil=True, num_threads=n_threads): - # Note: a more correct expression is 2 * (raw_predictions - y_true) - # but since we use 1 for the constant hessian value (and not 2) this - # is strictly equivalent for the leaves values. - gradients[i] = raw_predictions[i] - y_true[i] - - -def _update_gradients_hessians_least_squares( - G_H_DTYPE_C [::1] gradients, # OUT - G_H_DTYPE_C [::1] hessians, # OUT - const Y_DTYPE_C [::1] y_true, # IN - const Y_DTYPE_C [::1] raw_predictions, # IN - const Y_DTYPE_C [::1] sample_weight, # IN - int n_threads, # IN -): - - cdef: - int n_samples - int i - - n_samples = raw_predictions.shape[0] - for i in prange(n_samples, schedule='static', nogil=True, num_threads=n_threads): - # Note: a more correct exp is 2 * (raw_predictions - y_true) * sample_weight - # but since we use 1 for the constant hessian value (and not 2) this - # is strictly equivalent for the leaves values. - gradients[i] = (raw_predictions[i] - y_true[i]) * sample_weight[i] - hessians[i] = sample_weight[i] - - -def _update_gradients_hessians_least_absolute_deviation( - G_H_DTYPE_C [::1] gradients, # OUT - G_H_DTYPE_C [::1] hessians, # OUT - const Y_DTYPE_C [::1] y_true, # IN - const Y_DTYPE_C [::1] raw_predictions, # IN - const Y_DTYPE_C [::1] sample_weight, # IN - int n_threads, # IN -): - cdef: - int n_samples - int i - - n_samples = raw_predictions.shape[0] - for i in prange(n_samples, schedule='static', nogil=True, num_threads=n_threads): - # gradient = sign(raw_predicition - y_pred) * sample_weight - gradients[i] = sample_weight[i] * (2 * - (y_true[i] - raw_predictions[i] < 0) - 1) - hessians[i] = sample_weight[i] - - -def _update_gradients_least_absolute_deviation( - G_H_DTYPE_C [::1] gradients, # OUT - const Y_DTYPE_C [::1] y_true, # IN - const Y_DTYPE_C [::1] raw_predictions, # IN - int n_threads, # IN -): - cdef: - int n_samples - int i - - n_samples = raw_predictions.shape[0] - for i in prange(n_samples, schedule='static', nogil=True, num_threads=n_threads): - # gradient = sign(raw_predicition - y_pred) - gradients[i] = 2 * (y_true[i] - raw_predictions[i] < 0) - 1 - - -def _update_gradients_hessians_poisson( - G_H_DTYPE_C [::1] gradients, # OUT - G_H_DTYPE_C [::1] hessians, # OUT - const Y_DTYPE_C [::1] y_true, # IN - const Y_DTYPE_C [::1] raw_predictions, # IN - const Y_DTYPE_C [::1] sample_weight, # IN - int n_threads, # IN -): - cdef: - int n_samples - int i - Y_DTYPE_C y_pred - - n_samples = raw_predictions.shape[0] - if sample_weight is None: - for i in prange(n_samples, schedule='static', nogil=True, num_threads=n_threads): - # Note: We use only half of the deviance loss. Therefore, there is - # no factor of 2. - y_pred = exp(raw_predictions[i]) - gradients[i] = (y_pred - y_true[i]) - hessians[i] = y_pred - else: - for i in prange(n_samples, schedule='static', nogil=True, num_threads=n_threads): - # Note: We use only half of the deviance loss. Therefore, there is - # no factor of 2. - y_pred = exp(raw_predictions[i]) - gradients[i] = (y_pred - y_true[i]) * sample_weight[i] - hessians[i] = y_pred * sample_weight[i] - - -def _update_gradients_hessians_binary_crossentropy( - G_H_DTYPE_C [::1] gradients, # OUT - G_H_DTYPE_C [::1] hessians, # OUT - const Y_DTYPE_C [::1] y_true, # IN - const Y_DTYPE_C [::1] raw_predictions, # IN - const Y_DTYPE_C [::1] sample_weight, # IN - int n_threads, # IN -): - cdef: - int n_samples - Y_DTYPE_C p_i # proba that ith sample belongs to positive class - int i - - n_samples = raw_predictions.shape[0] - if sample_weight is None: - for i in prange(n_samples, schedule='static', nogil=True, num_threads=n_threads): - p_i = _cexpit(raw_predictions[i]) - gradients[i] = p_i - y_true[i] - hessians[i] = p_i * (1. - p_i) - else: - for i in prange(n_samples, schedule='static', nogil=True, num_threads=n_threads): - p_i = _cexpit(raw_predictions[i]) - gradients[i] = (p_i - y_true[i]) * sample_weight[i] - hessians[i] = p_i * (1. - p_i) * sample_weight[i] - - -def _update_gradients_hessians_categorical_crossentropy( - G_H_DTYPE_C [:, ::1] gradients, # OUT - G_H_DTYPE_C [:, ::1] hessians, # OUT - const Y_DTYPE_C [::1] y_true, # IN - const Y_DTYPE_C [:, ::1] raw_predictions, # IN - const Y_DTYPE_C [::1] sample_weight, # IN - int n_threads, # IN -): - cdef: - int prediction_dim = raw_predictions.shape[0] - int n_samples = raw_predictions.shape[1] - int k # class index - int i # sample index - Y_DTYPE_C sw - # p[i, k] is the probability that class(ith sample) == k. - # It's the softmax of the raw predictions - Y_DTYPE_C [:, ::1] p = np.empty(shape=(n_samples, prediction_dim)) - Y_DTYPE_C p_i_k - - if sample_weight is None: - for i in prange(n_samples, schedule='static', nogil=True, num_threads=n_threads): - # first compute softmaxes of sample i for each class - for k in range(prediction_dim): - p[i, k] = raw_predictions[k, i] # prepare softmax - _compute_softmax(p, i) - # then update gradients and hessians - for k in range(prediction_dim): - p_i_k = p[i, k] - gradients[k, i] = p_i_k - (y_true[i] == k) - hessians[k, i] = p_i_k * (1. - p_i_k) - else: - for i in prange(n_samples, schedule='static', nogil=True, num_threads=n_threads): - # first compute softmaxes of sample i for each class - for k in range(prediction_dim): - p[i, k] = raw_predictions[k, i] # prepare softmax - _compute_softmax(p, i) - # then update gradients and hessians - sw = sample_weight[i] - for k in range(prediction_dim): - p_i_k = p[i, k] - gradients[k, i] = (p_i_k - (y_true[i] == k)) * sw - hessians[k, i] = (p_i_k * (1. - p_i_k)) * sw - - -cdef inline void _compute_softmax(Y_DTYPE_C [:, ::1] p, const int i) nogil: - """Compute softmaxes of values in p[i, :].""" - # i needs to be passed (and stays constant) because otherwise Cython does - # not generate optimal code - - cdef: - Y_DTYPE_C max_value = p[i, 0] - Y_DTYPE_C sum_exps = 0. - unsigned int k - unsigned prediction_dim = p.shape[1] - - # Compute max value of array for numerical stability - for k in range(1, prediction_dim): - if max_value < p[i, k]: - max_value = p[i, k] - - for k in range(prediction_dim): - p[i, k] = exp(p[i, k] - max_value) - sum_exps += p[i, k] - - for k in range(prediction_dim): - p[i, k] /= sum_exps - - -cdef inline Y_DTYPE_C _cexpit(const Y_DTYPE_C x) nogil: - """Custom expit (logistic sigmoid function)""" - return 1. / (1. + exp(-x)) diff --git a/sklearn/ensemble/_hist_gradient_boosting/gradient_boosting.py b/sklearn/ensemble/_hist_gradient_boosting/gradient_boosting.py index 097ceeeadc588..e7388f62568c8 100644 --- a/sklearn/ensemble/_hist_gradient_boosting/gradient_boosting.py +++ b/sklearn/ensemble/_hist_gradient_boosting/gradient_boosting.py @@ -7,6 +7,15 @@ import numpy as np from timeit import default_timer as time +from ..._loss.loss import ( + _LOSSES, + BaseLoss, + AbsoluteError, + HalfBinomialLoss, + HalfMultinomialLoss, + HalfPoissonLoss, + HalfSquaredError, +) from ...base import BaseEstimator, RegressorMixin, ClassifierMixin, is_classifier from ...utils import check_random_state, resample from ...utils.validation import ( @@ -20,12 +29,54 @@ from ...model_selection import train_test_split from ...preprocessing import LabelEncoder from ._gradient_boosting import _update_raw_predictions -from .common import Y_DTYPE, X_DTYPE, X_BINNED_DTYPE +from .common import Y_DTYPE, X_DTYPE, X_BINNED_DTYPE, G_H_DTYPE from .binning import _BinMapper from .grower import TreeGrower -from .loss import _LOSSES -from .loss import BaseLoss + + +_LOSSES = _LOSSES.copy() +# TODO: Remove least_squares and least_absolute_deviation in v1.2 +_LOSSES.update( + { + "least_squares": HalfSquaredError, + "least_absolute_deviation": AbsoluteError, + "poisson": HalfPoissonLoss, + "binary_crossentropy": HalfBinomialLoss, + "categorical_crossentropy": HalfMultinomialLoss, + } +) + + +def _update_leaves_values(loss, grower, y_true, raw_prediction, sample_weight): + """Update the leaf values to be predicted by the tree. + + Update equals: + loss.fit_intercept_only(y_true - raw_prediction) + + This is only applied if loss.need_update_leaves_values is True. + Note: It only works, if the loss is a function of the residual, as is the + case for AbsoluteError and PinballLoss. Otherwise, one would need to get + the minimum of loss(y_true, raw_prediction + x) in x. A few examples: + - AbsoluteError: median(y_true - raw_prediction). + - PinballLoss: quantile(y_true - raw_prediction). + See also notes about need_update_leaves_values in BaseLoss. + """ + # TODO: Ideally this should be computed in parallel over the leaves using something + # similar to _update_raw_predictions(), but this requires a cython version of + # median(). + for leaf in grower.finalized_leaves: + indices = leaf.sample_indices + if sample_weight is None: + sw = None + else: + sw = sample_weight[indices] + update = loss.fit_intercept_only( + y_true=y_true[indices] - raw_prediction[indices], + sample_weight=sw, + ) + leaf.value = grower.shrinkage * update + # Note that the regularization is ignored here class BaseHistGradientBoosting(BaseEstimator, ABC): @@ -270,9 +321,7 @@ def fit(self, X, y, sample_weight=None): n_threads = _openmp_effective_n_threads() if isinstance(self.loss, str): - self._loss = self._get_loss( - sample_weight=sample_weight, n_threads=n_threads - ) + self._loss = self._get_loss(sample_weight=sample_weight) elif isinstance(self.loss, BaseLoss): self._loss = self.loss @@ -285,6 +334,7 @@ def fit(self, X, y, sample_weight=None): self._use_validation_data = self.validation_fraction is not None if self.do_early_stopping_ and self._use_validation_data: # stratify for classification + # instead of checking predict_proba, loss.n_classes >= 2 would also work stratify = y if hasattr(self._loss, "predict_proba") else None # Save the state of the RNG for the training and validation split. @@ -363,15 +413,17 @@ def fit(self, X, y, sample_weight=None): # initialize raw_predictions: those are the accumulated values # predicted by the trees for the training data. raw_predictions has - # shape (n_trees_per_iteration, n_samples) where + # shape (n_samples, n_trees_per_iteration) where # n_trees_per_iterations is n_classes in multiclass classification, # else 1. - self._baseline_prediction = self._loss.get_baseline_prediction( - y_train, sample_weight_train, self.n_trees_per_iteration_ - ) + # self._baseline_prediction has shape (1, n_trees_per_iteration) + self._baseline_prediction = self._loss.fit_intercept_only( + y_true=y_train, sample_weight=sample_weight_train + ).reshape((1, -1)) raw_predictions = np.zeros( - shape=(self.n_trees_per_iteration_, n_samples), + shape=(n_samples, self.n_trees_per_iteration_), dtype=self._baseline_prediction.dtype, + order="F", ) raw_predictions += self._baseline_prediction @@ -401,19 +453,21 @@ def fit(self, X, y, sample_weight=None): if self._use_validation_data: raw_predictions_val = np.zeros( - shape=(self.n_trees_per_iteration_, X_binned_val.shape[0]), + shape=(X_binned_val.shape[0], self.n_trees_per_iteration_), dtype=self._baseline_prediction.dtype, + order="F", ) raw_predictions_val += self._baseline_prediction self._check_early_stopping_loss( - raw_predictions, - y_train, - sample_weight_train, - raw_predictions_val, - y_val, - sample_weight_val, + raw_predictions=raw_predictions, + y_train=y_train, + sample_weight_train=sample_weight_train, + raw_predictions_val=raw_predictions_val, + y_val=y_val, + sample_weight_val=sample_weight_val, + n_threads=n_threads, ) else: self._scorer = check_scoring(self, self.scoring) @@ -482,11 +536,9 @@ def fit(self, X, y, sample_weight=None): begin_at_stage = self.n_iter_ # initialize gradients and hessians (empty arrays). - # shape = (n_trees_per_iteration, n_samples). - gradients, hessians = self._loss.init_gradients_and_hessians( - n_samples=n_samples, - prediction_dim=self.n_trees_per_iteration_, - sample_weight=sample_weight_train, + # shape = (n_samples, n_trees_per_iteration). + gradient, hessian = self._loss.init_gradient_and_hessian( + n_samples=n_samples, dtype=G_H_DTYPE, order="F" ) for iteration in range(begin_at_stage, self.max_iter): @@ -498,19 +550,44 @@ def fit(self, X, y, sample_weight=None): ) # Update gradients and hessians, inplace - self._loss.update_gradients_and_hessians( - gradients, hessians, y_train, raw_predictions, sample_weight_train - ) + # Note that self._loss expects shape (n_samples,) for + # n_trees_per_iteration = 1 else shape (n_samples, n_trees_per_iteration). + if self._loss.constant_hessian: + self._loss.gradient( + y_true=y_train, + raw_prediction=raw_predictions, + sample_weight=sample_weight_train, + gradient_out=gradient, + n_threads=n_threads, + ) + else: + self._loss.gradient_hessian( + y_true=y_train, + raw_prediction=raw_predictions, + sample_weight=sample_weight_train, + gradient_out=gradient, + hessian_out=hessian, + n_threads=n_threads, + ) # Append a list since there may be more than 1 predictor per iter predictors.append([]) + # 2-d views of shape (n_samples, n_trees_per_iteration_) or (n_samples, 1) + # on gradient and hessian to simplify the loop over n_trees_per_iteration_. + if gradient.ndim == 1: + g_view = gradient.reshape((-1, 1)) + h_view = hessian.reshape((-1, 1)) + else: + g_view = gradient + h_view = hessian + # Build `n_trees_per_iteration` trees. for k in range(self.n_trees_per_iteration_): grower = TreeGrower( - X_binned_train, - gradients[k, :], - hessians[k, :], + X_binned=X_binned_train, + gradients=g_view[:, k], + hessians=h_view[:, k], n_bins=n_bins, n_bins_non_missing=self._bin_mapper.n_bins_non_missing_, has_missing_values=has_missing_values, @@ -530,8 +607,12 @@ def fit(self, X, y, sample_weight=None): acc_compute_hist_time += grower.total_compute_hist_time if self._loss.need_update_leaves_values: - self._loss.update_leaves_values( - grower, y_train, raw_predictions[k, :], sample_weight_train + _update_leaves_values( + loss=self._loss, + grower=grower, + y_true=y_train, + raw_prediction=raw_predictions[:, k], + sample_weight=sample_weight_train, ) predictor = grower.make_predictor( @@ -542,7 +623,7 @@ def fit(self, X, y, sample_weight=None): # Update raw_predictions with the predictions of the newly # created tree. tic_pred = time() - _update_raw_predictions(raw_predictions[k, :], grower, n_threads) + _update_raw_predictions(raw_predictions[:, k], grower, n_threads) toc_pred = time() acc_prediction_time += toc_pred - tic_pred @@ -552,19 +633,20 @@ def fit(self, X, y, sample_weight=None): # Update raw_predictions_val with the newest tree(s) if self._use_validation_data: for k, pred in enumerate(self._predictors[-1]): - raw_predictions_val[k, :] += pred.predict_binned( + raw_predictions_val[:, k] += pred.predict_binned( X_binned_val, self._bin_mapper.missing_values_bin_idx_, n_threads, ) should_early_stop = self._check_early_stopping_loss( - raw_predictions, - y_train, - sample_weight_train, - raw_predictions_val, - y_val, - sample_weight_val, + raw_predictions=raw_predictions, + y_train=y_train, + sample_weight_train=sample_weight_train, + raw_predictions_val=raw_predictions_val, + y_val=y_val, + sample_weight_val=sample_weight_val, + n_threads=n_threads, ) else: @@ -715,19 +797,29 @@ def _check_early_stopping_loss( raw_predictions_val, y_val, sample_weight_val, + n_threads=1, ): """Check if fitting should be early-stopped based on loss. Scores are computed on validation data or on training data. """ - self.train_score_.append( - -self._loss(y_train, raw_predictions, sample_weight_train) + -self._loss( + y_true=y_train, + raw_prediction=raw_predictions, + sample_weight=sample_weight_train, + n_threads=n_threads, + ) ) if self._use_validation_data: self.validation_score_.append( - -self._loss(y_val, raw_predictions_val, sample_weight_val) + -self._loss( + y_true=y_val, + raw_prediction=raw_predictions_val, + sample_weight=sample_weight_val, + n_threads=n_threads, + ) ) return self._should_stop(self.validation_score_) else: @@ -838,7 +930,7 @@ def _raw_predict(self, X, n_threads=None): Returns ------- - raw_predictions : array, shape (n_trees_per_iteration, n_samples) + raw_predictions : array, shape (n_samples, n_trees_per_iteration) The raw predicted values. """ is_binned = getattr(self, "_in_fit", False) @@ -852,8 +944,9 @@ def _raw_predict(self, X, n_threads=None): ) n_samples = X.shape[0] raw_predictions = np.zeros( - shape=(self.n_trees_per_iteration_, n_samples), + shape=(n_samples, self.n_trees_per_iteration_), dtype=self._baseline_prediction.dtype, + order="F", ) raw_predictions += self._baseline_prediction @@ -889,7 +982,7 @@ def _predict_iterations(self, X, predictors, raw_predictions, is_binned, n_threa f_idx_map=f_idx_map, n_threads=n_threads, ) - raw_predictions[k, :] += predict(X) + raw_predictions[:, k] += predict(X) def _staged_raw_predict(self, X): """Compute raw predictions of ``X`` for each iteration. @@ -905,7 +998,7 @@ def _staged_raw_predict(self, X): Yields ------- raw_predictions : generator of ndarray of shape \ - (n_trees_per_iteration, n_samples) + (n_samples, n_trees_per_iteration) The raw predictions of the input samples. The order of the classes corresponds to that in the attribute :term:`classes_`. """ @@ -918,8 +1011,9 @@ def _staged_raw_predict(self, X): ) n_samples = X.shape[0] raw_predictions = np.zeros( - shape=(self.n_trees_per_iteration_, n_samples), + shape=(n_samples, self.n_trees_per_iteration_), dtype=self._baseline_prediction.dtype, + order="F", ) raw_predictions += self._baseline_prediction @@ -983,7 +1077,7 @@ def _more_tags(self): return {"allow_nan": True} @abstractmethod - def _get_loss(self, sample_weight, n_threads): + def _get_loss(self, sample_weight): pass @abstractmethod @@ -1261,7 +1355,7 @@ def predict(self, X): check_is_fitted(self) # Return inverse link of raw predictions after converting # shape (n_samples, 1) to (n_samples,) - return self._loss.inverse_link_function(self._raw_predict(X).ravel()) + return self._loss.link.inverse(self._raw_predict(X).ravel()) def staged_predict(self, X): """Predict regression target for each iteration. @@ -1282,7 +1376,7 @@ def staged_predict(self, X): The predicted values of the input samples, for each iteration. """ for raw_predictions in self._staged_raw_predict(X): - yield self._loss.inverse_link_function(raw_predictions.ravel()) + yield self._loss.link.inverse(raw_predictions.ravel()) def _encode_y(self, y): # Just convert y to the expected dtype @@ -1296,7 +1390,7 @@ def _encode_y(self, y): ) return y - def _get_loss(self, sample_weight, n_threads): + def _get_loss(self, sample_weight): # TODO: Remove in v1.2 if self.loss == "least_squares": warnings.warn( @@ -1305,9 +1399,7 @@ def _get_loss(self, sample_weight, n_threads): "equivalent.", FutureWarning, ) - return _LOSSES["squared_error"]( - sample_weight=sample_weight, n_threads=n_threads - ) + return _LOSSES["squared_error"](sample_weight=sample_weight) elif self.loss == "least_absolute_deviation": warnings.warn( "The loss 'least_absolute_deviation' was deprecated in v1.0 " @@ -1315,11 +1407,9 @@ def _get_loss(self, sample_weight, n_threads): "which is equivalent.", FutureWarning, ) - return _LOSSES["absolute_error"]( - sample_weight=sample_weight, n_threads=n_threads - ) + return _LOSSES["absolute_error"](sample_weight=sample_weight) - return _LOSSES[self.loss](sample_weight=sample_weight, n_threads=n_threads) + return _LOSSES[self.loss](sample_weight=sample_weight) class HistGradientBoostingClassifier(ClassifierMixin, BaseHistGradientBoosting): @@ -1645,9 +1735,9 @@ def decision_function(self, X): classes in multiclass classification. """ decision = self._raw_predict(X) - if decision.shape[0] == 1: + if decision.shape[1] == 1: decision = decision.ravel() - return decision.T + return decision def staged_decision_function(self, X): """Compute decision function of ``X`` for each iteration. @@ -1669,9 +1759,9 @@ def staged_decision_function(self, X): classes corresponds to that in the attribute :term:`classes_`. """ for staged_decision in self._staged_raw_predict(X): - if staged_decision.shape[0] == 1: + if staged_decision.shape[1] == 1: staged_decision = staged_decision.ravel() - yield staged_decision.T + yield staged_decision def _encode_y(self, y): # encode classes into 0 ... n_classes - 1 and sets attributes classes_ @@ -1688,22 +1778,34 @@ def _encode_y(self, y): encoded_y = encoded_y.astype(Y_DTYPE, copy=False) return encoded_y - def _get_loss(self, sample_weight, n_threads): - if self.loss == "categorical_crossentropy" and self.n_trees_per_iteration_ == 1: - raise ValueError( - "'categorical_crossentropy' is not suitable for " - "a binary classification problem. Please use " - "'auto' or 'binary_crossentropy' instead." - ) - + def _get_loss(self, sample_weight): if self.loss == "auto": if self.n_trees_per_iteration_ == 1: - return _LOSSES["binary_crossentropy"]( - sample_weight=sample_weight, n_threads=n_threads - ) + return _LOSSES["binary_crossentropy"](sample_weight=sample_weight) else: return _LOSSES["categorical_crossentropy"]( - sample_weight=sample_weight, n_threads=n_threads + sample_weight=sample_weight, + n_classes=self.n_trees_per_iteration_, ) - return _LOSSES[self.loss](sample_weight=sample_weight, n_threads=n_threads) + if self.loss == "categorical_crossentropy": + if self.n_trees_per_iteration_ == 1: + raise ValueError( + "loss='categorical_crossentropy' is not suitable for " + "a binary classification problem. Please use " + "loss='auto' or loss='binary_crossentropy' instead." + ) + else: + return _LOSSES[self.loss]( + sample_weight=sample_weight, n_classes=self.n_trees_per_iteration_ + ) + else: + if self.n_trees_per_iteration_ > 1: + raise ValueError( + "loss='binary_crossentropy' is not defined for multiclass" + " classification with n_classes=" + f"{self.n_trees_per_iteration_}, use loss=" + "'categorical_crossentropy' instead." + ) + else: + return _LOSSES[self.loss](sample_weight=sample_weight) diff --git a/sklearn/ensemble/_hist_gradient_boosting/loss.py b/sklearn/ensemble/_hist_gradient_boosting/loss.py deleted file mode 100644 index c5870f97f900e..0000000000000 --- a/sklearn/ensemble/_hist_gradient_boosting/loss.py +++ /dev/null @@ -1,466 +0,0 @@ -""" -This module contains the loss classes. - -Specific losses are used for regression, binary classification or multiclass -classification. -""" -# Author: Nicolas Hug - -from abc import ABC, abstractmethod - -import numpy as np -from scipy.special import expit, logsumexp, xlogy - -from .common import Y_DTYPE -from .common import G_H_DTYPE -from ._loss import _update_gradients_least_squares -from ._loss import _update_gradients_hessians_least_squares -from ._loss import _update_gradients_least_absolute_deviation -from ._loss import _update_gradients_hessians_least_absolute_deviation -from ._loss import _update_gradients_hessians_binary_crossentropy -from ._loss import _update_gradients_hessians_categorical_crossentropy -from ._loss import _update_gradients_hessians_poisson -from ...utils._openmp_helpers import _openmp_effective_n_threads -from ...utils.stats import _weighted_percentile - - -class BaseLoss(ABC): - """Base class for a loss.""" - - def __init__(self, hessians_are_constant, n_threads=None): - self.hessians_are_constant = hessians_are_constant - self.n_threads = _openmp_effective_n_threads(n_threads) - - def __call__(self, y_true, raw_predictions, sample_weight): - """Return the weighted average loss""" - return np.average( - self.pointwise_loss(y_true, raw_predictions), weights=sample_weight - ) - - @abstractmethod - def pointwise_loss(self, y_true, raw_predictions): - """Return loss value for each input""" - - # This variable indicates whether the loss requires the leaves values to - # be updated once the tree has been trained. The trees are trained to - # predict a Newton-Raphson step (see grower._finalize_leaf()). But for - # some losses (e.g. least absolute deviation) we need to adjust the tree - # values to account for the "line search" of the gradient descent - # procedure. See the original paper Greedy Function Approximation: A - # Gradient Boosting Machine by Friedman - # (https://statweb.stanford.edu/~jhf/ftp/trebst.pdf) for the theory. - need_update_leaves_values = False - - def init_gradients_and_hessians(self, n_samples, prediction_dim, sample_weight): - """Return initial gradients and hessians. - - Unless hessians are constant, arrays are initialized with undefined - values. - - Parameters - ---------- - n_samples : int - The number of samples passed to `fit()`. - - prediction_dim : int - The dimension of a raw prediction, i.e. the number of trees - built at each iteration. Equals 1 for regression and binary - classification, or K where K is the number of classes for - multiclass classification. - - sample_weight : array-like of shape(n_samples,) default=None - Weights of training data. - - Returns - ------- - gradients : ndarray, shape (prediction_dim, n_samples) - The initial gradients. The array is not initialized. - hessians : ndarray, shape (prediction_dim, n_samples) - If hessians are constant (e.g. for `LeastSquares` loss, the - array is initialized to ``1``. Otherwise, the array is allocated - without being initialized. - """ - shape = (prediction_dim, n_samples) - gradients = np.empty(shape=shape, dtype=G_H_DTYPE) - - if self.hessians_are_constant: - # If the hessians are constant, we consider they are equal to 1. - # - This is correct for the half LS loss - # - For LAD loss, hessians are actually 0, but they are always - # ignored anyway. - hessians = np.ones(shape=(1, 1), dtype=G_H_DTYPE) - else: - hessians = np.empty(shape=shape, dtype=G_H_DTYPE) - - return gradients, hessians - - @abstractmethod - def get_baseline_prediction(self, y_train, sample_weight, prediction_dim): - """Return initial predictions (before the first iteration). - - Parameters - ---------- - y_train : ndarray, shape (n_samples,) - The target training values. - - sample_weight : array-like of shape(n_samples,) default=None - Weights of training data. - - prediction_dim : int - The dimension of one prediction: 1 for binary classification and - regression, n_classes for multiclass classification. - - Returns - ------- - baseline_prediction : float or ndarray, shape (1, prediction_dim) - The baseline prediction. - """ - - @abstractmethod - def update_gradients_and_hessians( - self, gradients, hessians, y_true, raw_predictions, sample_weight - ): - """Update gradients and hessians arrays, inplace. - - The gradients (resp. hessians) are the first (resp. second) order - derivatives of the loss for each sample with respect to the - predictions of model, evaluated at iteration ``i - 1``. - - Parameters - ---------- - gradients : ndarray, shape (prediction_dim, n_samples) - The gradients (treated as OUT array). - - hessians : ndarray, shape (prediction_dim, n_samples) or \ - (1,) - The hessians (treated as OUT array). - - y_true : ndarray, shape (n_samples,) - The true target values or each training sample. - - raw_predictions : ndarray, shape (prediction_dim, n_samples) - The raw_predictions (i.e. values from the trees) of the tree - ensemble at iteration ``i - 1``. - - sample_weight : array-like of shape(n_samples,) default=None - Weights of training data. - """ - - -class LeastSquares(BaseLoss): - """Least squares loss, for regression. - - For a given sample x_i, least squares loss is defined as:: - - loss(x_i) = 0.5 * (y_true_i - raw_pred_i)**2 - - This actually computes the half least squares loss to simplify - the computation of the gradients and get a unit hessian (and be consistent - with what is done in LightGBM). - """ - - def __init__(self, sample_weight, n_threads=None): - # If sample weights are provided, the hessians and gradients - # are multiplied by sample_weight, which means the hessians are - # equal to sample weights. - super().__init__( - hessians_are_constant=sample_weight is None, n_threads=n_threads - ) - - def pointwise_loss(self, y_true, raw_predictions): - # shape (1, n_samples) --> (n_samples,). reshape(-1) is more likely to - # return a view. - raw_predictions = raw_predictions.reshape(-1) - loss = 0.5 * np.power(y_true - raw_predictions, 2) - return loss - - def get_baseline_prediction(self, y_train, sample_weight, prediction_dim): - return np.average(y_train, weights=sample_weight) - - @staticmethod - def inverse_link_function(raw_predictions): - return raw_predictions - - def update_gradients_and_hessians( - self, gradients, hessians, y_true, raw_predictions, sample_weight - ): - # shape (1, n_samples) --> (n_samples,). reshape(-1) is more likely to - # return a view. - raw_predictions = raw_predictions.reshape(-1) - gradients = gradients.reshape(-1) - if sample_weight is None: - _update_gradients_least_squares( - gradients, y_true, raw_predictions, self.n_threads - ) - else: - hessians = hessians.reshape(-1) - _update_gradients_hessians_least_squares( - gradients, - hessians, - y_true, - raw_predictions, - sample_weight, - self.n_threads, - ) - - -class LeastAbsoluteDeviation(BaseLoss): - """Least absolute deviation, for regression. - - For a given sample x_i, the loss is defined as:: - - loss(x_i) = |y_true_i - raw_pred_i| - """ - - def __init__(self, sample_weight, n_threads=None): - # If sample weights are provided, the hessians and gradients - # are multiplied by sample_weight, which means the hessians are - # equal to sample weights. - super().__init__( - hessians_are_constant=sample_weight is None, n_threads=n_threads - ) - - # This variable indicates whether the loss requires the leaves values to - # be updated once the tree has been trained. The trees are trained to - # predict a Newton-Raphson step (see grower._finalize_leaf()). But for - # some losses (e.g. least absolute deviation) we need to adjust the tree - # values to account for the "line search" of the gradient descent - # procedure. See the original paper Greedy Function Approximation: A - # Gradient Boosting Machine by Friedman - # (https://statweb.stanford.edu/~jhf/ftp/trebst.pdf) for the theory. - need_update_leaves_values = True - - def pointwise_loss(self, y_true, raw_predictions): - # shape (1, n_samples) --> (n_samples,). reshape(-1) is more likely to - # return a view. - raw_predictions = raw_predictions.reshape(-1) - loss = np.abs(y_true - raw_predictions) - return loss - - def get_baseline_prediction(self, y_train, sample_weight, prediction_dim): - if sample_weight is None: - return np.median(y_train) - else: - return _weighted_percentile(y_train, sample_weight, 50) - - @staticmethod - def inverse_link_function(raw_predictions): - return raw_predictions - - def update_gradients_and_hessians( - self, gradients, hessians, y_true, raw_predictions, sample_weight - ): - # shape (1, n_samples) --> (n_samples,). reshape(-1) is more likely to - # return a view. - raw_predictions = raw_predictions.reshape(-1) - gradients = gradients.reshape(-1) - if sample_weight is None: - _update_gradients_least_absolute_deviation( - gradients, - y_true, - raw_predictions, - self.n_threads, - ) - else: - hessians = hessians.reshape(-1) - _update_gradients_hessians_least_absolute_deviation( - gradients, - hessians, - y_true, - raw_predictions, - sample_weight, - self.n_threads, - ) - - def update_leaves_values(self, grower, y_true, raw_predictions, sample_weight): - # Update the values predicted by the tree with - # median(y_true - raw_predictions). - # See note about need_update_leaves_values in BaseLoss. - - # TODO: ideally this should be computed in parallel over the leaves - # using something similar to _update_raw_predictions(), but this - # requires a cython version of median() - for leaf in grower.finalized_leaves: - indices = leaf.sample_indices - if sample_weight is None: - median_res = np.median(y_true[indices] - raw_predictions[indices]) - else: - median_res = _weighted_percentile( - y_true[indices] - raw_predictions[indices], - sample_weight=sample_weight[indices], - percentile=50, - ) - leaf.value = grower.shrinkage * median_res - # Note that the regularization is ignored here - - -class Poisson(BaseLoss): - """Poisson deviance loss with log-link, for regression. - - For a given sample x_i, Poisson deviance loss is defined as:: - - loss(x_i) = y_true_i * log(y_true_i/exp(raw_pred_i)) - - y_true_i + exp(raw_pred_i)) - - This actually computes half the Poisson deviance to simplify - the computation of the gradients. - """ - - def __init__(self, sample_weight, n_threads=None): - super().__init__(hessians_are_constant=False, n_threads=n_threads) - - inverse_link_function = staticmethod(np.exp) - - def pointwise_loss(self, y_true, raw_predictions): - # shape (1, n_samples) --> (n_samples,). reshape(-1) is more likely to - # return a view. - raw_predictions = raw_predictions.reshape(-1) - # TODO: For speed, we could remove the constant xlogy(y_true, y_true) - # Advantage of this form: minimum of zero at raw_predictions = y_true. - loss = ( - xlogy(y_true, y_true) - - y_true * (raw_predictions + 1) - + np.exp(raw_predictions) - ) - return loss - - def get_baseline_prediction(self, y_train, sample_weight, prediction_dim): - y_pred = np.average(y_train, weights=sample_weight) - eps = np.finfo(y_train.dtype).eps - y_pred = np.clip(y_pred, eps, None) - return np.log(y_pred) - - def update_gradients_and_hessians( - self, gradients, hessians, y_true, raw_predictions, sample_weight - ): - # shape (1, n_samples) --> (n_samples,). reshape(-1) is more likely to - # return a view. - raw_predictions = raw_predictions.reshape(-1) - gradients = gradients.reshape(-1) - hessians = hessians.reshape(-1) - _update_gradients_hessians_poisson( - gradients, - hessians, - y_true, - raw_predictions, - sample_weight, - self.n_threads, - ) - - -class BinaryCrossEntropy(BaseLoss): - """Binary cross-entropy loss, for binary classification. - - For a given sample x_i, the binary cross-entropy loss is defined as the - negative log-likelihood of the model which can be expressed as:: - - loss(x_i) = log(1 + exp(raw_pred_i)) - y_true_i * raw_pred_i - - See The Elements of Statistical Learning, by Hastie, Tibshirani, Friedman, - section 4.4.1 (about logistic regression). - """ - - def __init__(self, sample_weight, n_threads=None): - super().__init__(hessians_are_constant=False, n_threads=n_threads) - - inverse_link_function = staticmethod(expit) - - def pointwise_loss(self, y_true, raw_predictions): - # shape (1, n_samples) --> (n_samples,). reshape(-1) is more likely to - # return a view. - raw_predictions = raw_predictions.reshape(-1) - # logaddexp(0, x) = log(1 + exp(x)) - loss = np.logaddexp(0, raw_predictions) - y_true * raw_predictions - return loss - - def get_baseline_prediction(self, y_train, sample_weight, prediction_dim): - if prediction_dim > 2: - raise ValueError( - "loss='binary_crossentropy' is not defined for multiclass" - " classification with n_classes=%d, use" - " loss='categorical_crossentropy' instead" % prediction_dim - ) - proba_positive_class = np.average(y_train, weights=sample_weight) - eps = np.finfo(y_train.dtype).eps - proba_positive_class = np.clip(proba_positive_class, eps, 1 - eps) - # log(x / 1 - x) is the anti function of sigmoid, or the link function - # of the Binomial model. - return np.log(proba_positive_class / (1 - proba_positive_class)) - - def update_gradients_and_hessians( - self, gradients, hessians, y_true, raw_predictions, sample_weight - ): - # shape (1, n_samples) --> (n_samples,). reshape(-1) is more likely to - # return a view. - raw_predictions = raw_predictions.reshape(-1) - gradients = gradients.reshape(-1) - hessians = hessians.reshape(-1) - _update_gradients_hessians_binary_crossentropy( - gradients, hessians, y_true, raw_predictions, sample_weight, self.n_threads - ) - - def predict_proba(self, raw_predictions): - # shape (1, n_samples) --> (n_samples,). reshape(-1) is more likely to - # return a view. - raw_predictions = raw_predictions.reshape(-1) - proba = np.empty((raw_predictions.shape[0], 2), dtype=Y_DTYPE) - proba[:, 1] = expit(raw_predictions) - proba[:, 0] = 1 - proba[:, 1] - return proba - - -class CategoricalCrossEntropy(BaseLoss): - """Categorical cross-entropy loss, for multiclass classification. - - For a given sample x_i, the categorical cross-entropy loss is defined as - the negative log-likelihood of the model and generalizes the binary - cross-entropy to more than 2 classes. - """ - - def __init__(self, sample_weight, n_threads=None): - super().__init__(hessians_are_constant=False, n_threads=n_threads) - - def pointwise_loss(self, y_true, raw_predictions): - one_hot_true = np.zeros_like(raw_predictions) - prediction_dim = raw_predictions.shape[0] - for k in range(prediction_dim): - one_hot_true[k, :] = y_true == k - - loss = logsumexp(raw_predictions, axis=0) - ( - one_hot_true * raw_predictions - ).sum(axis=0) - return loss - - def get_baseline_prediction(self, y_train, sample_weight, prediction_dim): - init_value = np.zeros(shape=(prediction_dim, 1), dtype=Y_DTYPE) - eps = np.finfo(y_train.dtype).eps - for k in range(prediction_dim): - proba_kth_class = np.average(y_train == k, weights=sample_weight) - proba_kth_class = np.clip(proba_kth_class, eps, 1 - eps) - init_value[k, :] += np.log(proba_kth_class) - - return init_value - - def update_gradients_and_hessians( - self, gradients, hessians, y_true, raw_predictions, sample_weight - ): - _update_gradients_hessians_categorical_crossentropy( - gradients, hessians, y_true, raw_predictions, sample_weight, self.n_threads - ) - - def predict_proba(self, raw_predictions): - # TODO: This could be done in parallel - # compute softmax (using exp(log(softmax))) - proba = np.exp( - raw_predictions - logsumexp(raw_predictions, axis=0)[np.newaxis, :] - ) - return proba.T - - -_LOSSES = { - "squared_error": LeastSquares, - "absolute_error": LeastAbsoluteDeviation, - "binary_crossentropy": BinaryCrossEntropy, - "categorical_crossentropy": CategoricalCrossEntropy, - "poisson": Poisson, -} diff --git a/sklearn/ensemble/setup.py b/sklearn/ensemble/setup.py index 9f46a7e3cd303..a9594757dbeb2 100644 --- a/sklearn/ensemble/setup.py +++ b/sklearn/ensemble/setup.py @@ -44,12 +44,6 @@ def configuration(parent_package="", top_path=None): include_dirs=[numpy.get_include()], ) - config.add_extension( - "_hist_gradient_boosting._loss", - sources=["_hist_gradient_boosting/_loss.pyx"], - include_dirs=[numpy.get_include()], - ) - config.add_extension( "_hist_gradient_boosting._bitset", sources=["_hist_gradient_boosting/_bitset.pyx"],
diff --git a/sklearn/_loss/tests/test_loss.py b/sklearn/_loss/tests/test_loss.py index 2ad5633037c4a..5426ed296f01a 100644 --- a/sklearn/_loss/tests/test_loss.py +++ b/sklearn/_loss/tests/test_loss.py @@ -991,6 +991,63 @@ def test_predict_proba(loss): ) [email protected]("loss", ALL_LOSSES) [email protected]("sample_weight", [None, "range"]) [email protected]("dtype", (np.float32, np.float64)) [email protected]("order", ("C", "F")) +def test_init_gradient_and_hessians(loss, sample_weight, dtype, order): + """Test that init_gradient_and_hessian works as expected. + + passing sample_weight to a loss correctly influences the constant_hessian + attribute, and consequently the shape of the hessian array. + """ + n_samples = 5 + if sample_weight == "range": + sample_weight = np.ones(n_samples) + loss = loss(sample_weight=sample_weight) + gradient, hessian = loss.init_gradient_and_hessian( + n_samples=n_samples, + dtype=dtype, + order=order, + ) + if loss.constant_hessian: + assert gradient.shape == (n_samples,) + assert hessian.shape == (1,) + elif loss.is_multiclass: + assert gradient.shape == (n_samples, loss.n_classes) + assert hessian.shape == (n_samples, loss.n_classes) + else: + assert hessian.shape == (n_samples,) + assert hessian.shape == (n_samples,) + + assert gradient.dtype == dtype + assert hessian.dtype == dtype + + if order == "C": + assert gradient.flags.c_contiguous + assert hessian.flags.c_contiguous + else: + assert gradient.flags.f_contiguous + assert hessian.flags.f_contiguous + + [email protected]("loss", ALL_LOSSES) [email protected]( + "params, err_msg", + [ + ( + {"dtype": np.int64}, + f"Valid options for 'dtype' are .* Got dtype={np.int64} instead.", + ), + ], +) +def test_init_gradient_and_hessian_raises(loss, params, err_msg): + """Test that init_gradient_and_hessian raises errors for invalid input.""" + loss = loss() + with pytest.raises((ValueError, TypeError), match=err_msg): + gradient, hessian = loss.init_gradient_and_hessian(n_samples=5, **params) + + @pytest.mark.parametrize("loss", LOSS_INSTANCES, ids=loss_instance_name) def test_loss_pickle(loss): """Test that losses can be pickled.""" diff --git a/sklearn/ensemble/_hist_gradient_boosting/tests/test_gradient_boosting.py b/sklearn/ensemble/_hist_gradient_boosting/tests/test_gradient_boosting.py index 79581525b50bb..c3c4816044d3f 100644 --- a/sklearn/ensemble/_hist_gradient_boosting/tests/test_gradient_boosting.py +++ b/sklearn/ensemble/_hist_gradient_boosting/tests/test_gradient_boosting.py @@ -1,6 +1,13 @@ import numpy as np import pytest from numpy.testing import assert_allclose, assert_array_equal +from sklearn._loss.loss import ( + AbsoluteError, + HalfBinomialLoss, + HalfMultinomialLoss, + HalfPoissonLoss, + HalfSquaredError, +) from sklearn.datasets import make_classification, make_regression from sklearn.datasets import make_low_rank_matrix from sklearn.preprocessing import KBinsDiscretizer, MinMaxScaler, OneHotEncoder @@ -15,16 +22,23 @@ from sklearn.ensemble import HistGradientBoostingRegressor from sklearn.ensemble import HistGradientBoostingClassifier -from sklearn.ensemble._hist_gradient_boosting.loss import _LOSSES -from sklearn.ensemble._hist_gradient_boosting.loss import LeastSquares -from sklearn.ensemble._hist_gradient_boosting.loss import BinaryCrossEntropy from sklearn.ensemble._hist_gradient_boosting.grower import TreeGrower from sklearn.ensemble._hist_gradient_boosting.binning import _BinMapper +from sklearn.ensemble._hist_gradient_boosting.common import G_H_DTYPE from sklearn.utils import shuffle from sklearn.utils._openmp_helpers import _openmp_effective_n_threads + n_threads = _openmp_effective_n_threads() +_LOSSES = { + "squared_error": HalfSquaredError, + "absolute_error": AbsoluteError, + "poisson": HalfPoissonLoss, + "binary_crossentropy": HalfBinomialLoss, + "categorical_crossentropy": HalfMultinomialLoss, +} + X_classification, y_classification = make_classification(random_state=0) X_regression, y_regression = make_regression(random_state=0) @@ -572,7 +586,7 @@ def test_crossentropy_binary_problem(): y = [0, 1] gbrt = HistGradientBoostingClassifier(loss="categorical_crossentropy") with pytest.raises( - ValueError, match="'categorical_crossentropy' is not suitable for" + ValueError, match="loss='categorical_crossentropy' is not suitable for" ): gbrt.fit(X, y) @@ -694,15 +708,22 @@ def test_sum_hessians_are_sample_weight(loss_name): bin_mapper = _BinMapper() X_binned = bin_mapper.fit_transform(X) + # While sample weights are supposed to be positive, this still works. sample_weight = rng.normal(size=n_samples) - loss = _LOSSES[loss_name](sample_weight=sample_weight, n_threads=n_threads) - gradients, hessians = loss.init_gradients_and_hessians( - n_samples=n_samples, prediction_dim=1, sample_weight=sample_weight + loss = _LOSSES[loss_name](sample_weight=sample_weight) + gradients, hessians = loss.init_gradient_and_hessian( + n_samples=n_samples, dtype=G_H_DTYPE ) - raw_predictions = rng.normal(size=(1, n_samples)) - loss.update_gradients_and_hessians( - gradients, hessians, y, raw_predictions, sample_weight + gradients, hessians = gradients.reshape((-1, 1)), hessians.reshape((-1, 1)) + raw_predictions = rng.normal(size=(n_samples, 1)) + loss.gradient_hessian( + y_true=y, + raw_prediction=raw_predictions, + sample_weight=sample_weight, + gradient_out=gradients, + hessian_out=hessians, + n_threads=n_threads, ) # build sum_sample_weight which contains the sum of the sample weights at @@ -716,7 +737,9 @@ def test_sum_hessians_are_sample_weight(loss_name): ] # Build histogram - grower = TreeGrower(X_binned, gradients[0], hessians[0], n_bins=bin_mapper.n_bins) + grower = TreeGrower( + X_binned, gradients[:, 0], hessians[:, 0], n_bins=bin_mapper.n_bins + ) histograms = grower.histogram_builder.compute_histograms_brute( grower.root.sample_indices ) @@ -789,13 +812,13 @@ def test_single_node_trees(Est): [ ( HistGradientBoostingClassifier, - BinaryCrossEntropy(sample_weight=None), + HalfBinomialLoss(sample_weight=None), X_classification, y_classification, ), ( HistGradientBoostingRegressor, - LeastSquares(sample_weight=None), + HalfSquaredError(sample_weight=None), X_regression, y_regression, ), diff --git a/sklearn/ensemble/_hist_gradient_boosting/tests/test_loss.py b/sklearn/ensemble/_hist_gradient_boosting/tests/test_loss.py deleted file mode 100644 index 813163802f956..0000000000000 --- a/sklearn/ensemble/_hist_gradient_boosting/tests/test_loss.py +++ /dev/null @@ -1,348 +0,0 @@ -import numpy as np -from numpy.testing import assert_almost_equal -from numpy.testing import assert_allclose -from scipy.optimize import newton -from scipy.special import logit -from sklearn.utils import assert_all_finite -from sklearn.utils.fixes import sp_version, parse_version -import pytest - -from sklearn.ensemble._hist_gradient_boosting.loss import _LOSSES -from sklearn.ensemble._hist_gradient_boosting.common import Y_DTYPE -from sklearn.ensemble._hist_gradient_boosting.common import G_H_DTYPE -from sklearn.utils._testing import skip_if_32bit -from sklearn.utils._openmp_helpers import _openmp_effective_n_threads - -n_threads = _openmp_effective_n_threads() - - -def get_derivatives_helper(loss): - """Return get_gradients() and get_hessians() functions for a given loss.""" - - def get_gradients(y_true, raw_predictions): - # create gradients and hessians array, update inplace, and return - gradients = np.empty_like(raw_predictions, dtype=G_H_DTYPE) - hessians = np.empty_like(raw_predictions, dtype=G_H_DTYPE) - loss.update_gradients_and_hessians( - gradients, hessians, y_true, raw_predictions, None - ) - return gradients - - def get_hessians(y_true, raw_predictions): - # create gradients and hessians array, update inplace, and return - gradients = np.empty_like(raw_predictions, dtype=G_H_DTYPE) - hessians = np.empty_like(raw_predictions, dtype=G_H_DTYPE) - loss.update_gradients_and_hessians( - gradients, hessians, y_true, raw_predictions, None - ) - - if loss.__class__.__name__ == "LeastSquares": - # hessians aren't updated because they're constant: - # the value is 1 (and not 2) because the loss is actually an half - # least squares loss. - hessians = np.full_like(raw_predictions, fill_value=1) - elif loss.__class__.__name__ == "LeastAbsoluteDeviation": - # hessians aren't updated because they're constant - hessians = np.full_like(raw_predictions, fill_value=0) - - return hessians - - return get_gradients, get_hessians - - [email protected]( - "loss, x0, y_true", - [ - ("squared_error", -2.0, 42), - ("squared_error", 117.0, 1.05), - ("squared_error", 0.0, 0.0), - # The argmin of binary_crossentropy for y_true=0 and y_true=1 is resp. -inf - # and +inf due to logit, cf. "complete separation". Therefore, we use - # 0 < y_true < 1. - ("binary_crossentropy", 0.3, 0.1), - ("binary_crossentropy", -12, 0.2), - ("binary_crossentropy", 30, 0.9), - ("poisson", 12.0, 1.0), - ("poisson", 0.0, 2.0), - ("poisson", -22.0, 10.0), - ], -) [email protected]( - sp_version == parse_version("1.2.0"), - reason="bug in scipy 1.2.0, see scipy issue #9608", -) -@skip_if_32bit -def test_derivatives(loss, x0, y_true): - # Check that gradients are zero when the loss is minimized on a single - # value/sample using Halley's method with the first and second order - # derivatives computed by the Loss instance. - # Note that methods of Loss instances operate on arrays while the newton - # root finder expects a scalar or a one-element array for this purpose. - - loss = _LOSSES[loss](sample_weight=None) - y_true = np.array([y_true], dtype=Y_DTYPE) - x0 = np.array([x0], dtype=Y_DTYPE).reshape(1, 1) - get_gradients, get_hessians = get_derivatives_helper(loss) - - def func(x: np.ndarray) -> np.ndarray: - if isinstance(loss, _LOSSES["binary_crossentropy"]): - # Subtract a constant term such that the binary cross entropy - # has its minimum at zero, which is needed for the newton method. - actual_min = loss.pointwise_loss(y_true, logit(y_true)) - return loss.pointwise_loss(y_true, x) - actual_min - else: - return loss.pointwise_loss(y_true, x) - - def fprime(x: np.ndarray) -> np.ndarray: - return get_gradients(y_true, x) - - def fprime2(x: np.ndarray) -> np.ndarray: - return get_hessians(y_true, x) - - optimum = newton(func, x0=x0, fprime=fprime, fprime2=fprime2, maxiter=70, tol=2e-8) - - # Need to ravel arrays because assert_allclose requires matching dimensions - y_true = y_true.ravel() - optimum = optimum.ravel() - assert_allclose(loss.inverse_link_function(optimum), y_true) - assert_allclose(func(optimum), 0, atol=1e-14) - assert_allclose(get_gradients(y_true, optimum), 0, atol=1e-6) - - [email protected]( - "loss, n_classes, prediction_dim", - [ - ("squared_error", 0, 1), - ("absolute_error", 0, 1), - ("binary_crossentropy", 2, 1), - ("categorical_crossentropy", 3, 3), - ("poisson", 0, 1), - ], -) [email protected]( - Y_DTYPE != np.float64, reason="Need 64 bits float precision for numerical checks" -) -def test_numerical_gradients(loss, n_classes, prediction_dim, seed=0): - # Make sure gradients and hessians computed in the loss are correct, by - # comparing with their approximations computed with finite central - # differences. - # See https://en.wikipedia.org/wiki/Finite_difference. - - rng = np.random.RandomState(seed) - n_samples = 100 - if loss in ("squared_error", "absolute_error"): - y_true = rng.normal(size=n_samples).astype(Y_DTYPE) - elif loss in ("poisson"): - y_true = rng.poisson(size=n_samples).astype(Y_DTYPE) - else: - y_true = rng.randint(0, n_classes, size=n_samples).astype(Y_DTYPE) - raw_predictions = rng.normal(size=(prediction_dim, n_samples)).astype(Y_DTYPE) - loss = _LOSSES[loss](sample_weight=None, n_threads=n_threads) - get_gradients, get_hessians = get_derivatives_helper(loss) - - # only take gradients and hessians of first tree / class. - gradients = get_gradients(y_true, raw_predictions)[0, :].ravel() - hessians = get_hessians(y_true, raw_predictions)[0, :].ravel() - - # Approximate gradients - # For multiclass loss, we should only change the predictions of one tree - # (here the first), hence the use of offset[0, :] += eps - # As a softmax is computed, offsetting the whole array by a constant would - # have no effect on the probabilities, and thus on the loss - eps = 1e-9 - offset = np.zeros_like(raw_predictions) - offset[0, :] = eps - f_plus_eps = loss.pointwise_loss(y_true, raw_predictions + offset / 2) - f_minus_eps = loss.pointwise_loss(y_true, raw_predictions - offset / 2) - numerical_gradients = (f_plus_eps - f_minus_eps) / eps - - # Approximate hessians - eps = 1e-4 # need big enough eps as we divide by its square - offset[0, :] = eps - f_plus_eps = loss.pointwise_loss(y_true, raw_predictions + offset) - f_minus_eps = loss.pointwise_loss(y_true, raw_predictions - offset) - f = loss.pointwise_loss(y_true, raw_predictions) - numerical_hessians = (f_plus_eps + f_minus_eps - 2 * f) / eps ** 2 - - assert_allclose(numerical_gradients, gradients, rtol=1e-4, atol=1e-7) - assert_allclose(numerical_hessians, hessians, rtol=1e-4, atol=1e-7) - - -def test_baseline_least_squares(): - rng = np.random.RandomState(0) - - loss = _LOSSES["squared_error"](sample_weight=None) - y_train = rng.normal(size=100) - baseline_prediction = loss.get_baseline_prediction(y_train, None, 1) - assert baseline_prediction.shape == tuple() # scalar - assert baseline_prediction.dtype == y_train.dtype - # Make sure baseline prediction is the mean of all targets - assert_almost_equal(baseline_prediction, y_train.mean()) - assert np.allclose( - loss.inverse_link_function(baseline_prediction), baseline_prediction - ) - - -def test_baseline_absolute_error(): - rng = np.random.RandomState(0) - - loss = _LOSSES["absolute_error"](sample_weight=None) - y_train = rng.normal(size=100) - baseline_prediction = loss.get_baseline_prediction(y_train, None, 1) - assert baseline_prediction.shape == tuple() # scalar - assert baseline_prediction.dtype == y_train.dtype - # Make sure baseline prediction is the median of all targets - assert np.allclose( - loss.inverse_link_function(baseline_prediction), baseline_prediction - ) - assert baseline_prediction == pytest.approx(np.median(y_train)) - - -def test_baseline_poisson(): - rng = np.random.RandomState(0) - - loss = _LOSSES["poisson"](sample_weight=None) - y_train = rng.poisson(size=100).astype(np.float64) - # Sanity check, make sure at least one sample is non-zero so we don't take - # log(0) - assert y_train.sum() > 0 - baseline_prediction = loss.get_baseline_prediction(y_train, None, 1) - assert np.isscalar(baseline_prediction) - assert baseline_prediction.dtype == y_train.dtype - assert_all_finite(baseline_prediction) - # Make sure baseline prediction produces the log of the mean of all targets - assert_almost_equal(np.log(y_train.mean()), baseline_prediction) - - # Test baseline for y_true = 0 - y_train.fill(0.0) - baseline_prediction = loss.get_baseline_prediction(y_train, None, 1) - assert_all_finite(baseline_prediction) - - -def test_baseline_binary_crossentropy(): - rng = np.random.RandomState(0) - - loss = _LOSSES["binary_crossentropy"](sample_weight=None) - for y_train in (np.zeros(shape=100), np.ones(shape=100)): - y_train = y_train.astype(np.float64) - baseline_prediction = loss.get_baseline_prediction(y_train, None, 1) - assert_all_finite(baseline_prediction) - assert np.allclose(loss.inverse_link_function(baseline_prediction), y_train[0]) - - # Make sure baseline prediction is equal to link_function(p), where p - # is the proba of the positive class. We want predict_proba() to return p, - # and by definition - # p = inverse_link_function(raw_prediction) = sigmoid(raw_prediction) - # So we want raw_prediction = link_function(p) = log(p / (1 - p)) - y_train = rng.randint(0, 2, size=100).astype(np.float64) - baseline_prediction = loss.get_baseline_prediction(y_train, None, 1) - assert baseline_prediction.shape == tuple() # scalar - assert baseline_prediction.dtype == y_train.dtype - p = y_train.mean() - assert np.allclose(baseline_prediction, np.log(p / (1 - p))) - - -def test_baseline_categorical_crossentropy(): - rng = np.random.RandomState(0) - - prediction_dim = 4 - loss = _LOSSES["categorical_crossentropy"](sample_weight=None) - for y_train in (np.zeros(shape=100), np.ones(shape=100)): - y_train = y_train.astype(np.float64) - baseline_prediction = loss.get_baseline_prediction( - y_train, None, prediction_dim - ) - assert baseline_prediction.dtype == y_train.dtype - assert_all_finite(baseline_prediction) - - # Same logic as for above test. Here inverse_link_function = softmax and - # link_function = log - y_train = rng.randint(0, prediction_dim + 1, size=100).astype(np.float32) - baseline_prediction = loss.get_baseline_prediction(y_train, None, prediction_dim) - assert baseline_prediction.shape == (prediction_dim, 1) - for k in range(prediction_dim): - p = (y_train == k).mean() - assert np.allclose(baseline_prediction[k, :], np.log(p)) - - [email protected]( - "loss, problem", - [ - ("squared_error", "regression"), - ("absolute_error", "regression"), - ("binary_crossentropy", "classification"), - ("categorical_crossentropy", "classification"), - ("poisson", "poisson_regression"), - ], -) [email protected]("sample_weight", ["ones", "random"]) -def test_sample_weight_multiplies_gradients(loss, problem, sample_weight): - # Make sure that passing sample weights to the gradient and hessians - # computation methods is equivalent to multiplying by the weights. - - rng = np.random.RandomState(42) - n_samples = 1000 - - if loss == "categorical_crossentropy": - n_classes = prediction_dim = 3 - else: - n_classes = prediction_dim = 1 - - if problem == "regression": - y_true = rng.normal(size=n_samples).astype(Y_DTYPE) - elif problem == "poisson_regression": - y_true = rng.poisson(size=n_samples).astype(Y_DTYPE) - else: - y_true = rng.randint(0, n_classes, size=n_samples).astype(Y_DTYPE) - - if sample_weight == "ones": - sample_weight = np.ones(shape=n_samples, dtype=Y_DTYPE) - else: - sample_weight = rng.normal(size=n_samples).astype(Y_DTYPE) - - loss_ = _LOSSES[loss](sample_weight=sample_weight, n_threads=n_threads) - - baseline_prediction = loss_.get_baseline_prediction(y_true, None, prediction_dim) - raw_predictions = np.zeros( - shape=(prediction_dim, n_samples), dtype=baseline_prediction.dtype - ) - raw_predictions += baseline_prediction - - gradients = np.empty(shape=(prediction_dim, n_samples), dtype=G_H_DTYPE) - hessians = np.ones(shape=(prediction_dim, n_samples), dtype=G_H_DTYPE) - loss_.update_gradients_and_hessians( - gradients, hessians, y_true, raw_predictions, None - ) - - gradients_sw = np.empty(shape=(prediction_dim, n_samples), dtype=G_H_DTYPE) - hessians_sw = np.ones(shape=(prediction_dim, n_samples), dtype=G_H_DTYPE) - loss_.update_gradients_and_hessians( - gradients_sw, hessians_sw, y_true, raw_predictions, sample_weight - ) - - assert np.allclose(gradients * sample_weight, gradients_sw) - assert np.allclose(hessians * sample_weight, hessians_sw) - - -def test_init_gradient_and_hessians_sample_weight(): - # Make sure that passing sample_weight to a loss correctly influences the - # hessians_are_constant attribute, and consequently the shape of the - # hessians array. - - prediction_dim = 2 - n_samples = 5 - sample_weight = None - loss = _LOSSES["squared_error"](sample_weight=sample_weight) - _, hessians = loss.init_gradients_and_hessians( - n_samples=n_samples, prediction_dim=prediction_dim, sample_weight=None - ) - assert loss.hessians_are_constant - assert hessians.shape == (1, 1) - - sample_weight = np.ones(n_samples) - loss = _LOSSES["squared_error"](sample_weight=sample_weight) - _, hessians = loss.init_gradients_and_hessians( - n_samples=n_samples, prediction_dim=prediction_dim, sample_weight=sample_weight - ) - assert not loss.hessians_are_constant - assert hessians.shape == (prediction_dim, n_samples)
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 61d5c64255f71..eb7133b510c81 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -210,6 +210,12 @@ Changelog\n :mod:`sklearn.ensemble`\n .......................\n \n+- |Enhancement| :class:`ensemble.HistGradientBoostingClassifier` is faster,\n+ for binary and in particular for multiclass problems thanks to the new private loss\n+ function module.\n+ :pr:`20811`, :pr:`20567` and :pr:`21814` by\n+ :user:`Christian Lorentzen <lorentzenchr>`.\n+\n - |API| Changed the default of :func:`max_features` to 1.0 for\n :class:`ensemble.RandomForestRegressor` and to `\"sqrt\"` for\n :class:`ensemble.RandomForestClassifier`. Note that these give the same fit\n" } ]
1.01
5d7dc4ba327c138cf63be5cd9238200037c1eb13
[ "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_on_specific_values[HalfMultinomialLoss-1.0-[0.2, 0.5, 0.3]-0.93983106084446]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[range-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[None-HalfTweedieLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[None-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_derivatives[squared_error-117.0-1.05]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_pred[loss1-y_pred_success1-y_pred_fail1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[range-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_pred[loss0-y_pred_success0-y_pred_fail0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[range-PinballLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[None-HalfTweedieLoss3]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[ones-HalfTweedieLoss4]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_predict_proba[HalfTweedieLoss5]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[range-HalfTweedieLoss5]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_on_specific_values[HalfBinomialLoss-0.25-1.3862943611198906-1.2628643221541276]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_on_specific_values[HalfMultinomialLoss-0.0-[0.2, 0.5, 0.3]-1.23983106084446]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_predict_proba[HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_binomial_and_multinomial_loss", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[ones-HalfTweedieLoss2]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[range-PinballLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_graceful_squeezing[HalfTweedieLoss5]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[None-HalfTweedieLoss4]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[random-HalfTweedieLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[None-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[random-HalfTweedieLoss2]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[random-HalfTweedieLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[range-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[ones-HalfTweedieLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_graceful_squeezing[PinballLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[range-HalfTweedieLoss5]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_multinomial_loss_fit_intercept_only", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_pred[loss17-y_pred_success17-y_pred_fail17]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[None-HalfTweedieLoss2]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_true[loss4-y_true_success4-y_true_fail4]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_true[loss6-y_true_success6-y_true_fail6]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[range-HalfTweedieLoss5]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_pred[loss14-y_pred_success14-y_pred_fail14]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_derivatives[squared_error--2.0-42]", "sklearn/_loss/tests/test_loss.py::test_graceful_squeezing[HalfTweedieLoss3]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[range-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[ones-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary[HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[range-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_pred[loss13-y_pred_success13-y_pred_fail13]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[range-PinballLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_pickle[HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[range-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[range-PinballLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[range-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[None-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_pred[loss3-y_pred_success3-y_pred_fail3]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_graceful_squeezing[AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[None-HalfTweedieLoss5]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[range-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[None-HalfTweedieLoss4]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[range-HalfTweedieLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[random-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_specific_fit_intercept_only[loss4-mean-exponential]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[ones-PinballLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_on_specific_values[HalfGammaLoss-2.0-1.3862943611198906-1.8862943611198906]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary[HalfTweedieLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary[HalfTweedieLoss2]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_true[loss14-y_true_success14-y_true_fail14]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary[AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[range-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[None-PinballLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[range-HalfTweedieLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[range-HalfTweedieLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[None-HalfTweedieLoss4]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[range-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[range-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[None-HalfTweedieLoss3]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_pred[loss15-y_pred_success15-y_pred_fail15]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[None-HalfTweedieLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[None-HalfTweedieLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_pickle[HalfTweedieLoss3]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[range-HalfTweedieLoss3]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[range-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[ones-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[None-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_specific_fit_intercept_only[loss1-median-normal]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[range-HalfTweedieLoss2]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_specific_fit_intercept_only[loss0-mean-normal]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_predict_proba[PinballLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[range-HalfTweedieLoss3]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[range-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[random-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[range-HalfTweedieLoss2]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[range-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_graceful_squeezing[HalfTweedieLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[random-HalfTweedieLoss4]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary[HalfTweedieLoss4]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_predict_proba[AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_predict_proba[HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[range-HalfTweedieLoss4]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[None-PinballLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_true[loss9-y_true_success9-y_true_fail9]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_derivatives[binomial_loss--12-0.2]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[ones-HalfTweedieLoss5]", "sklearn/_loss/tests/test_loss.py::test_loss_on_specific_values[HalfSquaredError-1.0-5.0-8]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_pickle[HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[range-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[random-HalfTweedieLoss3]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_pred[loss7-y_pred_success7-y_pred_fail7]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[range-PinballLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_true[loss2-y_true_success2-y_true_fail2]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[range-HalfTweedieLoss4]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_pred[loss2-y_pred_success2-y_pred_fail2]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[None-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[range-HalfTweedieLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[ones-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_derivatives[poisson_loss--22.0-10.0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[random-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_graceful_squeezing[PinballLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[None-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_predict_proba[HalfTweedieLoss3]", "sklearn/_loss/tests/test_loss.py::test_predict_proba[HalfTweedieLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_true[loss16-y_true_success16-y_true_fail16]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[random-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_pred[loss16-y_pred_success16-y_pred_fail16]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_true[loss5-y_true_success5-y_true_fail5]", "sklearn/_loss/tests/test_loss.py::test_derivatives[binomial_loss-30-0.9]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[None-HalfTweedieLoss5]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[None-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_pred[loss10-y_pred_success10-y_pred_fail10]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[range-PinballLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary[HalfTweedieLoss3]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[range-HalfTweedieLoss4]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[None-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_derivatives[binomial_loss-0.3-0.1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[None-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary[HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_graceful_squeezing[HalfTweedieLoss4]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[None-HalfTweedieLoss2]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[None-PinballLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_pred[loss4-y_pred_success4-y_pred_fail4]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[None-HalfTweedieLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[range-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[range-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[None-PinballLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[None-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[range-HalfTweedieLoss3]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[range-HalfTweedieLoss3]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[None-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[range-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_pickle[PinballLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[None-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_pickle[HalfTweedieLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[None-PinballLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary[HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[None-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[ones-HalfTweedieLoss3]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[None-PinballLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_true[loss17-y_true_success17-y_true_fail17]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[None-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[range-HalfTweedieLoss4]", "sklearn/_loss/tests/test_loss.py::test_predict_proba[PinballLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[None-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[range-HalfTweedieLoss4]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[None-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[None-HalfTweedieLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_pickle[HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_graceful_squeezing[HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[ones-HalfTweedieLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_predict_proba[HalfTweedieLoss4]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[None-PinballLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_graceful_squeezing[HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[range-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_specific_fit_intercept_only[loss2-<lambda>-normal]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[ones-PinballLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[None-HalfTweedieLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[range-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_predict_proba[HalfTweedieLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_pickle[HalfTweedieLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_true[loss15-y_true_success15-y_true_fail15]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary[HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_specific_fit_intercept_only[loss3-mean-poisson]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[range-HalfTweedieLoss3]", "sklearn/_loss/tests/test_loss.py::test_graceful_squeezing[HalfTweedieLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_on_specific_values[HalfTweedieLoss-2.0-1.3862943611198906--0.1875]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_true[loss10-y_true_success10-y_true_fail10]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[range-HalfTweedieLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[None-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[None-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_specific_fit_intercept_only[loss6-mean-binomial]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_pickle[HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_true[loss13-y_true_success13-y_true_fail13]", "sklearn/_loss/tests/test_loss.py::test_loss_on_specific_values[HalfMultinomialLoss-2.0-[0.2, 0.5, 0.3]-1.13983106084446]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[None-HalfTweedieLoss2]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_derivatives[squared_error-0.0-0.0]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[range-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_graceful_squeezing[HalfTweedieLoss2]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_pickle[AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[range-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[range-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_pred[loss5-y_pred_success5-y_pred_fail5]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[None-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[range-HalfTweedieLoss2]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_graceful_squeezing[HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[range-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[range-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_pickle[HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[range-PinballLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[None-HalfTweedieLoss4]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[None-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_true[loss7-y_true_success7-y_true_fail7]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[None-HalfTweedieLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary[HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[None-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_true[loss11-y_true_success11-y_true_fail11]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[range-HalfTweedieLoss5]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[None-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[None-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[random-PinballLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[None-HalfTweedieLoss3]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary[HalfTweedieLoss1]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[None-HalfTweedieLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_derivatives[poisson_loss-12.0-1.0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_pickle[PinballLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[random-PinballLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[None-HalfTweedieLoss5]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[range-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[range-PinballLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_true[loss1-y_true_success1-y_true_fail1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_graceful_squeezing[HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[ones-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_pred[loss9-y_pred_success9-y_pred_fail9]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[range-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[None-HalfTweedieLoss5]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[random-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_on_specific_values[PinballLoss-1.0-5.0-2]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[random-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[range-HalfTweedieLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[None-HalfTweedieLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[range-HalfTweedieLoss2]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[None-HalfTweedieLoss3]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[random-HalfTweedieLoss5]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[None-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[range-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[None-PinballLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_true[loss8-y_true_success8-y_true_fail8]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[None-HalfTweedieLoss3]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_pickle[HalfTweedieLoss2]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_pickle[HalfTweedieLoss4]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[range-HalfTweedieLoss2]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[range-HalfTweedieLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_pred[loss6-y_pred_success6-y_pred_fail6]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_pickle[HalfTweedieLoss5]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[range-PinballLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_pred[loss8-y_pred_success8-y_pred_fail8]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_on_specific_values[HalfPoissonLoss-2.0-1.3862943611198906-1.2274112777602189]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[None-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_predict_proba[HalfTweedieLoss2]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary[PinballLoss0]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[range-PinballLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[None-HalfTweedieLoss5]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_on_specific_values[PinballLoss-1.0-5.0-3.0]", "sklearn/_loss/tests/test_loss.py::test_predict_proba[HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[None-PinballLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[None-PinballLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[None-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[range-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_on_specific_values[AbsoluteError-1.0-5.0-4]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_specific_fit_intercept_only[loss5-mean-exponential]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[None-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[None-HalfTweedieLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_on_specific_values[PinballLoss-5.0-1.0-1.0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_pred[loss12-y_pred_success12-y_pred_fail12]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[range-HalfTweedieLoss5]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary[PinballLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_true[loss12-y_true_success12-y_true_fail12]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_true[loss0-y_true_success0-y_true_fail0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_predict_proba[HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_graceful_squeezing[HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[None-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_pred[loss11-y_pred_success11-y_pred_fail11]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[None-HalfTweedieLoss2]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[range-HalfTweedieLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[None-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_true[loss3-y_true_success3-y_true_fail3]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_derivatives[poisson_loss-0.0-2.0]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[ones-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_predict_proba[HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[range-HalfTweedieLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[ones-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[range-HalfTweedieLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[None-HalfTweedieLoss4]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[range-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[None-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[None-HalfTweedieLoss2]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary[HalfTweedieLoss5]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float32-True-HalfPoissonLoss]" ]
[ "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float64-range-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float32-None-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float32-range-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float32-range-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float32-None-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float64-None-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float32-None-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float64-None-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float32-range-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float32-range-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float32-None-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float64-range-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float64-None-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float32-range-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float32-None-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float64-None-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float32-None-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float32-None-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float32-range-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float64-None-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float32-range-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessian_raises[params0-Valid options for 'dtype' are .* Got dtype=<class 'numpy.int64'> instead.-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float64-range-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float64-None-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float64-range-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float64-None-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float64-range-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float32-None-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessian_raises[params0-Valid options for 'dtype' are .* Got dtype=<class 'numpy.int64'> instead.-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float64-None-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float64-None-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessian_raises[params0-Valid options for 'dtype' are .* Got dtype=<class 'numpy.int64'> instead.-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float64-range-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float32-range-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float64-None-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float32-range-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float32-None-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float64-range-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float64-range-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float32-None-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float32-range-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float64-range-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessian_raises[params0-Valid options for 'dtype' are .* Got dtype=<class 'numpy.int64'> instead.-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float32-range-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float64-range-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessian_raises[params0-Valid options for 'dtype' are .* Got dtype=<class 'numpy.int64'> instead.-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float32-range-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float64-range-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float32-range-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float64-range-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float32-None-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float32-range-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float32-None-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float64-None-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float32-range-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessian_raises[params0-Valid options for 'dtype' are .* Got dtype=<class 'numpy.int64'> instead.-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float32-None-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float32-None-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float32-range-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float32-None-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float64-None-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float64-None-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessian_raises[params0-Valid options for 'dtype' are .* Got dtype=<class 'numpy.int64'> instead.-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessian_raises[params0-Valid options for 'dtype' are .* Got dtype=<class 'numpy.int64'> instead.-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float64-range-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float64-range-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float64-None-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float64-None-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float32-None-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float64-None-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float64-range-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float64-range-HalfTweedieLoss]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 61d5c64255f71..eb7133b510c81 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -210,6 +210,12 @@ Changelog\n :mod:`sklearn.ensemble`\n .......................\n \n+- |Enhancement| :class:`ensemble.HistGradientBoostingClassifier` is faster,\n+ for binary and in particular for multiclass problems thanks to the new private loss\n+ function module.\n+ :pr:`<PRID>`, :pr:`<PRID>` and :pr:`<PRID>` by\n+ :user:`<NAME>`.\n+\n - |API| Changed the default of :func:`max_features` to 1.0 for\n :class:`ensemble.RandomForestRegressor` and to `\"sqrt\"` for\n :class:`ensemble.RandomForestClassifier`. Note that these give the same fit\n" } ]
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 61d5c64255f71..eb7133b510c81 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -210,6 +210,12 @@ Changelog :mod:`sklearn.ensemble` ....................... +- |Enhancement| :class:`ensemble.HistGradientBoostingClassifier` is faster, + for binary and in particular for multiclass problems thanks to the new private loss + function module. + :pr:`<PRID>`, :pr:`<PRID>` and :pr:`<PRID>` by + :user:`<NAME>`. + - |API| Changed the default of :func:`max_features` to 1.0 for :class:`ensemble.RandomForestRegressor` and to `"sqrt"` for :class:`ensemble.RandomForestClassifier`. Note that these give the same fit
scikit-learn/scikit-learn
scikit-learn__scikit-learn-22137
https://github.com/scikit-learn/scikit-learn/pull/22137
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index f0ccdc999c175..4be3104771cba 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -493,6 +493,11 @@ Changelog :class:`kernel_approximation.RBFSampler`, and :class:`kernel_approximation.SkewedChi2Sampler`. :pr:`22694` by `Thomas Fan`_. +- |API| Adds :term:`get_feature_names_out` to the following transformers + of the :mod:`~sklearn.kernel_approximation` module: + :class:`~sklearn.kernel_approximation.AdditiveChi2Sampler`. + :pr:`22137` by `Thomas Fan`_. + :mod:`sklearn.linear_model` ........................... diff --git a/sklearn/kernel_approximation.py b/sklearn/kernel_approximation.py index 8418e99d1667e..1e4f4c6aa1301 100644 --- a/sklearn/kernel_approximation.py +++ b/sklearn/kernel_approximation.py @@ -25,6 +25,7 @@ from .utils import check_random_state from .utils.extmath import safe_sparse_dot from .utils.validation import check_is_fitted +from .utils.validation import _check_feature_names_in from .metrics.pairwise import pairwise_kernels, KERNEL_PARAMS from .utils.validation import check_non_negative @@ -664,6 +665,33 @@ def transform(self, X): transf = self._transform_sparse if sparse else self._transform_dense return transf(X) + def get_feature_names_out(self, input_features=None): + """Get output feature names for transformation. + + Parameters + ---------- + input_features : array-like of str or None, default=None + Only used to validate feature names with the names seen in :meth:`fit`. + + Returns + ------- + feature_names_out : ndarray of str objects + Transformed feature names. + """ + input_features = _check_feature_names_in( + self, input_features, generate_names=True + ) + est_name = self.__class__.__name__.lower() + + names_list = [f"{est_name}_{name}_sqrt" for name in input_features] + + for j in range(1, self.sample_steps): + cos_names = [f"{est_name}_{name}_cos{j}" for name in input_features] + sin_names = [f"{est_name}_{name}_sin{j}" for name in input_features] + names_list.extend(cos_names + sin_names) + + return np.asarray(names_list, dtype=object) + def _transform_dense(self, X): non_zero = X != 0.0 X_nz = X[non_zero]
diff --git a/sklearn/tests/test_kernel_approximation.py b/sklearn/tests/test_kernel_approximation.py index 75b64d4087587..456a7f49ce6ff 100644 --- a/sklearn/tests/test_kernel_approximation.py +++ b/sklearn/tests/test_kernel_approximation.py @@ -360,3 +360,33 @@ def test_get_feature_names_out(Estimator): class_name = Estimator.__name__.lower() expected_names = [f"{class_name}{i}" for i in range(X_trans.shape[1])] assert_array_equal(names_out, expected_names) + + +def test_additivechi2sampler_get_feature_names_out(): + """Check get_feature_names_out for for AdditiveChi2Sampler.""" + rng = np.random.RandomState(0) + X = rng.random_sample(size=(300, 3)) + + chi2_sampler = AdditiveChi2Sampler(sample_steps=3).fit(X) + input_names = ["f0", "f1", "f2"] + suffixes = [ + "f0_sqrt", + "f1_sqrt", + "f2_sqrt", + "f0_cos1", + "f1_cos1", + "f2_cos1", + "f0_sin1", + "f1_sin1", + "f2_sin1", + "f0_cos2", + "f1_cos2", + "f2_cos2", + "f0_sin2", + "f1_sin2", + "f2_sin2", + ] + + names_out = chi2_sampler.get_feature_names_out(input_features=input_names) + expected_names = [f"additivechi2sampler_{suffix}" for suffix in suffixes] + assert_array_equal(names_out, expected_names)
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex f0ccdc999c175..4be3104771cba 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -493,6 +493,11 @@ Changelog\n :class:`kernel_approximation.RBFSampler`, and\n :class:`kernel_approximation.SkewedChi2Sampler`. :pr:`22694` by `Thomas Fan`_.\n \n+- |API| Adds :term:`get_feature_names_out` to the following transformers \n+ of the :mod:`~sklearn.kernel_approximation` module:\n+ :class:`~sklearn.kernel_approximation.AdditiveChi2Sampler`.\n+ :pr:`22137` by `Thomas Fan`_.\n+\n :mod:`sklearn.linear_model`\n ...........................\n \n" } ]
1.01
d616e43947340e152e4a901931e954d699368fa9
[ "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-1-2.5-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-3-1-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-1-0.1-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_nystroem_poly_kernel_params", "sklearn/tests/test_kernel_approximation.py::test_get_feature_names_out[RBFSampler]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-3-2.5-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-3-0.1-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-3-1-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-2-1-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-1-0.1-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-3-1-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-1-1-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_skewed_chi2_sampler", "sklearn/tests/test_kernel_approximation.py::test_nystroem_singular_kernel", "sklearn/tests/test_kernel_approximation.py::test_get_feature_names_out[SkewedChi2Sampler]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-1-2.5-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-3-2.5-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-2-0.1-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-1-2.5-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-3-0.1-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-1-1-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-1-1-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-1-1-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-2-2.5-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-1-2.5-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_nystroem_precomputed_kernel", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-2-1-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-2-0.1-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-1-0.1-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-3-2.5-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-1-2.5-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-1-2.5-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-3-0.1-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-3-2.5-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-1-2.5-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-2-2.5-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-2-1-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-1-1-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-2-1-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-1-2.5-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-3-2.5-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-2-1-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-2-2.5-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-3-1-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-3-2.5-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-1-1-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-2-0.1-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-3-1-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-2-1-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-2-2.5-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-1-0.1-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-2-0.1-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-2-2.5-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-2-0.1-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-2-2.5-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-1-1-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch_raises_if_degree_lower_than_one[0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-3-1-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-3-1-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-2-0.1-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_rbf_sampler", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-3-0.1-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-2-0.1-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-2-2.5-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-1-0.1-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-2-1-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-3-1-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-2-2.5-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-1-0.1-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-3-0.1-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-2-1-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-1-2.5-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-2-2.5-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-3-1-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-3-1-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-1-1-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-2-0.1-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-2-0.1-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-1-0.1-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-1-0.1-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-3-0.1-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-3-2.5-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_additive_chi2_sampler", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-2-0.1-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_nystroem_callable", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-1-1-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-2-1-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-2-0.1-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-2-1-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-1-0.1-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-1-0.1-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-3-0.1-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-3-1-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-3-0.1-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_additive_chi2_sampler_exceptions", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-3-2.5-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-2-2.5-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-3-1-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-3-2.5-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_nystroem_component_indices", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-1-0.1-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-2-1-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-1-1-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-3-0.1-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_nystroem_default_parameters", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-3-0.1-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-1-0.1-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-2-1-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-3-2.5-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_get_feature_names_out[Nystroem]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-2-0.1-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-3-0.1-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-1-2.5-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-3-0.1-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-3-2.5-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_get_feature_names_out[PolynomialCountSketch]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-1-2.5-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-1-1-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-1-1-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_input_validation", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-3-2.5-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-2-2.5-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-1-2.5-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-2-2.5-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_nystroem_approximation", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch_raises_if_degree_lower_than_one[-1]" ]
[ "sklearn/tests/test_kernel_approximation.py::test_additivechi2sampler_get_feature_names_out" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex f0ccdc999c175..4be3104771cba 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -493,6 +493,11 @@ Changelog\n :class:`kernel_approximation.RBFSampler`, and\n :class:`kernel_approximation.SkewedChi2Sampler`. :pr:`<PRID>` by `<NAME>`_.\n \n+- |API| Adds :term:`get_feature_names_out` to the following transformers \n+ of the :mod:`~sklearn.kernel_approximation` module:\n+ :class:`~sklearn.kernel_approximation.AdditiveChi2Sampler`.\n+ :pr:`<PRID>` by `<NAME>`_.\n+\n :mod:`sklearn.linear_model`\n ...........................\n \n" } ]
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index f0ccdc999c175..4be3104771cba 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -493,6 +493,11 @@ Changelog :class:`kernel_approximation.RBFSampler`, and :class:`kernel_approximation.SkewedChi2Sampler`. :pr:`<PRID>` by `<NAME>`_. +- |API| Adds :term:`get_feature_names_out` to the following transformers + of the :mod:`~sklearn.kernel_approximation` module: + :class:`~sklearn.kernel_approximation.AdditiveChi2Sampler`. + :pr:`<PRID>` by `<NAME>`_. + :mod:`sklearn.linear_model` ...........................
scikit-learn/scikit-learn
scikit-learn__scikit-learn-22808
https://github.com/scikit-learn/scikit-learn/pull/22808
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 10baed44932ab..fdc04fdff88fe 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -618,6 +618,10 @@ Changelog :class:`linear_model.ARDRegression` now preserve float32 dtype. :pr:`9087` by :user:`Arthur Imbert <Henley13>` and :pr:`22525` by :user:`Meekail Zain <micky774>`. +- |Feature| :class:`ElasticNet`, :class:`ElasticNetCV`, :class:`Lasso` and + :class:`LassoCV` support `sample_weight` for sparse input `X`. + :pr:`22808` by :user:`Christian Lorentzen <lorentzenchr>`. + - |Fix| The `coef_` and `intercept_` attributes of :class:`LinearRegression` are now correctly computed in the presence of sample weights when the input is sparse. :pr:`22891` by :user:`Jérémie du Boisberranger <jeremiedbb>`. @@ -625,7 +629,7 @@ Changelog - |Fix| The `coef_` and `intercept_` attributes of :class:`Ridge` with `solver="sparse_cg"` and `solver="lbfgs"` are now correctly computed in the presence of sample weights when the input is sparse. - :pr:`22899` by :user:`Jérémie du Boisberranger <jeremiedbb>`. + :pr:`22899` by :user:`Jérémie du Boisberranger <jeremiedbb>`. :mod:`sklearn.manifold` ....................... diff --git a/sklearn/linear_model/_base.py b/sklearn/linear_model/_base.py index 3a48908fde620..a7dbb00a5f4ce 100644 --- a/sklearn/linear_model/_base.py +++ b/sklearn/linear_model/_base.py @@ -217,7 +217,6 @@ def _preprocess_data( normalize=False, copy=True, sample_weight=None, - return_mean=False, check_input=True, ): """Center and scale data. @@ -231,7 +230,7 @@ def _preprocess_data( X_scale is the L2 norm of X - X_offset. If sample_weight is not None, then the weighted mean of X and y is zero, and not the mean itself. If - return_mean=True, the mean, eventually weighted, is returned, independently + fit_intercept=True, the mean, eventually weighted, is returned, independently of whether X was centered (option used for optimization with sparse data in coordinate_descend). @@ -271,8 +270,6 @@ def _preprocess_data( if fit_intercept: if sp.issparse(X): X_offset, X_var = mean_variance_axis(X, axis=0, weights=sample_weight) - if not return_mean: - X_offset[:] = X.dtype.type(0) else: if normalize: X_offset, X_var, _ = _incremental_mean_and_var( @@ -328,7 +325,18 @@ def _preprocess_data( def _rescale_data(X, y, sample_weight): """Rescale data sample-wise by square root of sample_weight. - For many linear models, this enables easy support for sample_weight. + For many linear models, this enables easy support for sample_weight because + + (y - X w)' S (y - X w) + + with S = diag(sample_weight) becomes + + ||y_rescaled - X_rescaled w||_2^2 + + when setting + + y_rescaled = sqrt(S) y + X_rescaled = sqrt(S) X Returns ------- @@ -687,7 +695,6 @@ def fit(self, X, y, sample_weight=None): normalize=_normalize, copy=self.copy_X, sample_weight=sample_weight, - return_mean=True, ) # Sample weight can be implemented via a simple rescaling. @@ -824,8 +831,8 @@ def _pre_fit( fit_intercept=fit_intercept, normalize=normalize, copy=False, - return_mean=True, check_input=check_input, + sample_weight=sample_weight, ) else: # copy was done in fit if necessary @@ -838,8 +845,11 @@ def _pre_fit( check_input=check_input, sample_weight=sample_weight, ) - if sample_weight is not None: - X, y, _ = _rescale_data(X, y, sample_weight=sample_weight) + # Rescale only in dense case. Sparse cd solver directly deals with + # sample_weight. + if sample_weight is not None: + # This triggers copies anyway. + X, y, _ = _rescale_data(X, y, sample_weight=sample_weight) # FIXME: 'normalize' to be removed in 1.2 if hasattr(precompute, "__array__"): diff --git a/sklearn/linear_model/_cd_fast.pyx b/sklearn/linear_model/_cd_fast.pyx index 19b4d0a6abd10..c64a464a7da9e 100644 --- a/sklearn/linear_model/_cd_fast.pyx +++ b/sklearn/linear_model/_cd_fast.pyx @@ -260,22 +260,45 @@ def enet_coordinate_descent(floating[::1] w, return w, gap, tol, n_iter + 1 -def sparse_enet_coordinate_descent(floating [::1] w, - floating alpha, floating beta, - np.ndarray[floating, ndim=1, mode='c'] X_data, - np.ndarray[int, ndim=1, mode='c'] X_indices, - np.ndarray[int, ndim=1, mode='c'] X_indptr, - np.ndarray[floating, ndim=1] y, - floating[:] X_mean, int max_iter, - floating tol, object rng, bint random=0, - bint positive=0): +def sparse_enet_coordinate_descent( + floating [::1] w, + floating alpha, + floating beta, + np.ndarray[floating, ndim=1, mode='c'] X_data, + np.ndarray[int, ndim=1, mode='c'] X_indices, + np.ndarray[int, ndim=1, mode='c'] X_indptr, + floating[::1] y, + floating[::1] sample_weight, + floating[::1] X_mean, + int max_iter, + floating tol, + object rng, + bint random=0, + bint positive=0, +): """Cython version of the coordinate descent algorithm for Elastic-Net We minimize: - (1/2) * norm(y - X w, 2)^2 + alpha norm(w, 1) + (beta/2) * norm(w, 2)^2 + 1/2 * norm(y - Z w, 2)^2 + alpha * norm(w, 1) + (beta/2) * norm(w, 2)^2 + + where Z = X - X_mean. + With sample weights sw, this becomes + 1/2 * sum(sw * (y - Z w)^2, axis=0) + alpha * norm(w, 1) + + (beta/2) * norm(w, 2)^2 + + and X_mean is the weighted average of X (per column). """ + # Notes for sample_weight: + # For dense X, one centers X and y and then rescales them by sqrt(sample_weight). + # Here, for sparse X, we get the sample_weight averaged center X_mean. We take care + # that every calculation results as if we had rescaled y and X (and therefore also + # X_mean) by sqrt(sample_weight) without actually calculating the square root. + # We work with: + # yw = sample_weight + # R = sample_weight * residual + # norm_cols_X = np.sum(sample_weight * (X - X_mean)**2, axis=0) # get the data information into easy vars cdef unsigned int n_samples = y.shape[0] @@ -289,10 +312,10 @@ def sparse_enet_coordinate_descent(floating [::1] w, cdef unsigned int endptr # initial value of the residuals - cdef floating[:] R = y.copy() - - cdef floating[:] X_T_R - cdef floating[:] XtA + # R = y - Zw, weighted version R = sample_weight * (y - Zw) + cdef floating[::1] R + cdef floating[::1] XtA + cdef floating[::1] yw if floating is float: dtype = np.float32 @@ -300,7 +323,6 @@ def sparse_enet_coordinate_descent(floating [::1] w, dtype = np.float64 norm_cols_X = np.zeros(n_features, dtype=dtype) - X_T_R = np.zeros(n_features, dtype=dtype) XtA = np.zeros(n_features, dtype=dtype) cdef floating tmp @@ -324,6 +346,14 @@ def sparse_enet_coordinate_descent(floating [::1] w, cdef UINT32_t rand_r_state_seed = rng.randint(0, RAND_R_MAX) cdef UINT32_t* rand_r_state = &rand_r_state_seed cdef bint center = False + cdef bint no_sample_weights = sample_weight is None + + if no_sample_weights: + yw = y + R = y.copy() + else: + yw = np.multiply(sample_weight, y) + R = yw.copy() with nogil: # center = (X_mean != 0).any() @@ -338,19 +368,32 @@ def sparse_enet_coordinate_descent(floating [::1] w, normalize_sum = 0.0 w_ii = w[ii] - for jj in range(startptr, endptr): - normalize_sum += (X_data[jj] - X_mean_ii) ** 2 - R[X_indices[jj]] -= X_data[jj] * w_ii - norm_cols_X[ii] = normalize_sum + \ - (n_samples - endptr + startptr) * X_mean_ii ** 2 - - if center: - for jj in range(n_samples): - R[jj] += X_mean_ii * w_ii + if no_sample_weights: + for jj in range(startptr, endptr): + normalize_sum += (X_data[jj] - X_mean_ii) ** 2 + R[X_indices[jj]] -= X_data[jj] * w_ii + norm_cols_X[ii] = normalize_sum + \ + (n_samples - endptr + startptr) * X_mean_ii ** 2 + if center: + for jj in range(n_samples): + R[jj] += X_mean_ii * w_ii + else: + for jj in range(startptr, endptr): + tmp = sample_weight[X_indices[jj]] + # second term will be subtracted by loop over range(n_samples) + normalize_sum += (tmp * (X_data[jj] - X_mean_ii) ** 2 + - tmp * X_mean_ii ** 2) + R[X_indices[jj]] -= tmp * X_data[jj] * w_ii + if center: + for jj in range(n_samples): + normalize_sum += sample_weight[jj] * X_mean_ii ** 2 + R[jj] += sample_weight[jj] * X_mean_ii * w_ii + norm_cols_X[ii] = normalize_sum startptr = endptr # tol *= np.dot(y, y) - tol *= _dot(n_samples, &y[0], 1, &y[0], 1) + # with sample weights: tol *= y @ (sw * y) + tol *= _dot(n_samples, &y[0], 1, &yw[0], 1) for n_iter in range(max_iter): @@ -373,11 +416,19 @@ def sparse_enet_coordinate_descent(floating [::1] w, if w_ii != 0.0: # R += w_ii * X[:,ii] - for jj in range(startptr, endptr): - R[X_indices[jj]] += X_data[jj] * w_ii - if center: - for jj in range(n_samples): - R[jj] -= X_mean_ii * w_ii + if no_sample_weights: + for jj in range(startptr, endptr): + R[X_indices[jj]] += X_data[jj] * w_ii + if center: + for jj in range(n_samples): + R[jj] -= X_mean_ii * w_ii + else: + for jj in range(startptr, endptr): + tmp = sample_weight[X_indices[jj]] + R[X_indices[jj]] += tmp * X_data[jj] * w_ii + if center: + for jj in range(n_samples): + R[jj] -= sample_weight[jj] * X_mean_ii * w_ii # tmp = (X[:,ii] * R).sum() tmp = 0.0 @@ -398,20 +449,25 @@ def sparse_enet_coordinate_descent(floating [::1] w, if w[ii] != 0.0: # R -= w[ii] * X[:,ii] # Update residual - for jj in range(startptr, endptr): - R[X_indices[jj]] -= X_data[jj] * w[ii] - - if center: - for jj in range(n_samples): - R[jj] += X_mean_ii * w[ii] + if no_sample_weights: + for jj in range(startptr, endptr): + R[X_indices[jj]] -= X_data[jj] * w[ii] + if center: + for jj in range(n_samples): + R[jj] += X_mean_ii * w[ii] + else: + for jj in range(startptr, endptr): + tmp = sample_weight[X_indices[jj]] + R[X_indices[jj]] -= tmp * X_data[jj] * w[ii] + if center: + for jj in range(n_samples): + R[jj] += sample_weight[jj] * X_mean_ii * w[ii] # update the maximum absolute coefficient update d_w_ii = fabs(w[ii] - w_ii) - if d_w_ii > d_w_max: - d_w_max = d_w_ii + d_w_max = fmax(d_w_max, d_w_ii) - if fabs(w[ii]) > w_max: - w_max = fabs(w[ii]) + w_max = fmax(w_max, fabs(w[ii])) if w_max == 0.0 or d_w_max / w_max < d_w_tol or n_iter == max_iter - 1: # the biggest coordinate update of this iteration was smaller than @@ -424,14 +480,15 @@ def sparse_enet_coordinate_descent(floating [::1] w, for jj in range(n_samples): R_sum += R[jj] + # XtA = X.T @ R - beta * w for ii in range(n_features): - X_T_R[ii] = 0.0 + XtA[ii] = 0.0 for jj in range(X_indptr[ii], X_indptr[ii + 1]): - X_T_R[ii] += X_data[jj] * R[X_indices[jj]] + XtA[ii] += X_data[jj] * R[X_indices[jj]] if center: - X_T_R[ii] -= X_mean[ii] * R_sum - XtA[ii] = X_T_R[ii] - beta * w[ii] + XtA[ii] -= X_mean[ii] * R_sum + XtA[ii] -= beta * w[ii] if positive: dual_norm_XtA = max(n_features, &XtA[0]) @@ -439,7 +496,14 @@ def sparse_enet_coordinate_descent(floating [::1] w, dual_norm_XtA = abs_max(n_features, &XtA[0]) # R_norm2 = np.dot(R, R) - R_norm2 = _dot(n_samples, &R[0], 1, &R[0], 1) + if no_sample_weights: + R_norm2 = _dot(n_samples, &R[0], 1, &R[0], 1) + else: + R_norm2 = 0.0 + for jj in range(n_samples): + # R is already multiplied by sample_weight + if sample_weight[jj] != 0: + R_norm2 += (R[jj] ** 2) / sample_weight[jj] # w_norm2 = np.dot(w, w) w_norm2 = _dot(n_features, &w[0], 1, &w[0], 1) diff --git a/sklearn/linear_model/_coordinate_descent.py b/sklearn/linear_model/_coordinate_descent.py index 1345ccda58a1d..997d7db41e4ad 100644 --- a/sklearn/linear_model/_coordinate_descent.py +++ b/sklearn/linear_model/_coordinate_descent.py @@ -164,7 +164,7 @@ def _alpha_grid( # Workaround to find alpha_max for sparse matrices. # since we should not destroy the sparsity of such matrices. _, _, X_offset, _, X_scale = _preprocess_data( - X, y, fit_intercept, normalize, return_mean=True + X, y, fit_intercept, normalize ) mean_dot = X_offset * np.sum(y) @@ -499,6 +499,7 @@ def enet_path( """ X_offset_param = params.pop("X_offset", None) X_scale_param = params.pop("X_scale", None) + sample_weight = params.pop("sample_weight", None) tol = params.pop("tol", 1e-4) max_iter = params.pop("max_iter", 1000) random_state = params.pop("random_state", None) @@ -544,14 +545,14 @@ def enet_path( # MultiTaskElasticNet does not support sparse matrices if not multi_output and sparse.isspmatrix(X): if X_offset_param is not None: - # As sparse matrices are not actually centered we need this - # to be passed to the CD solver. + # As sparse matrices are not actually centered we need this to be passed to + # the CD solver. X_sparse_scaling = X_offset_param / X_scale_param X_sparse_scaling = np.asarray(X_sparse_scaling, dtype=X.dtype) else: X_sparse_scaling = np.zeros(n_features, dtype=X.dtype) - # X should be normalized and fit already if function is called + # X should have been passed through _pre_fit already if function is called # from ElasticNet.fit if check_input: X, y, X_offset, y_offset, X_scale, precompute, Xy = _pre_fit( @@ -606,19 +607,20 @@ def enet_path( l2_reg = alpha * (1.0 - l1_ratio) * n_samples if not multi_output and sparse.isspmatrix(X): model = cd_fast.sparse_enet_coordinate_descent( - coef_, - l1_reg, - l2_reg, - X.data, - X.indices, - X.indptr, - y, - X_sparse_scaling, - max_iter, - tol, - rng, - random, - positive, + w=coef_, + alpha=l1_reg, + beta=l2_reg, + X_data=X.data, + X_indices=X.indices, + X_indptr=X.indptr, + y=y, + sample_weight=sample_weight, + X_mean=X_sparse_scaling, + max_iter=max_iter, + tol=tol, + rng=rng, + random=random, + positive=positive, ) elif multi_output: model = cd_fast.enet_coordinate_descent_multi_task( @@ -965,10 +967,6 @@ def fit(self, X, y, sample_weight=None, check_input=True): sample_weight = None if sample_weight is not None: if check_input: - if sparse.issparse(X): - raise ValueError( - "Sample weights do not (yet) support sparse matrices." - ) sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype) # TLDR: Rescale sw to sum up to n_samples. # Long: The objective function of Enet @@ -1057,17 +1055,19 @@ def fit(self, X, y, sample_weight=None, check_input=True): precompute=precompute, Xy=this_Xy, copy_X=True, + coef_init=coef_[k], verbose=False, - tol=self.tol, + return_n_iter=True, positive=self.positive, + check_input=False, + # from here on **params + tol=self.tol, X_offset=X_offset, X_scale=X_scale, - return_n_iter=True, - coef_init=coef_[k], max_iter=self.max_iter, random_state=self.random_state, selection=self.selection, - check_input=False, + sample_weight=sample_weight, ) coef_[k] = this_coef[:, 0] dual_gaps_[k] = this_dual_gap[0] @@ -1421,6 +1421,8 @@ def _path_residuals( path_params["precompute"] = precompute path_params["copy_X"] = False path_params["alphas"] = alphas + # needed for sparse cd solver + path_params["sample_weight"] = sw_train if "l1_ratio" in path_params: path_params["l1_ratio"] = l1_ratio @@ -1609,8 +1611,6 @@ def fit(self, X, y, sample_weight=None): if isinstance(sample_weight, numbers.Number): sample_weight = None if sample_weight is not None: - if sparse.issparse(X): - raise ValueError("Sample weights do not (yet) support sparse matrices.") sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype) model = self._get_estimator() diff --git a/sklearn/linear_model/_ridge.py b/sklearn/linear_model/_ridge.py index a4fe5aadca0a9..900b5f7c221db 100644 --- a/sklearn/linear_model/_ridge.py +++ b/sklearn/linear_model/_ridge.py @@ -805,7 +805,6 @@ def fit(self, X, y, sample_weight=None): self._normalize, self.copy_X, sample_weight=sample_weight, - return_mean=True, ) if solver == "sag" and sparse.issparse(X) and self.fit_intercept: @@ -2011,7 +2010,10 @@ def fit(self, X, y, sample_weight=None): self.dual_coef_ = best_coef self.coef_ = safe_sparse_dot(self.dual_coef_.T, X) - X_offset += X_mean * X_scale + if sparse.issparse(X): + X_offset = X_mean * X_scale + else: + X_offset += X_mean * X_scale self._set_intercept(X_offset, y_offset, X_scale) if self.store_cv_values:
diff --git a/sklearn/linear_model/tests/test_base.py b/sklearn/linear_model/tests/test_base.py index afe316adb9efb..2f7d30a763159 100644 --- a/sklearn/linear_model/tests/test_base.py +++ b/sklearn/linear_model/tests/test_base.py @@ -472,7 +472,6 @@ def test_preprocess_data_weighted(is_sparse): fit_intercept=True, normalize=False, sample_weight=sample_weight, - return_mean=True, ) assert_array_almost_equal(X_mean, expected_X_mean) assert_array_almost_equal(y_mean, expected_y_mean) @@ -490,7 +489,6 @@ def test_preprocess_data_weighted(is_sparse): fit_intercept=True, normalize=True, sample_weight=sample_weight, - return_mean=True, ) assert_array_almost_equal(X_mean, expected_X_mean) @@ -531,7 +529,7 @@ def test_preprocess_data_weighted(is_sparse): assert_array_almost_equal(yt, y - expected_y_mean) -def test_sparse_preprocess_data_with_return_mean(): +def test_sparse_preprocess_data_offsets(): n_samples = 200 n_features = 2 # random_state not supported yet in sparse.rand @@ -542,7 +540,7 @@ def test_sparse_preprocess_data_with_return_mean(): expected_X_scale = np.std(XA, axis=0) * np.sqrt(X.shape[0]) Xt, yt, X_mean, y_mean, X_scale = _preprocess_data( - X, y, fit_intercept=False, normalize=False, return_mean=True + X, y, fit_intercept=False, normalize=False ) assert_array_almost_equal(X_mean, np.zeros(n_features)) assert_array_almost_equal(y_mean, 0) @@ -551,7 +549,7 @@ def test_sparse_preprocess_data_with_return_mean(): assert_array_almost_equal(yt, y) Xt, yt, X_mean, y_mean, X_scale = _preprocess_data( - X, y, fit_intercept=True, normalize=False, return_mean=True + X, y, fit_intercept=True, normalize=False ) assert_array_almost_equal(X_mean, np.mean(XA, axis=0)) assert_array_almost_equal(y_mean, np.mean(y, axis=0)) @@ -560,7 +558,7 @@ def test_sparse_preprocess_data_with_return_mean(): assert_array_almost_equal(yt, y - np.mean(y, axis=0)) Xt, yt, X_mean, y_mean, X_scale = _preprocess_data( - X, y, fit_intercept=True, normalize=True, return_mean=True + X, y, fit_intercept=True, normalize=True ) assert_array_almost_equal(X_mean, np.mean(XA, axis=0)) assert_array_almost_equal(y_mean, np.mean(y, axis=0)) @@ -618,7 +616,6 @@ def test_dtype_preprocess_data(): y_32, fit_intercept=fit_intercept, normalize=normalize, - return_mean=True, ) Xt_64, yt_64, X_mean_64, y_mean_64, X_scale_64 = _preprocess_data( @@ -626,7 +623,6 @@ def test_dtype_preprocess_data(): y_64, fit_intercept=fit_intercept, normalize=normalize, - return_mean=True, ) Xt_3264, yt_3264, X_mean_3264, y_mean_3264, X_scale_3264 = _preprocess_data( @@ -634,7 +630,6 @@ def test_dtype_preprocess_data(): y_64, fit_intercept=fit_intercept, normalize=normalize, - return_mean=True, ) Xt_6432, yt_6432, X_mean_6432, y_mean_6432, X_scale_6432 = _preprocess_data( @@ -642,7 +637,6 @@ def test_dtype_preprocess_data(): y_32, fit_intercept=fit_intercept, normalize=normalize, - return_mean=True, ) assert Xt_32.dtype == np.float32 diff --git a/sklearn/linear_model/tests/test_coordinate_descent.py b/sklearn/linear_model/tests/test_coordinate_descent.py index df118be7c0cb5..e5d7ba358c1f5 100644 --- a/sklearn/linear_model/tests/test_coordinate_descent.py +++ b/sklearn/linear_model/tests/test_coordinate_descent.py @@ -554,9 +554,6 @@ def test_linear_model_sample_weights_normalize_in_pipeline( # a StandardScaler and sample_weight. model_name = estimator.__name__ - if model_name in ["Lasso", "ElasticNet"] and is_sparse: - pytest.skip(f"{model_name} does not support sample_weight with sparse") - rng = np.random.RandomState(0) X, y = make_regression(n_samples=20, n_features=5, noise=1e-2, random_state=rng) @@ -1483,15 +1480,17 @@ def test_multi_task_lasso_cv_dtype(): @pytest.mark.parametrize("fit_intercept", [True, False]) @pytest.mark.parametrize("alpha", [0.01]) [email protected]("normalize", [False, True]) @pytest.mark.parametrize("precompute", [False, True]) -def test_enet_sample_weight_consistency(fit_intercept, alpha, normalize, precompute): [email protected]("sparseX", [False, True]) +def test_enet_sample_weight_consistency(fit_intercept, alpha, precompute, sparseX): """Test that the impact of sample_weight is consistent.""" rng = np.random.RandomState(0) n_samples, n_features = 10, 5 X = rng.rand(n_samples, n_features) y = rng.rand(n_samples) + if sparseX: + X = sparse.csc_matrix(X) params = dict( alpha=alpha, fit_intercept=fit_intercept, @@ -1541,7 +1540,10 @@ def test_enet_sample_weight_consistency(fit_intercept, alpha, normalize, precomp # check that multiplying sample_weight by 2 is equivalent # to repeating corresponding samples twice - X2 = np.concatenate([X, X[: n_samples // 2]], axis=0) + if sparseX: + X2 = sparse.vstack([X, X[: n_samples // 2]], format="csc") + else: + X2 = np.concatenate([X, X[: n_samples // 2]], axis=0) y2 = np.concatenate([y, y[: n_samples // 2]]) sample_weight_1 = np.ones(len(y)) sample_weight_1[: n_samples // 2] = 2 @@ -1549,23 +1551,12 @@ def test_enet_sample_weight_consistency(fit_intercept, alpha, normalize, precomp reg1 = ElasticNet(**params).fit(X, y, sample_weight=sample_weight_1) reg2 = ElasticNet(**params).fit(X2, y2, sample_weight=None) - assert_allclose(reg1.coef_, reg2.coef_) - - [email protected]("estimator", (Lasso, ElasticNet)) -def test_enet_sample_weight_sparse(estimator): - reg = estimator() - X = sparse.csc_matrix(np.zeros((3, 2))) - y = np.array([-1, 0, 1]) - sw = np.array([1, 2, 3]) - with pytest.raises( - ValueError, match="Sample weights do not.*support sparse matrices" - ): - reg.fit(X, y, sample_weight=sw, check_input=True) + assert_allclose(reg1.coef_, reg2.coef_, rtol=1e-6) @pytest.mark.parametrize("fit_intercept", [True, False]) -def test_enet_cv_sample_weight_correctness(fit_intercept): [email protected]("sparseX", [False, True]) +def test_enet_cv_sample_weight_correctness(fit_intercept, sparseX): """Test that ElasticNetCV with sample weights gives correct results.""" rng = np.random.RandomState(42) n_splits, n_samples, n_features = 3, 10, 5 @@ -1574,6 +1565,9 @@ def test_enet_cv_sample_weight_correctness(fit_intercept): beta[0:2] = 0 y = X @ beta + rng.rand(n_splits * n_samples) sw = np.ones_like(y) + if sparseX: + X = sparse.csc_matrix(X) + params = dict(tol=1e-6) # Set alphas, otherwise the two cv models might use different ones. if fit_intercept: @@ -1588,20 +1582,22 @@ def test_enet_cv_sample_weight_correctness(fit_intercept): ] splits_sw = list(LeaveOneGroupOut().split(X, groups=groups_sw)) reg_sw = ElasticNetCV( - alphas=alphas, - cv=splits_sw, - fit_intercept=fit_intercept, + alphas=alphas, cv=splits_sw, fit_intercept=fit_intercept, **params ) reg_sw.fit(X, y, sample_weight=sw) # We repeat the first fold 2 times and provide splits ourselves + if sparseX: + X = X.toarray() X = np.r_[X[:n_samples], X] + if sparseX: + X = sparse.csc_matrix(X) y = np.r_[y[:n_samples], y] groups = np.r_[ np.full(2 * n_samples, 0), np.full(n_samples, 1), np.full(n_samples, 2) ] splits = list(LeaveOneGroupOut().split(X, groups=groups)) - reg = ElasticNetCV(alphas=alphas, cv=splits, fit_intercept=fit_intercept) + reg = ElasticNetCV(alphas=alphas, cv=splits, fit_intercept=fit_intercept, **params) reg.fit(X, y) # ensure that we chose meaningful alphas, i.e. not boundaries @@ -1649,7 +1645,10 @@ def test_enet_cv_grid_search(sample_weight): @pytest.mark.parametrize("fit_intercept", [True, False]) @pytest.mark.parametrize("l1_ratio", [0, 0.5, 1]) @pytest.mark.parametrize("precompute", [False, True]) -def test_enet_cv_sample_weight_consistency(fit_intercept, l1_ratio, precompute): [email protected]("sparseX", [False, True]) +def test_enet_cv_sample_weight_consistency( + fit_intercept, l1_ratio, precompute, sparseX +): """Test that the impact of sample_weight is consistent.""" rng = np.random.RandomState(0) n_samples, n_features = 10, 5 @@ -1663,6 +1662,8 @@ def test_enet_cv_sample_weight_consistency(fit_intercept, l1_ratio, precompute): tol=1e-6, cv=3, ) + if sparseX: + X = sparse.csc_matrix(X) if l1_ratio == 0: params.pop("l1_ratio", None) @@ -1695,18 +1696,6 @@ def test_enet_cv_sample_weight_consistency(fit_intercept, l1_ratio, precompute): assert_allclose(reg.intercept_, intercept) [email protected]("estimator", (LassoCV, ElasticNetCV)) -def test_enet_cv_sample_weight_sparse(estimator): - reg = estimator() - X = sparse.csc_matrix(np.zeros((3, 2))) - y = np.array([-1, 0, 1]) - sw = np.array([1, 2, 3]) - with pytest.raises( - ValueError, match="Sample weights do not.*support sparse matrices" - ): - reg.fit(X, y, sample_weight=sw) - - @pytest.mark.parametrize("estimator", [ElasticNetCV, LassoCV]) def test_linear_models_cv_fit_with_loky(estimator): # LinearModelsCV.fit performs inplace operations on fancy-indexed memmapped diff --git a/sklearn/linear_model/tests/test_sparse_coordinate_descent.py b/sklearn/linear_model/tests/test_sparse_coordinate_descent.py index c51f05f36b84a..b9d87e5207b7e 100644 --- a/sklearn/linear_model/tests/test_sparse_coordinate_descent.py +++ b/sklearn/linear_model/tests/test_sparse_coordinate_descent.py @@ -54,33 +54,38 @@ def test_lasso_zero(): assert_almost_equal(clf.dual_gap_, 0) -def test_enet_toy_list_input(): [email protected]("with_sample_weight", [True, False]) +def test_enet_toy_list_input(with_sample_weight): # Test ElasticNet for various values of alpha and l1_ratio with list X X = np.array([[-1], [0], [1]]) X = sp.csc_matrix(X) Y = [-1, 0, 1] # just a straight line T = np.array([[2], [3], [4]]) # test sample + if with_sample_weight: + sw = np.array([2.0, 2, 2]) + else: + sw = None # this should be the same as unregularized least squares clf = ElasticNet(alpha=0, l1_ratio=1.0) # catch warning about alpha=0. # this is discouraged but should work. - ignore_warnings(clf.fit)(X, Y) + ignore_warnings(clf.fit)(X, Y, sample_weight=sw) pred = clf.predict(T) assert_array_almost_equal(clf.coef_, [1]) assert_array_almost_equal(pred, [2, 3, 4]) assert_almost_equal(clf.dual_gap_, 0) clf = ElasticNet(alpha=0.5, l1_ratio=0.3) - clf.fit(X, Y) + clf.fit(X, Y, sample_weight=sw) pred = clf.predict(T) assert_array_almost_equal(clf.coef_, [0.50819], decimal=3) assert_array_almost_equal(pred, [1.0163, 1.5245, 2.0327], decimal=3) assert_almost_equal(clf.dual_gap_, 0) clf = ElasticNet(alpha=0.5, l1_ratio=0.5) - clf.fit(X, Y) + clf.fit(X, Y, sample_weight=sw) pred = clf.predict(T) assert_array_almost_equal(clf.coef_, [0.45454], 3) assert_array_almost_equal(pred, [0.9090, 1.3636, 1.8181], 3) @@ -276,7 +281,10 @@ def test_path_parameters(): @pytest.mark.parametrize("Model", [Lasso, ElasticNet, LassoCV, ElasticNetCV]) @pytest.mark.parametrize("fit_intercept", [False, True]) @pytest.mark.parametrize("n_samples, n_features", [(24, 6), (6, 24)]) -def test_sparse_dense_equality(Model, fit_intercept, n_samples, n_features): [email protected]("with_sample_weight", [True, False]) +def test_sparse_dense_equality( + Model, fit_intercept, n_samples, n_features, with_sample_weight +): X, y = make_regression( n_samples=n_samples, n_features=n_features, @@ -286,13 +294,20 @@ def test_sparse_dense_equality(Model, fit_intercept, n_samples, n_features): noise=1, random_state=42, ) + if with_sample_weight: + sw = np.abs(np.random.RandomState(42).normal(scale=10, size=y.shape)) + else: + sw = None Xs = sp.csc_matrix(X) - reg_dense = Model(fit_intercept=fit_intercept).fit(X, y) - reg_sparse = Model(fit_intercept=fit_intercept).fit(Xs, y) + params = {"fit_intercept": fit_intercept} + reg_dense = Model(**params).fit(X, y, sample_weight=sw) + reg_sparse = Model(**params).fit(Xs, y, sample_weight=sw) if fit_intercept: assert reg_sparse.intercept_ == pytest.approx(reg_dense.intercept_) # balance property - assert reg_sparse.predict(X).mean() == pytest.approx(y.mean()) + assert np.average(reg_sparse.predict(X), weights=sw) == pytest.approx( + np.average(y, weights=sw) + ) assert_allclose(reg_sparse.coef_, reg_dense.coef_)
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 10baed44932ab..fdc04fdff88fe 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -618,6 +618,10 @@ Changelog\n :class:`linear_model.ARDRegression` now preserve float32 dtype. :pr:`9087` by\n :user:`Arthur Imbert <Henley13>` and :pr:`22525` by :user:`Meekail Zain <micky774>`.\n \n+- |Feature| :class:`ElasticNet`, :class:`ElasticNetCV`, :class:`Lasso` and\n+ :class:`LassoCV` support `sample_weight` for sparse input `X`.\n+ :pr:`22808` by :user:`Christian Lorentzen <lorentzenchr>`.\n+\n - |Fix| The `coef_` and `intercept_` attributes of :class:`LinearRegression` are now\n correctly computed in the presence of sample weights when the input is sparse.\n :pr:`22891` by :user:`Jérémie du Boisberranger <jeremiedbb>`.\n@@ -625,7 +629,7 @@ Changelog\n - |Fix| The `coef_` and `intercept_` attributes of :class:`Ridge` with\n `solver=\"sparse_cg\"` and `solver=\"lbfgs\"` are now correctly computed in the presence\n of sample weights when the input is sparse.\n- :pr:`22899` by :user:`Jérémie du Boisberranger <jeremiedbb>`. \n+ :pr:`22899` by :user:`Jérémie du Boisberranger <jeremiedbb>`.\n \n :mod:`sklearn.manifold`\n .......................\n" } ]
1.01
e5736afb316038c43301d2c53ce39f9a89b64495
[ "sklearn/linear_model/tests/test_coordinate_descent.py::test_lassocv_alphas_validation[alphas1-ValueError-alphas\\\\[1\\\\] == -1, must be >= 0.0.]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[True-False-RidgeCV-params6]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_path_parameters", "sklearn/linear_model/tests/test_coordinate_descent.py::test_assure_warning_when_normalize[deprecated-0-MultiTaskElasticNet]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[BayesianRidge-params6]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_multitask_enet_and_lasso_cv", "sklearn/linear_model/tests/test_coordinate_descent.py::test_assure_warning_when_normalize[deprecated-0-MultiTaskElasticNetCV]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[MultiTaskLasso-params11]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[Lasso-params0]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_assure_warning_when_normalize[False-1-LassoCV]", "sklearn/linear_model/tests/test_base.py::test_dtype_preprocess_data", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_toy", "sklearn/linear_model/tests/test_coordinate_descent.py::test_assure_warning_when_normalize[True-1-Lasso]", "sklearn/linear_model/tests/test_base.py::test_preprocess_data", "sklearn/linear_model/tests/test_coordinate_descent.py::test_assure_warning_when_normalize[deprecated-0-Lasso]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_multitarget", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_copy_X_False_check_input_False", "sklearn/linear_model/tests/test_coordinate_descent.py::test_convergence_warnings", "sklearn/linear_model/tests/test_base.py::test_preprocess_copy_data_no_checks[True-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_coordinate_descent[MultiTaskLasso-2-kwargs3]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_assure_warning_when_normalize[True-1-ElasticNet]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[True-False-Ridge-params4]", "sklearn/linear_model/tests/test_sparse_coordinate_descent.py::test_sparse_dense_equality[False-6-24-False-ElasticNet]", "sklearn/linear_model/tests/test_sparse_coordinate_descent.py::test_sparse_dense_equality[False-6-24-True-ElasticNetCV]", "sklearn/linear_model/tests/test_base.py::test_linear_regression_sample_weights[True-array]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[RidgeCV-params15]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-True-RidgeCV-params6]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lassoCV_does_not_set_precompute[True-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_coordinate_descent[MultiTaskLasso-2-kwargs2]", "sklearn/linear_model/tests/test_base.py::test_deprecate_normalize[False-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_1d_multioutput_enet_and_multitask_enet_cv", "sklearn/linear_model/tests/test_coordinate_descent.py::test_assure_warning_when_normalize[deprecated-0-ElasticNetCV]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_param_invalid[params1-ValueError-l1_ratio == -1, must be >= 0.0]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_param_invalid[params6-ValueError-max_iter == 0, must be >= 1.]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_ridge_consistency[True-1.0]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-True-ElasticNet-params3]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_correctness[False-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[LinearRegression-params13]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_path", "sklearn/linear_model/tests/test_base.py::test_linear_regression_sparse_equal_dense[False-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_set_order_sparse[F-F]", "sklearn/linear_model/tests/test_sparse_coordinate_descent.py::test_sparse_dense_equality[False-6-24-True-LassoCV]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_ridge_consistency[True-0.1]", "sklearn/linear_model/tests/test_sparse_coordinate_descent.py::test_enet_toy_list_input[False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-False-Lasso-params0]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-False-RidgeClassifier-params1]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_assure_warning_when_normalize[False-1-MultiTaskLasso]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_warm_start", "sklearn/linear_model/tests/test_coordinate_descent.py::test_set_order_dense[C-C]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[False-False-0.5-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_warm_start_convergence_with_regularizer_decrement", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_path_return_models_vs_new_return_gives_same_coefficients", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_correctness[False-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_assure_warning_when_normalize[False-1-MultiTaskElasticNet]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[False-True-0.5-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_readonly_data", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_non_float_y[ElasticNet]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[LassoCV-params1]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[RidgeClassifier-params2]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-False-ElasticNet-params2]", "sklearn/linear_model/tests/test_base.py::test_preprocess_copy_data_no_checks[True-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_assure_warning_when_normalize[True-1-MultiTaskElasticNetCV]", "sklearn/linear_model/tests/test_base.py::test_raises_value_error_if_sample_weights_greater_than_1d", "sklearn/linear_model/tests/test_base.py::test_error_on_wrong_normalize", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_positive_constraint", "sklearn/linear_model/tests/test_coordinate_descent.py::test_assure_warning_when_normalize[False-1-Lasso]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-True-LinearRegression-params5]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_copy_X_True[True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_path_unknown_parameter[lasso_path]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_consistency[False-False-0.01-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_set_order_dense[C-F]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-True-Lasso-params0]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[Lasso-params0]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_sample_weight_invariance[estimator0]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_assure_warning_when_normalize[deprecated-0-ElasticNet]", "sklearn/linear_model/tests/test_base.py::test_linear_regression_positive_vs_nonpositive", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-False-RidgeClassifierCV-params7]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_does_not_overwrite_sample_weight[True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_param_invalid[params4-ValueError-tol == -1.0, must be >= 0.]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_assure_warning_when_normalize[False-1-ElasticNetCV]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_multi_task_lasso_cv_dtype", "sklearn/linear_model/tests/test_coordinate_descent.py::test_path_unknown_parameter[enet_path]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_check_input_false", "sklearn/linear_model/tests/test_sparse_coordinate_descent.py::test_sparse_enet_not_as_toy_dataset", "sklearn/linear_model/tests/test_coordinate_descent.py::test_warm_start_multitask_lasso", "sklearn/linear_model/tests/test_sparse_coordinate_descent.py::test_sparse_dense_equality[False-24-6-False-Lasso]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_ridge_consistency[True-1000000.0]", "sklearn/linear_model/tests/test_sparse_coordinate_descent.py::test_sparse_dense_equality[False-24-6-True-ElasticNet]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lassocv_alphas_validation[alphas3-TypeError-alphas\\\\[2\\\\] must be an instance of float, not str]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lassoCV_does_not_set_precompute[False-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_cv_positive_constraint", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-True-RidgeClassifierCV-params7]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_coordinate_descent[Lasso-1-kwargs1]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_multioutput_enetcv_error", "sklearn/linear_model/tests/test_coordinate_descent.py::test_set_order_sparse[F-C]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-True-RidgeClassifier-params1]", "sklearn/linear_model/tests/test_base.py::test_linear_regression_positive_vs_nonpositive_when_positive", "sklearn/linear_model/tests/test_base.py::test_linear_regression_sample_weights[True-csr_matrix]", "sklearn/linear_model/tests/test_base.py::test_raises_value_error_if_positive_and_sparse", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[MultiTaskElasticNet-params9]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_sparse_input_convergence_warning", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_consistency[False-True-0.01-True]", "sklearn/linear_model/tests/test_sparse_coordinate_descent.py::test_sparse_dense_equality[False-24-6-False-LassoCV]", "sklearn/linear_model/tests/test_base.py::test_preprocess_copy_data_no_checks[False-False]", "sklearn/linear_model/tests/test_base.py::test_preprocess_data_weighted[False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_precompute_invalid_argument", "sklearn/linear_model/tests/test_coordinate_descent.py::test_coef_shape_not_zero", "sklearn/linear_model/tests/test_coordinate_descent.py::test_multi_task_lasso_and_enet", "sklearn/linear_model/tests/test_coordinate_descent.py::test_1d_multioutput_lasso_and_multitask_lasso_cv", "sklearn/linear_model/tests/test_coordinate_descent.py::test_assure_warning_when_normalize[True-1-LassoCV]", "sklearn/linear_model/tests/test_sparse_coordinate_descent.py::test_sparse_dense_equality[False-6-24-True-Lasso]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[False-True-0-True]", "sklearn/linear_model/tests/test_sparse_coordinate_descent.py::test_same_multiple_output_sparse_dense", "sklearn/linear_model/tests/test_coordinate_descent.py::test_param_invalid[params2-ValueError-l1_ratio == 2, must be <= 1.0]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_ridge_consistency[False-1.0]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_assure_warning_when_normalize[deprecated-0-LassoCV]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_assure_warning_when_normalize[True-1-MultiTaskLasso]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_assure_warning_when_normalize[True-1-ElasticNetCV]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_assure_warning_when_normalize[deprecated-0-MultiTaskLassoCV]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_param_invalid[params7-TypeError-max_iter must be an instance of int, not str]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_coordinate_descent[Lasso-1-kwargs0]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_random_descent", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[MultiTaskElasticNet-params10]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[RidgeCV-params8]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_non_float_y[Lasso]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[ElasticNetCV-params2]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[Ridge-params5]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_assure_warning_when_normalize[False-1-MultiTaskElasticNetCV]", "sklearn/linear_model/tests/test_base.py::test_linear_regression_positive_multiple_outcome", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-False-Ridge-params4]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_set_order_dense[F-C]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_does_not_overwrite_sample_weight[False]", "sklearn/linear_model/tests/test_base.py::test_fit_intercept", "sklearn/linear_model/tests/test_coordinate_descent.py::test_elasticnet_precompute_incorrect_gram", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[False-False-1-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_alpha_warning", "sklearn/linear_model/tests/test_base.py::test_deprecate_normalize[False-False]", "sklearn/linear_model/tests/test_base.py::test_rescale_data_dense[2]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_set_order_sparse[C-F]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_ridge_consistency[False-0.1]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_models_cv_fit_with_loky[LassoCV]", "sklearn/linear_model/tests/test_sparse_coordinate_descent.py::test_sparse_lasso_not_as_toy_dataset", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[False-False-0.5-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_float_precision", "sklearn/linear_model/tests/test_sparse_coordinate_descent.py::test_sparse_dense_equality[False-24-6-True-Lasso]", "sklearn/linear_model/tests/test_base.py::test_preprocess_data_multioutput", "sklearn/linear_model/tests/test_coordinate_descent.py::test_sparse_input_dtype_enet_and_lassocv", "sklearn/linear_model/tests/test_coordinate_descent.py::test_assure_warning_when_normalize[True-1-MultiTaskLassoCV]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[RidgeClassifier-params3]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[ARDRegression-params7]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_uniform_targets", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[RidgeClassifierCV-params9]", "sklearn/linear_model/tests/test_sparse_coordinate_descent.py::test_enet_multitarget", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[RidgeClassifierCV-params16]", "sklearn/linear_model/tests/test_sparse_coordinate_descent.py::test_sparse_dense_equality[False-6-24-False-ElasticNetCV]", "sklearn/linear_model/tests/test_base.py::test_deprecate_normalize[True-deprecated]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_warm_start_convergence", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[True-False-LinearRegression-params5]", "sklearn/linear_model/tests/test_base.py::test_csr_preprocess_data", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[LinearRegression-params7]", "sklearn/linear_model/tests/test_base.py::test_linear_regression_sparse", "sklearn/linear_model/tests/test_base.py::test_linear_regression_sample_weights[False-csr_matrix]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_sample_weight_invariance[estimator1]", "sklearn/linear_model/tests/test_base.py::test_preprocess_copy_data_no_checks[False-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_elasticnet_precompute_gram_weighted_samples", "sklearn/linear_model/tests/test_sparse_coordinate_descent.py::test_normalize_option", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[LassoLarsIC-params14]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_positive_constraint", "sklearn/linear_model/tests/test_base.py::test_linear_regression", "sklearn/linear_model/tests/test_sparse_coordinate_descent.py::test_sparse_dense_equality[False-6-24-True-ElasticNet]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[ElasticNet-params3]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_zero", "sklearn/linear_model/tests/test_coordinate_descent.py::test_set_order_sparse[C-C]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_grid_search[False]", "sklearn/linear_model/tests/test_sparse_coordinate_descent.py::test_same_output_sparse_dense_lasso_and_enet_cv", "sklearn/linear_model/tests/test_coordinate_descent.py::test_assure_warning_when_normalize[deprecated-0-MultiTaskLasso]", "sklearn/linear_model/tests/test_sparse_coordinate_descent.py::test_sparse_dense_equality[False-24-6-True-LassoCV]", "sklearn/linear_model/tests/test_base.py::test_linear_regression_positive", "sklearn/linear_model/tests/test_base.py::test_linear_regression_multiple_outcome", "sklearn/linear_model/tests/test_coordinate_descent.py::test_assure_warning_when_normalize[False-1-MultiTaskLassoCV]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[Lars-params12]", "sklearn/linear_model/tests/test_sparse_coordinate_descent.py::test_sparse_dense_equality[False-24-6-False-ElasticNet]", "sklearn/linear_model/tests/test_sparse_coordinate_descent.py::test_sparse_dense_equality[False-6-24-False-LassoCV]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_assure_warning_when_normalize[True-1-MultiTaskElasticNet]", "sklearn/linear_model/tests/test_sparse_coordinate_descent.py::test_sparse_coef", "sklearn/linear_model/tests/test_coordinate_descent.py::test_sparse_dense_descent_paths", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[Ridge-params6]", "sklearn/linear_model/tests/test_sparse_coordinate_descent.py::test_lasso_zero", "sklearn/linear_model/tests/test_sparse_coordinate_descent.py::test_sparse_dense_equality[False-24-6-False-ElasticNetCV]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_assure_warning_when_normalize[False-1-ElasticNet]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_cv", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[LassoLars-params1]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[False-True-0.5-True]", "sklearn/linear_model/tests/test_base.py::test_fused_types_make_dataset", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_cv_with_some_model_selection", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-False-LinearRegression-params5]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_dual_gap", "sklearn/linear_model/tests/test_coordinate_descent.py::test_param_invalid[params3-TypeError-l1_ratio must be an instance of float, not str]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[True-False-RidgeClassifier-params1]", "sklearn/linear_model/tests/test_base.py::test_linear_regression_pd_sparse_dataframe_warning", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_positive_constraint", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lassoCV_does_not_set_precompute[auto-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_consistency[False-True-0.01-False]", "sklearn/linear_model/tests/test_base.py::test_linear_regression_sample_weights[False-array]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[False-True-0-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_models_cv_fit_with_loky[ElasticNetCV]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_path_positive", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_l1_ratio", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-True-ElasticNet-params2]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_toy", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lassocv_alphas_validation[-2-ValueError-alphas == -2, must be >= 0.0.]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_param_invalid[params5-TypeError-tol must be an instance of float, not str]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lassocv_alphas_validation[alphas2-ValueError-alphas\\\\[0\\\\] == -0.1, must be >= 0.0.]", "sklearn/linear_model/tests/test_sparse_coordinate_descent.py::test_sparse_dense_equality[False-6-24-False-Lasso]", "sklearn/linear_model/tests/test_sparse_coordinate_descent.py::test_sparse_enet_coordinate_descent", "sklearn/linear_model/tests/test_coordinate_descent.py::test_set_order_dense[F-F]", "sklearn/linear_model/tests/test_base.py::test_rescale_data_dense[None]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[OrthogonalMatchingPursuit-params8]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[ElasticNet-params4]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[False-True-1-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[False-False-1-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-False-RidgeCV-params6]", "sklearn/linear_model/tests/test_base.py::test_linear_regression_sparse_equal_dense[True-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[ElasticNet-params5]", "sklearn/linear_model/tests/test_base.py::test_linear_regression_sparse_equal_dense[True-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[False-False-0-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_multi_task_lasso_readonly_data", "sklearn/linear_model/tests/test_sparse_coordinate_descent.py::test_path_parameters", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_consistency[False-False-0.01-False]", "sklearn/linear_model/tests/test_sparse_coordinate_descent.py::test_enet_toy_explicit_sparse_input", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_ridge_consistency[False-1000000.0]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[False-True-1-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_overrided_gram_matrix", "sklearn/linear_model/tests/test_coordinate_descent.py::test_param_invalid[params0-ValueError-alpha == -1, must be >= 0.0]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_copy_X_True[False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-True-Ridge-params4]", "sklearn/linear_model/tests/test_base.py::test_linear_regression_sparse_multiple_outcome", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[True-False-RidgeClassifierCV-params7]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[ElasticNet-params4]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_grid_search[True]", "sklearn/linear_model/tests/test_sparse_coordinate_descent.py::test_sparse_dense_equality[False-24-6-True-ElasticNetCV]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_nonfinite_params", "sklearn/linear_model/tests/test_base.py::test_linear_regression_sparse_equal_dense[False-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[False-False-0-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-False-ElasticNet-params3]" ]
[ "sklearn/linear_model/tests/test_sparse_coordinate_descent.py::test_sparse_dense_equality[True-6-24-True-Lasso]", "sklearn/linear_model/tests/test_sparse_coordinate_descent.py::test_sparse_dense_equality[True-6-24-False-ElasticNetCV]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[True-False-ElasticNet-params2]", "sklearn/linear_model/tests/test_base.py::test_preprocess_data_weighted[True]", "sklearn/linear_model/tests/test_sparse_coordinate_descent.py::test_sparse_dense_equality[True-6-24-False-ElasticNet]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_correctness[True-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_consistency[True-True-0.01-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[True-True-0.5-True]", "sklearn/linear_model/tests/test_sparse_coordinate_descent.py::test_sparse_dense_equality[True-24-6-False-LassoCV]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[True-False-1-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_correctness[True-True]", "sklearn/linear_model/tests/test_sparse_coordinate_descent.py::test_sparse_dense_equality[True-6-24-False-LassoCV]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[True-True-1-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[True-True-0-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[True-False-Lasso-params0]", "sklearn/linear_model/tests/test_sparse_coordinate_descent.py::test_sparse_dense_equality[True-6-24-True-ElasticNetCV]", "sklearn/linear_model/tests/test_sparse_coordinate_descent.py::test_sparse_dense_equality[True-24-6-True-LassoCV]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[True-False-0.5-True]", "sklearn/linear_model/tests/test_sparse_coordinate_descent.py::test_sparse_dense_equality[True-24-6-False-ElasticNet]", "sklearn/linear_model/tests/test_sparse_coordinate_descent.py::test_enet_toy_list_input[True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[True-True-0-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_consistency[True-False-0.01-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[True-True-1-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_consistency[True-True-0.01-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[True-False-0.5-False]", "sklearn/linear_model/tests/test_sparse_coordinate_descent.py::test_sparse_dense_equality[True-6-24-True-ElasticNet]", "sklearn/linear_model/tests/test_sparse_coordinate_descent.py::test_sparse_dense_equality[True-24-6-True-Lasso]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[True-False-0-False]", "sklearn/linear_model/tests/test_sparse_coordinate_descent.py::test_sparse_dense_equality[True-24-6-True-ElasticNetCV]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_consistency[True-False-0.01-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[True-False-0-True]", "sklearn/linear_model/tests/test_sparse_coordinate_descent.py::test_sparse_dense_equality[True-24-6-False-ElasticNetCV]", "sklearn/linear_model/tests/test_sparse_coordinate_descent.py::test_sparse_dense_equality[True-24-6-False-Lasso]", "sklearn/linear_model/tests/test_sparse_coordinate_descent.py::test_sparse_dense_equality[True-24-6-True-ElasticNet]", "sklearn/linear_model/tests/test_sparse_coordinate_descent.py::test_sparse_dense_equality[True-6-24-False-Lasso]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[True-True-0.5-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[True-False-ElasticNet-params3]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[True-False-1-True]", "sklearn/linear_model/tests/test_sparse_coordinate_descent.py::test_sparse_dense_equality[True-6-24-True-LassoCV]", "sklearn/linear_model/tests/test_base.py::test_sparse_preprocess_data_offsets" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 10baed44932ab..fdc04fdff88fe 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -618,6 +618,10 @@ Changelog\n :class:`linear_model.ARDRegression` now preserve float32 dtype. :pr:`<PRID>` by\n :user:`<NAME>` and :pr:`<PRID>` by :user:`<NAME>`.\n \n+- |Feature| :class:`ElasticNet`, :class:`ElasticNetCV`, :class:`Lasso` and\n+ :class:`LassoCV` support `sample_weight` for sparse input `X`.\n+ :pr:`<PRID>` by :user:`<NAME>`.\n+\n - |Fix| The `coef_` and `intercept_` attributes of :class:`LinearRegression` are now\n correctly computed in the presence of sample weights when the input is sparse.\n :pr:`<PRID>` by :user:`<NAME>`.\n@@ -625,7 +629,7 @@ Changelog\n - |Fix| The `coef_` and `intercept_` attributes of :class:`Ridge` with\n `solver=\"sparse_cg\"` and `solver=\"lbfgs\"` are now correctly computed in the presence\n of sample weights when the input is sparse.\n- :pr:`<PRID>` by :user:`<NAME>`. \n+ :pr:`<PRID>` by :user:`<NAME>`.\n \n :mod:`sklearn.manifold`\n .......................\n" } ]
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 10baed44932ab..fdc04fdff88fe 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -618,6 +618,10 @@ Changelog :class:`linear_model.ARDRegression` now preserve float32 dtype. :pr:`<PRID>` by :user:`<NAME>` and :pr:`<PRID>` by :user:`<NAME>`. +- |Feature| :class:`ElasticNet`, :class:`ElasticNetCV`, :class:`Lasso` and + :class:`LassoCV` support `sample_weight` for sparse input `X`. + :pr:`<PRID>` by :user:`<NAME>`. + - |Fix| The `coef_` and `intercept_` attributes of :class:`LinearRegression` are now correctly computed in the presence of sample weights when the input is sparse. :pr:`<PRID>` by :user:`<NAME>`. @@ -625,7 +629,7 @@ Changelog - |Fix| The `coef_` and `intercept_` attributes of :class:`Ridge` with `solver="sparse_cg"` and `solver="lbfgs"` are now correctly computed in the presence of sample weights when the input is sparse. - :pr:`<PRID>` by :user:`<NAME>`. + :pr:`<PRID>` by :user:`<NAME>`. :mod:`sklearn.manifold` .......................
scikit-learn/scikit-learn
scikit-learn__scikit-learn-21808
https://github.com/scikit-learn/scikit-learn/pull/21808
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 39f8e405ebf7c..b88e54b46a4bf 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -393,6 +393,15 @@ Changelog beginning which speeds up fitting. :pr:`22206` by :user:`Christian Lorentzen <lorentzenchr>`. +- |Enhancement| :class:`~linear_model.LogisticRegression` is faster for + ``solvers="lbfgs"`` and ``solver="newton-cg"``, for binary and in particular for + multiclass problems thanks to the new private loss function module. In the multiclass + case, the memory consumption has also been reduced for these solvers as the target is + now label encoded (mapped to integers) instead of label binarized (one-hot encoded). + The more classes, the larger the benefit. + :pr:`21808`, :pr:`20567` and :pr:`21814` by + :user:`Christian Lorentzen <lorentzenchr>`. + - |Enhancement| Rename parameter `base_estimator` to `estimator` in :class:`linear_model.RANSACRegressor` to improve readability and consistency. `base_estimator` is deprecated and will be removed in 1.3. diff --git a/sklearn/linear_model/_linear_loss.py b/sklearn/linear_model/_linear_loss.py new file mode 100644 index 0000000000000..93a7684aea5b6 --- /dev/null +++ b/sklearn/linear_model/_linear_loss.py @@ -0,0 +1,411 @@ +""" +Loss functions for linear models with raw_prediction = X @ coef +""" +import numpy as np +from scipy import sparse +from ..utils.extmath import squared_norm + + +class LinearModelLoss: + """General class for loss functions with raw_prediction = X @ coef + intercept. + + The loss is the sum of per sample losses and includes a term for L2 + regularization:: + + loss = sum_i s_i loss(y_i, X_i @ coef + intercept) + + 1/2 * l2_reg_strength * ||coef||_2^2 + + with sample weights s_i=1 if sample_weight=None. + + Gradient and hessian, for simplicity without intercept, are:: + + gradient = X.T @ loss.gradient + l2_reg_strength * coef + hessian = X.T @ diag(loss.hessian) @ X + l2_reg_strength * identity + + Conventions: + if fit_intercept: + n_dof = n_features + 1 + else: + n_dof = n_features + + if base_loss.is_multiclass: + coef.shape = (n_classes, n_dof) or ravelled (n_classes * n_dof,) + else: + coef.shape = (n_dof,) + + The intercept term is at the end of the coef array: + if base_loss.is_multiclass: + if coef.shape (n_classes, n_dof): + intercept = coef[:, -1] + if coef.shape (n_classes * n_dof,) + intercept = coef[n_features::n_dof] = coef[(n_dof-1)::n_dof] + intercept.shape = (n_classes,) + else: + intercept = coef[-1] + + Note: If coef has shape (n_classes * n_dof,), the 2d-array can be reconstructed as + + coef.reshape((n_classes, -1), order="F") + + The option order="F" makes coef[:, i] contiguous. This, in turn, makes the + coefficients without intercept, coef[:, :-1], contiguous and speeds up + matrix-vector computations. + + Note: If the average loss per sample is wanted instead of the sum of the loss per + sample, one can simply use a rescaled sample_weight such that + sum(sample_weight) = 1. + + Parameters + ---------- + base_loss : instance of class BaseLoss from sklearn._loss. + fit_intercept : bool + """ + + def __init__(self, base_loss, fit_intercept): + self.base_loss = base_loss + self.fit_intercept = fit_intercept + + def _w_intercept_raw(self, coef, X): + """Helper function to get coefficients, intercept and raw_prediction. + + Parameters + ---------- + coef : ndarray of shape (n_dof,), (n_classes, n_dof) or (n_classes * n_dof,) + Coefficients of a linear model. + If shape (n_classes * n_dof,), the classes of one feature are contiguous, + i.e. one reconstructs the 2d-array via + coef.reshape((n_classes, -1), order="F"). + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training data. + + Returns + ------- + weights : ndarray of shape (n_features,) or (n_classes, n_features) + Coefficients without intercept term. + intercept : float or ndarray of shape (n_classes,) + Intercept terms. + raw_prediction : ndarray of shape (n_samples,) or \ + (n_samples, n_classes) + """ + if not self.base_loss.is_multiclass: + if self.fit_intercept: + intercept = coef[-1] + weights = coef[:-1] + else: + intercept = 0.0 + weights = coef + raw_prediction = X @ weights + intercept + else: + # reshape to (n_classes, n_dof) + if coef.ndim == 1: + weights = coef.reshape((self.base_loss.n_classes, -1), order="F") + else: + weights = coef + if self.fit_intercept: + intercept = weights[:, -1] + weights = weights[:, :-1] + else: + intercept = 0.0 + raw_prediction = X @ weights.T + intercept # ndarray, likely C-contiguous + + return weights, intercept, raw_prediction + + def loss(self, coef, X, y, sample_weight=None, l2_reg_strength=0.0, n_threads=1): + """Compute the loss as sum over point-wise losses. + + Parameters + ---------- + coef : ndarray of shape (n_dof,), (n_classes, n_dof) or (n_classes * n_dof,) + Coefficients of a linear model. + If shape (n_classes * n_dof,), the classes of one feature are contiguous, + i.e. one reconstructs the 2d-array via + coef.reshape((n_classes, -1), order="F"). + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training data. + y : contiguous array of shape (n_samples,) + Observed, true target values. + sample_weight : None or contiguous array of shape (n_samples,), default=None + Sample weights. + l2_reg_strength : float, default=0.0 + L2 regularization strength + n_threads : int, default=1 + Number of OpenMP threads to use. + + Returns + ------- + loss : float + Sum of losses per sample plus penalty. + """ + weights, intercept, raw_prediction = self._w_intercept_raw(coef, X) + + loss = self.base_loss.loss( + y_true=y, + raw_prediction=raw_prediction, + sample_weight=sample_weight, + n_threads=n_threads, + ) + loss = loss.sum() + + norm2_w = weights @ weights if weights.ndim == 1 else squared_norm(weights) + return loss + 0.5 * l2_reg_strength * norm2_w + + def loss_gradient( + self, coef, X, y, sample_weight=None, l2_reg_strength=0.0, n_threads=1 + ): + """Computes the sum of loss and gradient w.r.t. coef. + + Parameters + ---------- + coef : ndarray of shape (n_dof,), (n_classes, n_dof) or (n_classes * n_dof,) + Coefficients of a linear model. + If shape (n_classes * n_dof,), the classes of one feature are contiguous, + i.e. one reconstructs the 2d-array via + coef.reshape((n_classes, -1), order="F"). + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training data. + y : contiguous array of shape (n_samples,) + Observed, true target values. + sample_weight : None or contiguous array of shape (n_samples,), default=None + Sample weights. + l2_reg_strength : float, default=0.0 + L2 regularization strength + n_threads : int, default=1 + Number of OpenMP threads to use. + + Returns + ------- + loss : float + Sum of losses per sample plus penalty. + + gradient : ndarray of shape coef.shape + The gradient of the loss. + """ + n_features, n_classes = X.shape[1], self.base_loss.n_classes + n_dof = n_features + int(self.fit_intercept) + weights, intercept, raw_prediction = self._w_intercept_raw(coef, X) + + loss, grad_per_sample = self.base_loss.loss_gradient( + y_true=y, + raw_prediction=raw_prediction, + sample_weight=sample_weight, + n_threads=n_threads, + ) + loss = loss.sum() + + if not self.base_loss.is_multiclass: + loss += 0.5 * l2_reg_strength * (weights @ weights) + grad = np.empty_like(coef, dtype=X.dtype) + grad[:n_features] = X.T @ grad_per_sample + l2_reg_strength * weights + if self.fit_intercept: + grad[-1] = grad_per_sample.sum() + else: + loss += 0.5 * l2_reg_strength * squared_norm(weights) + grad = np.empty((n_classes, n_dof), dtype=X.dtype, order="F") + # grad_per_sample.shape = (n_samples, n_classes) + grad[:, :n_features] = grad_per_sample.T @ X + l2_reg_strength * weights + if self.fit_intercept: + grad[:, -1] = grad_per_sample.sum(axis=0) + if coef.ndim == 1: + grad = grad.ravel(order="F") + + return loss, grad + + def gradient( + self, coef, X, y, sample_weight=None, l2_reg_strength=0.0, n_threads=1 + ): + """Computes the gradient w.r.t. coef. + + Parameters + ---------- + coef : ndarray of shape (n_dof,), (n_classes, n_dof) or (n_classes * n_dof,) + Coefficients of a linear model. + If shape (n_classes * n_dof,), the classes of one feature are contiguous, + i.e. one reconstructs the 2d-array via + coef.reshape((n_classes, -1), order="F"). + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training data. + y : contiguous array of shape (n_samples,) + Observed, true target values. + sample_weight : None or contiguous array of shape (n_samples,), default=None + Sample weights. + l2_reg_strength : float, default=0.0 + L2 regularization strength + n_threads : int, default=1 + Number of OpenMP threads to use. + + Returns + ------- + gradient : ndarray of shape coef.shape + The gradient of the loss. + """ + n_features, n_classes = X.shape[1], self.base_loss.n_classes + n_dof = n_features + int(self.fit_intercept) + weights, intercept, raw_prediction = self._w_intercept_raw(coef, X) + + grad_per_sample = self.base_loss.gradient( + y_true=y, + raw_prediction=raw_prediction, + sample_weight=sample_weight, + n_threads=n_threads, + ) + + if not self.base_loss.is_multiclass: + grad = np.empty_like(coef, dtype=X.dtype) + grad[:n_features] = X.T @ grad_per_sample + l2_reg_strength * weights + if self.fit_intercept: + grad[-1] = grad_per_sample.sum() + return grad + else: + grad = np.empty((n_classes, n_dof), dtype=X.dtype, order="F") + # gradient.shape = (n_samples, n_classes) + grad[:, :n_features] = grad_per_sample.T @ X + l2_reg_strength * weights + if self.fit_intercept: + grad[:, -1] = grad_per_sample.sum(axis=0) + if coef.ndim == 1: + return grad.ravel(order="F") + else: + return grad + + def gradient_hessian_product( + self, coef, X, y, sample_weight=None, l2_reg_strength=0.0, n_threads=1 + ): + """Computes gradient and hessp (hessian product function) w.r.t. coef. + + Parameters + ---------- + coef : ndarray of shape (n_dof,), (n_classes, n_dof) or (n_classes * n_dof,) + Coefficients of a linear model. + If shape (n_classes * n_dof,), the classes of one feature are contiguous, + i.e. one reconstructs the 2d-array via + coef.reshape((n_classes, -1), order="F"). + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training data. + y : contiguous array of shape (n_samples,) + Observed, true target values. + sample_weight : None or contiguous array of shape (n_samples,), default=None + Sample weights. + l2_reg_strength : float, default=0.0 + L2 regularization strength + n_threads : int, default=1 + Number of OpenMP threads to use. + + Returns + ------- + gradient : ndarray of shape coef.shape + The gradient of the loss. + + hessp : callable + Function that takes in a vector input of shape of gradient and + and returns matrix-vector product with hessian. + """ + (n_samples, n_features), n_classes = X.shape, self.base_loss.n_classes + n_dof = n_features + int(self.fit_intercept) + weights, intercept, raw_prediction = self._w_intercept_raw(coef, X) + + if not self.base_loss.is_multiclass: + gradient, hessian = self.base_loss.gradient_hessian( + y_true=y, + raw_prediction=raw_prediction, + sample_weight=sample_weight, + n_threads=n_threads, + ) + grad = np.empty_like(coef, dtype=X.dtype) + grad[:n_features] = X.T @ gradient + l2_reg_strength * weights + if self.fit_intercept: + grad[-1] = gradient.sum() + + # Precompute as much as possible: hX, hX_sum and hessian_sum + hessian_sum = hessian.sum() + if sparse.issparse(X): + hX = sparse.dia_matrix((hessian, 0), shape=(n_samples, n_samples)) @ X + else: + hX = hessian[:, np.newaxis] * X + + if self.fit_intercept: + # Calculate the double derivative with respect to intercept. + # Note: In case hX is sparse, hX.sum is a matrix object. + hX_sum = np.squeeze(np.asarray(hX.sum(axis=0))) + + # With intercept included and l2_reg_strength = 0, hessp returns + # res = (X, 1)' @ diag(h) @ (X, 1) @ s + # = (X, 1)' @ (hX @ s[:n_features], sum(h) * s[-1]) + # res[:n_features] = X' @ hX @ s[:n_features] + sum(h) * s[-1] + # res[-1] = 1' @ hX @ s[:n_features] + sum(h) * s[-1] + def hessp(s): + ret = np.empty_like(s) + if sparse.issparse(X): + ret[:n_features] = X.T @ (hX @ s[:n_features]) + else: + ret[:n_features] = np.linalg.multi_dot([X.T, hX, s[:n_features]]) + ret[:n_features] += l2_reg_strength * s[:n_features] + + if self.fit_intercept: + ret[:n_features] += s[-1] * hX_sum + ret[-1] = hX_sum @ s[:n_features] + hessian_sum * s[-1] + return ret + + else: + # Here we may safely assume HalfMultinomialLoss aka categorical + # cross-entropy. + # HalfMultinomialLoss computes only the diagonal part of the hessian, i.e. + # diagonal in the classes. Here, we want the matrix-vector product of the + # full hessian. Therefore, we call gradient_proba. + gradient, proba = self.base_loss.gradient_proba( + y_true=y, + raw_prediction=raw_prediction, + sample_weight=sample_weight, + n_threads=n_threads, + ) + grad = np.empty((n_classes, n_dof), dtype=X.dtype, order="F") + grad[:, :n_features] = gradient.T @ X + l2_reg_strength * weights + if self.fit_intercept: + grad[:, -1] = gradient.sum(axis=0) + + # Full hessian-vector product, i.e. not only the diagonal part of the + # hessian. Derivation with some index battle for input vector s: + # - sample index i + # - feature indices j, m + # - class indices k, l + # - 1_{k=l} is one if k=l else 0 + # - p_i_k is the (predicted) probability that sample i belongs to class k + # for all i: sum_k p_i_k = 1 + # - s_l_m is input vector for class l and feature m + # - X' = X transposed + # + # Note: Hessian with dropping most indices is just: + # X' @ p_k (1(k=l) - p_l) @ X + # + # result_{k j} = sum_{i, l, m} Hessian_{i, k j, m l} * s_l_m + # = sum_{i, l, m} (X')_{ji} * p_i_k * (1_{k=l} - p_i_l) + # * X_{im} s_l_m + # = sum_{i, m} (X')_{ji} * p_i_k + # * (X_{im} * s_k_m - sum_l p_i_l * X_{im} * s_l_m) + # + # See also https://github.com/scikit-learn/scikit-learn/pull/3646#discussion_r17461411 # noqa + def hessp(s): + s = s.reshape((n_classes, -1), order="F") # shape = (n_classes, n_dof) + if self.fit_intercept: + s_intercept = s[:, -1] + s = s[:, :-1] # shape = (n_classes, n_features) + else: + s_intercept = 0 + tmp = X @ s.T + s_intercept # X_{im} * s_k_m + tmp += (-proba * tmp).sum(axis=1)[:, np.newaxis] # - sum_l .. + tmp *= proba # * p_i_k + if sample_weight is not None: + tmp *= sample_weight[:, np.newaxis] + # hess_prod = empty_like(grad), but we ravel grad below and this + # function is run after that. + hess_prod = np.empty((n_classes, n_dof), dtype=X.dtype, order="F") + hess_prod[:, :n_features] = tmp.T @ X + l2_reg_strength * s + if self.fit_intercept: + hess_prod[:, -1] = tmp.sum(axis=0) + if coef.ndim == 1: + return hess_prod.ravel(order="F") + else: + return hess_prod + + if coef.ndim == 1: + return grad.ravel(order="F"), hessp + + return grad, hessp diff --git a/sklearn/linear_model/_logistic.py b/sklearn/linear_model/_logistic.py index dd3a1a0c15a11..fed48fb07d924 100644 --- a/sklearn/linear_model/_logistic.py +++ b/sklearn/linear_model/_logistic.py @@ -14,17 +14,18 @@ import warnings import numpy as np -from scipy import optimize, sparse -from scipy.special import expit, logsumexp +from scipy import optimize from joblib import Parallel, effective_n_jobs from ._base import LinearClassifierMixin, SparseCoefMixin, BaseEstimator +from ._linear_loss import LinearModelLoss from ._sag import sag_solver +from .._loss.loss import HalfBinomialLoss, HalfMultinomialLoss from ..preprocessing import LabelEncoder, LabelBinarizer from ..svm._base import _fit_liblinear from ..utils import check_array, check_consistent_length, compute_class_weight from ..utils import check_random_state -from ..utils.extmath import log_logistic, safe_sparse_dot, softmax, squared_norm +from ..utils.extmath import softmax from ..utils.extmath import row_norms from ..utils.optimize import _newton_cg, _check_optimize_result from ..utils.validation import check_is_fitted, _check_sample_weight @@ -41,392 +42,6 @@ ) -# .. some helper functions for logistic_regression_path .. -def _intercept_dot(w, X, y): - """Computes y * np.dot(X, w). - - It takes into consideration if the intercept should be fit or not. - - Parameters - ---------- - w : ndarray of shape (n_features,) or (n_features + 1,) - Coefficient vector. - - X : {array-like, sparse matrix} of shape (n_samples, n_features) - Training data. - - y : ndarray of shape (n_samples,) - Array of labels. - - Returns - ------- - w : ndarray of shape (n_features,) - Coefficient vector without the intercept weight (w[-1]) if the - intercept should be fit. Unchanged otherwise. - - c : float - The intercept. - - yz : float - y * np.dot(X, w). - """ - c = 0.0 - if w.size == X.shape[1] + 1: - c = w[-1] - w = w[:-1] - - z = safe_sparse_dot(X, w) + c - yz = y * z - return w, c, yz - - -def _logistic_loss_and_grad(w, X, y, alpha, sample_weight=None): - """Computes the logistic loss and gradient. - - Parameters - ---------- - w : ndarray of shape (n_features,) or (n_features + 1,) - Coefficient vector. - - X : {array-like, sparse matrix} of shape (n_samples, n_features) - Training data. - - y : ndarray of shape (n_samples,) - Array of labels. - - alpha : float - Regularization parameter. alpha is equal to 1 / C. - - sample_weight : array-like of shape (n_samples,), default=None - Array of weights that are assigned to individual samples. - If not provided, then each sample is given unit weight. - - Returns - ------- - out : float - Logistic loss. - - grad : ndarray of shape (n_features,) or (n_features + 1,) - Logistic gradient. - """ - n_samples, n_features = X.shape - grad = np.empty_like(w) - - w, c, yz = _intercept_dot(w, X, y) - - if sample_weight is None: - sample_weight = np.ones(n_samples) - - # Logistic loss is the negative of the log of the logistic function. - out = -np.sum(sample_weight * log_logistic(yz)) + 0.5 * alpha * np.dot(w, w) - - z = expit(yz) - z0 = sample_weight * (z - 1) * y - - grad[:n_features] = safe_sparse_dot(X.T, z0) + alpha * w - - # Case where we fit the intercept. - if grad.shape[0] > n_features: - grad[-1] = z0.sum() - return out, grad - - -def _logistic_loss(w, X, y, alpha, sample_weight=None): - """Computes the logistic loss. - - Parameters - ---------- - w : ndarray of shape (n_features,) or (n_features + 1,) - Coefficient vector. - - X : {array-like, sparse matrix} of shape (n_samples, n_features) - Training data. - - y : ndarray of shape (n_samples,) - Array of labels. - - alpha : float - Regularization parameter. alpha is equal to 1 / C. - - sample_weight : array-like of shape (n_samples,) default=None - Array of weights that are assigned to individual samples. - If not provided, then each sample is given unit weight. - - Returns - ------- - out : float - Logistic loss. - """ - w, c, yz = _intercept_dot(w, X, y) - - if sample_weight is None: - sample_weight = np.ones(y.shape[0]) - - # Logistic loss is the negative of the log of the logistic function. - out = -np.sum(sample_weight * log_logistic(yz)) + 0.5 * alpha * np.dot(w, w) - return out - - -def _logistic_grad_hess(w, X, y, alpha, sample_weight=None): - """Computes the gradient and the Hessian, in the case of a logistic loss. - - Parameters - ---------- - w : ndarray of shape (n_features,) or (n_features + 1,) - Coefficient vector. - - X : {array-like, sparse matrix} of shape (n_samples, n_features) - Training data. - - y : ndarray of shape (n_samples,) - Array of labels. - - alpha : float - Regularization parameter. alpha is equal to 1 / C. - - sample_weight : array-like of shape (n_samples,) default=None - Array of weights that are assigned to individual samples. - If not provided, then each sample is given unit weight. - - Returns - ------- - grad : ndarray of shape (n_features,) or (n_features + 1,) - Logistic gradient. - - Hs : callable - Function that takes the gradient as a parameter and returns the - matrix product of the Hessian and gradient. - """ - n_samples, n_features = X.shape - grad = np.empty_like(w) - fit_intercept = grad.shape[0] > n_features - - w, c, yz = _intercept_dot(w, X, y) - - if sample_weight is None: - sample_weight = np.ones(y.shape[0]) - - z = expit(yz) - z0 = sample_weight * (z - 1) * y - - grad[:n_features] = safe_sparse_dot(X.T, z0) + alpha * w - - # Case where we fit the intercept. - if fit_intercept: - grad[-1] = z0.sum() - - # The mat-vec product of the Hessian - d = sample_weight * z * (1 - z) - if sparse.issparse(X): - dX = safe_sparse_dot(sparse.dia_matrix((d, 0), shape=(n_samples, n_samples)), X) - else: - # Precompute as much as possible - dX = d[:, np.newaxis] * X - - if fit_intercept: - # Calculate the double derivative with respect to intercept - # In the case of sparse matrices this returns a matrix object. - dd_intercept = np.squeeze(np.array(dX.sum(axis=0))) - - def Hs(s): - ret = np.empty_like(s) - if sparse.issparse(X): - ret[:n_features] = X.T.dot(dX.dot(s[:n_features])) - else: - ret[:n_features] = np.linalg.multi_dot([X.T, dX, s[:n_features]]) - ret[:n_features] += alpha * s[:n_features] - - # For the fit intercept case. - if fit_intercept: - ret[:n_features] += s[-1] * dd_intercept - ret[-1] = dd_intercept.dot(s[:n_features]) - ret[-1] += d.sum() * s[-1] - return ret - - return grad, Hs - - -def _multinomial_loss(w, X, Y, alpha, sample_weight): - """Computes multinomial loss and class probabilities. - - Parameters - ---------- - w : ndarray of shape (n_classes * n_features,) or - (n_classes * (n_features + 1),) - Coefficient vector. - - X : {array-like, sparse matrix} of shape (n_samples, n_features) - Training data. - - Y : ndarray of shape (n_samples, n_classes) - Transformed labels according to the output of LabelBinarizer. - - alpha : float - Regularization parameter. alpha is equal to 1 / C. - - sample_weight : array-like of shape (n_samples,) - Array of weights that are assigned to individual samples. - - Returns - ------- - loss : float - Multinomial loss. - - p : ndarray of shape (n_samples, n_classes) - Estimated class probabilities. - - w : ndarray of shape (n_classes, n_features) - Reshaped param vector excluding intercept terms. - - Reference - --------- - Bishop, C. M. (2006). Pattern recognition and machine learning. - Springer. (Chapter 4.3.4) - """ - n_classes = Y.shape[1] - n_features = X.shape[1] - fit_intercept = w.size == (n_classes * (n_features + 1)) - w = w.reshape(n_classes, -1) - sample_weight = sample_weight[:, np.newaxis] - if fit_intercept: - intercept = w[:, -1] - w = w[:, :-1] - else: - intercept = 0 - p = safe_sparse_dot(X, w.T) - p += intercept - p -= logsumexp(p, axis=1)[:, np.newaxis] - loss = -(sample_weight * Y * p).sum() - loss += 0.5 * alpha * squared_norm(w) - p = np.exp(p, p) - return loss, p, w - - -def _multinomial_loss_grad(w, X, Y, alpha, sample_weight): - """Computes the multinomial loss, gradient and class probabilities. - - Parameters - ---------- - w : ndarray of shape (n_classes * n_features,) or - (n_classes * (n_features + 1),) - Coefficient vector. - - X : {array-like, sparse matrix} of shape (n_samples, n_features) - Training data. - - Y : ndarray of shape (n_samples, n_classes) - Transformed labels according to the output of LabelBinarizer. - - alpha : float - Regularization parameter. alpha is equal to 1 / C. - - sample_weight : array-like of shape (n_samples,) - Array of weights that are assigned to individual samples. - - Returns - ------- - loss : float - Multinomial loss. - - grad : ndarray of shape (n_classes * n_features,) or \ - (n_classes * (n_features + 1),) - Ravelled gradient of the multinomial loss. - - p : ndarray of shape (n_samples, n_classes) - Estimated class probabilities - - Reference - --------- - Bishop, C. M. (2006). Pattern recognition and machine learning. - Springer. (Chapter 4.3.4) - """ - n_classes = Y.shape[1] - n_features = X.shape[1] - fit_intercept = w.size == n_classes * (n_features + 1) - grad = np.zeros((n_classes, n_features + bool(fit_intercept)), dtype=X.dtype) - loss, p, w = _multinomial_loss(w, X, Y, alpha, sample_weight) - sample_weight = sample_weight[:, np.newaxis] - diff = sample_weight * (p - Y) - grad[:, :n_features] = safe_sparse_dot(diff.T, X) - grad[:, :n_features] += alpha * w - if fit_intercept: - grad[:, -1] = diff.sum(axis=0) - return loss, grad.ravel(), p - - -def _multinomial_grad_hess(w, X, Y, alpha, sample_weight): - """ - Computes the gradient and the Hessian, in the case of a multinomial loss. - - Parameters - ---------- - w : ndarray of shape (n_classes * n_features,) or - (n_classes * (n_features + 1),) - Coefficient vector. - - X : {array-like, sparse matrix} of shape (n_samples, n_features) - Training data. - - Y : ndarray of shape (n_samples, n_classes) - Transformed labels according to the output of LabelBinarizer. - - alpha : float - Regularization parameter. alpha is equal to 1 / C. - - sample_weight : array-like of shape (n_samples,) - Array of weights that are assigned to individual samples. - - Returns - ------- - grad : ndarray of shape (n_classes * n_features,) or \ - (n_classes * (n_features + 1),) - Ravelled gradient of the multinomial loss. - - hessp : callable - Function that takes in a vector input of shape (n_classes * n_features) - or (n_classes * (n_features + 1)) and returns matrix-vector product - with hessian. - - References - ---------- - Barak A. Pearlmutter (1993). Fast Exact Multiplication by the Hessian. - http://www.bcl.hamilton.ie/~barak/papers/nc-hessian.pdf - """ - n_features = X.shape[1] - n_classes = Y.shape[1] - fit_intercept = w.size == (n_classes * (n_features + 1)) - - # `loss` is unused. Refactoring to avoid computing it does not - # significantly speed up the computation and decreases readability - loss, grad, p = _multinomial_loss_grad(w, X, Y, alpha, sample_weight) - sample_weight = sample_weight[:, np.newaxis] - - # Hessian-vector product derived by applying the R-operator on the gradient - # of the multinomial loss function. - def hessp(v): - v = v.reshape(n_classes, -1) - if fit_intercept: - inter_terms = v[:, -1] - v = v[:, :-1] - else: - inter_terms = 0 - # r_yhat holds the result of applying the R-operator on the multinomial - # estimator. - r_yhat = safe_sparse_dot(X, v.T) - r_yhat += inter_terms - r_yhat += (-p * r_yhat).sum(axis=1)[:, np.newaxis] - r_yhat *= p - r_yhat *= sample_weight - hessProd = np.zeros((n_classes, n_features + bool(fit_intercept))) - hessProd[:, :n_features] = safe_sparse_dot(r_yhat.T, X) - hessProd[:, :n_features] += v * alpha - if fit_intercept: - hessProd[:, -1] = r_yhat.sum(axis=0) - return hessProd.ravel() - - return grad, hessp - - def _check_solver(solver, penalty, dual): all_solvers = ["liblinear", "newton-cg", "lbfgs", "sag", "saga"] if solver not in all_solvers: @@ -504,6 +119,7 @@ def _logistic_regression_path( max_squared_sum=None, sample_weight=None, l1_ratio=None, + n_threads=1, ): """Compute a Logistic Regression model for a list of regularization parameters. @@ -628,6 +244,9 @@ def _logistic_regression_path( to using ``penalty='l1'``. For ``0 < l1_ratio <1``, the penalty is a combination of L1 and L2. + n_threads : int, default=1 + Number of OpenMP threads to use. + Returns ------- coefs : ndarray of shape (n_cs, n_features) or (n_cs, n_features + 1) @@ -695,12 +314,18 @@ def _logistic_regression_path( # multinomial case this is not necessary. if multi_class == "ovr": w0 = np.zeros(n_features + int(fit_intercept), dtype=X.dtype) - mask_classes = np.array([-1, 1]) mask = y == pos_class y_bin = np.ones(y.shape, dtype=X.dtype) - y_bin[~mask] = -1.0 - # for compute_class_weight + if solver in ["lbfgs", "newton-cg"]: + # HalfBinomialLoss, used for those solvers, represents y in [0, 1] instead + # of in [-1, 1]. + mask_classes = np.array([0, 1]) + y_bin[~mask] = 0.0 + else: + mask_classes = np.array([-1, 1]) + y_bin[~mask] = -1.0 + # for compute_class_weight if class_weight == "balanced": class_weight_ = compute_class_weight( class_weight, classes=mask_classes, y=y_bin @@ -708,15 +333,19 @@ def _logistic_regression_path( sample_weight *= class_weight_[le.fit_transform(y_bin)] else: - if solver not in ["sag", "saga"]: + if solver in ["sag", "saga", "lbfgs", "newton-cg"]: + # SAG, lbfgs and newton-cg multinomial solvers need LabelEncoder, + # not LabelBinarizer, i.e. y as a 1d-array of integers. + # LabelEncoder also saves memory compared to LabelBinarizer, especially + # when n_classes is large. + le = LabelEncoder() + Y_multi = le.fit_transform(y).astype(X.dtype, copy=False) + else: + # For liblinear solver, apply LabelBinarizer, i.e. y is one-hot encoded. lbin = LabelBinarizer() Y_multi = lbin.fit_transform(y) if Y_multi.shape[1] == 1: Y_multi = np.hstack([1 - Y_multi, Y_multi]) - else: - # SAG multinomial solver needs LabelEncoder, not LabelBinarizer - le = LabelEncoder() - Y_multi = le.fit_transform(y).astype(X.dtype, copy=False) w0 = np.zeros( (classes.size, n_features + int(fit_intercept)), order="F", dtype=X.dtype @@ -762,43 +391,45 @@ def _logistic_regression_path( w0[:, : coef.shape[1]] = coef if multi_class == "multinomial": - # scipy.optimize.minimize and newton-cg accepts only - # ravelled parameters. if solver in ["lbfgs", "newton-cg"]: - w0 = w0.ravel() + # scipy.optimize.minimize and newton-cg accept only ravelled parameters, + # i.e. 1d-arrays. LinearModelLoss expects classes to be contiguous and + # reconstructs the 2d-array via w0.reshape((n_classes, -1), order="F"). + # As w0 is F-contiguous, ravel(order="F") also avoids a copy. + w0 = w0.ravel(order="F") + loss = LinearModelLoss( + base_loss=HalfMultinomialLoss(n_classes=classes.size), + fit_intercept=fit_intercept, + ) target = Y_multi - if solver == "lbfgs": - - def func(x, *args): - return _multinomial_loss_grad(x, *args)[0:2] - + if solver in "lbfgs": + func = loss.loss_gradient elif solver == "newton-cg": - - def func(x, *args): - return _multinomial_loss(x, *args)[0] - - def grad(x, *args): - return _multinomial_loss_grad(x, *args)[1] - - hess = _multinomial_grad_hess + func = loss.loss + grad = loss.gradient + hess = loss.gradient_hessian_product # hess = [gradient, hessp] warm_start_sag = {"coef": w0.T} else: target = y_bin if solver == "lbfgs": - func = _logistic_loss_and_grad + loss = LinearModelLoss( + base_loss=HalfBinomialLoss(), fit_intercept=fit_intercept + ) + func = loss.loss_gradient elif solver == "newton-cg": - func = _logistic_loss - - def grad(x, *args): - return _logistic_loss_and_grad(x, *args)[1] - - hess = _logistic_grad_hess + loss = LinearModelLoss( + base_loss=HalfBinomialLoss(), fit_intercept=fit_intercept + ) + func = loss.loss + grad = loss.gradient + hess = loss.gradient_hessian_product # hess = [gradient, hessp] warm_start_sag = {"coef": np.expand_dims(w0, axis=1)} coefs = list() n_iter = np.zeros(len(Cs), dtype=np.int32) for i, C in enumerate(Cs): if solver == "lbfgs": + l2_reg_strength = 1.0 / C iprint = [-1, 50, 1, 100, 101][ np.searchsorted(np.array([0, 1, 2, 3]), verbose) ] @@ -807,7 +438,7 @@ def grad(x, *args): w0, method="L-BFGS-B", jac=True, - args=(X, target, 1.0 / C, sample_weight), + args=(X, target, sample_weight, l2_reg_strength, n_threads), options={"iprint": iprint, "gtol": tol, "maxiter": max_iter}, ) n_iter_i = _check_optimize_result( @@ -818,7 +449,8 @@ def grad(x, *args): ) w0, loss = opt_res.x, opt_res.fun elif solver == "newton-cg": - args = (X, target, 1.0 / C, sample_weight) + l2_reg_strength = 1.0 / C + args = (X, target, sample_weight, l2_reg_strength, n_threads) w0, n_iter_i = _newton_cg( hess, func, grad, w0, args=args, maxiter=max_iter, tol=tol ) @@ -885,7 +517,10 @@ def grad(x, *args): if multi_class == "multinomial": n_classes = max(2, classes.size) - multi_w0 = np.reshape(w0, (n_classes, -1)) + if solver in ["lbfgs", "newton-cg"]: + multi_w0 = np.reshape(w0, (n_classes, -1), order="F") + else: + multi_w0 = w0 if n_classes == 2: multi_w0 = multi_w0[1][np.newaxis, :] coefs.append(multi_w0.copy()) @@ -1584,6 +1219,21 @@ def fit(self, X, y, sample_weight=None): prefer = "threads" else: prefer = "processes" + + # TODO: Refactor this to avoid joblib parallelism entirely when doing binary + # and multinomial multiclass classification and use joblib only for the + # one-vs-rest multiclass case. + if ( + solver in ["lbfgs", "newton-cg"] + and len(classes_) == 1 + and effective_n_jobs(self.n_jobs) == 1 + ): + # In the future, we would like n_threads = _openmp_effective_n_threads() + # For the time being, we just do + n_threads = 1 + else: + n_threads = 1 + fold_coefs_ = Parallel(n_jobs=self.n_jobs, verbose=self.verbose, prefer=prefer)( path_func( X, @@ -1604,6 +1254,7 @@ def fit(self, X, y, sample_weight=None): penalty=penalty, max_squared_sum=max_squared_sum, sample_weight=sample_weight, + n_threads=n_threads, ) for class_, warm_start_coef_ in zip(classes_, warm_start_coef) )
diff --git a/sklearn/linear_model/tests/test_linear_loss.py b/sklearn/linear_model/tests/test_linear_loss.py new file mode 100644 index 0000000000000..d4e20ad69ca8a --- /dev/null +++ b/sklearn/linear_model/tests/test_linear_loss.py @@ -0,0 +1,308 @@ +""" +Tests for LinearModelLoss + +Note that correctness of losses (which compose LinearModelLoss) is already well +covered in the _loss module. +""" +import pytest +import numpy as np +from numpy.testing import assert_allclose +from scipy import linalg, optimize, sparse + +from sklearn._loss.loss import ( + HalfBinomialLoss, + HalfMultinomialLoss, + HalfPoissonLoss, +) +from sklearn.datasets import make_low_rank_matrix +from sklearn.linear_model._linear_loss import LinearModelLoss +from sklearn.utils.extmath import squared_norm + + +# We do not need to test all losses, just what LinearModelLoss does on top of the +# base losses. +LOSSES = [HalfBinomialLoss, HalfMultinomialLoss, HalfPoissonLoss] + + +def random_X_y_coef( + linear_model_loss, n_samples, n_features, coef_bound=(-2, 2), seed=42 +): + """Random generate y, X and coef in valid range.""" + rng = np.random.RandomState(seed) + n_dof = n_features + linear_model_loss.fit_intercept + X = make_low_rank_matrix( + n_samples=n_samples, + n_features=n_features, + random_state=rng, + ) + + if linear_model_loss.base_loss.is_multiclass: + n_classes = linear_model_loss.base_loss.n_classes + coef = np.empty((n_classes, n_dof)) + coef.flat[:] = rng.uniform( + low=coef_bound[0], + high=coef_bound[1], + size=n_classes * n_dof, + ) + if linear_model_loss.fit_intercept: + raw_prediction = X @ coef[:, :-1].T + coef[:, -1] + else: + raw_prediction = X @ coef.T + proba = linear_model_loss.base_loss.link.inverse(raw_prediction) + + # y = rng.choice(np.arange(n_classes), p=proba) does not work. + # See https://stackoverflow.com/a/34190035/16761084 + def choice_vectorized(items, p): + s = p.cumsum(axis=1) + r = rng.rand(p.shape[0])[:, None] + k = (s < r).sum(axis=1) + return items[k] + + y = choice_vectorized(np.arange(n_classes), p=proba).astype(np.float64) + else: + coef = np.empty((n_dof,)) + coef.flat[:] = rng.uniform( + low=coef_bound[0], + high=coef_bound[1], + size=n_dof, + ) + if linear_model_loss.fit_intercept: + raw_prediction = X @ coef[:-1] + coef[-1] + else: + raw_prediction = X @ coef + y = linear_model_loss.base_loss.link.inverse( + raw_prediction + rng.uniform(low=-1, high=1, size=n_samples) + ) + + return X, y, coef + + [email protected]("base_loss", LOSSES) [email protected]("fit_intercept", [False, True]) [email protected]("sample_weight", [None, "range"]) [email protected]("l2_reg_strength", [0, 1]) +def test_loss_gradients_are_the_same( + base_loss, fit_intercept, sample_weight, l2_reg_strength +): + """Test that loss and gradient are the same across different functions.""" + loss = LinearModelLoss(base_loss=base_loss(), fit_intercept=fit_intercept) + X, y, coef = random_X_y_coef( + linear_model_loss=loss, n_samples=10, n_features=5, seed=42 + ) + + if sample_weight == "range": + sample_weight = np.linspace(1, y.shape[0], num=y.shape[0]) + + l1 = loss.loss( + coef, X, y, sample_weight=sample_weight, l2_reg_strength=l2_reg_strength + ) + g1 = loss.gradient( + coef, X, y, sample_weight=sample_weight, l2_reg_strength=l2_reg_strength + ) + l2, g2 = loss.loss_gradient( + coef, X, y, sample_weight=sample_weight, l2_reg_strength=l2_reg_strength + ) + g3, h3 = loss.gradient_hessian_product( + coef, X, y, sample_weight=sample_weight, l2_reg_strength=l2_reg_strength + ) + + assert_allclose(l1, l2) + assert_allclose(g1, g2) + assert_allclose(g1, g3) + + # same for sparse X + X = sparse.csr_matrix(X) + l1_sp = loss.loss( + coef, X, y, sample_weight=sample_weight, l2_reg_strength=l2_reg_strength + ) + g1_sp = loss.gradient( + coef, X, y, sample_weight=sample_weight, l2_reg_strength=l2_reg_strength + ) + l2_sp, g2_sp = loss.loss_gradient( + coef, X, y, sample_weight=sample_weight, l2_reg_strength=l2_reg_strength + ) + g3_sp, h3_sp = loss.gradient_hessian_product( + coef, X, y, sample_weight=sample_weight, l2_reg_strength=l2_reg_strength + ) + + assert_allclose(l1, l1_sp) + assert_allclose(l1, l2_sp) + assert_allclose(g1, g1_sp) + assert_allclose(g1, g2_sp) + assert_allclose(g1, g3_sp) + assert_allclose(h3(g1), h3_sp(g1_sp)) + + [email protected]("base_loss", LOSSES) [email protected]("sample_weight", [None, "range"]) [email protected]("l2_reg_strength", [0, 1]) [email protected]("X_sparse", [False, True]) +def test_loss_gradients_hessp_intercept( + base_loss, sample_weight, l2_reg_strength, X_sparse +): + """Test that loss and gradient handle intercept correctly.""" + loss = LinearModelLoss(base_loss=base_loss(), fit_intercept=False) + loss_inter = LinearModelLoss(base_loss=base_loss(), fit_intercept=True) + n_samples, n_features = 10, 5 + X, y, coef = random_X_y_coef( + linear_model_loss=loss, n_samples=n_samples, n_features=n_features, seed=42 + ) + + X[:, -1] = 1 # make last column of 1 to mimic intercept term + X_inter = X[ + :, :-1 + ] # exclude intercept column as it is added automatically by loss_inter + + if X_sparse: + X = sparse.csr_matrix(X) + + if sample_weight == "range": + sample_weight = np.linspace(1, y.shape[0], num=y.shape[0]) + + l, g = loss.loss_gradient( + coef, X, y, sample_weight=sample_weight, l2_reg_strength=l2_reg_strength + ) + _, hessp = loss.gradient_hessian_product( + coef, X, y, sample_weight=sample_weight, l2_reg_strength=l2_reg_strength + ) + l_inter, g_inter = loss_inter.loss_gradient( + coef, X_inter, y, sample_weight=sample_weight, l2_reg_strength=l2_reg_strength + ) + _, hessp_inter = loss_inter.gradient_hessian_product( + coef, X_inter, y, sample_weight=sample_weight, l2_reg_strength=l2_reg_strength + ) + + # Note, that intercept gets no L2 penalty. + assert l == pytest.approx( + l_inter + 0.5 * l2_reg_strength * squared_norm(coef.T[-1]) + ) + + g_inter_corrected = g_inter + g_inter_corrected.T[-1] += l2_reg_strength * coef.T[-1] + assert_allclose(g, g_inter_corrected) + + s = np.random.RandomState(42).randn(*coef.shape) + h = hessp(s) + h_inter = hessp_inter(s) + h_inter_corrected = h_inter + h_inter_corrected.T[-1] += l2_reg_strength * s.T[-1] + assert_allclose(h, h_inter_corrected) + + [email protected]("base_loss", LOSSES) [email protected]("fit_intercept", [False, True]) [email protected]("sample_weight", [None, "range"]) [email protected]("l2_reg_strength", [0, 1]) +def test_gradients_hessians_numerically( + base_loss, fit_intercept, sample_weight, l2_reg_strength +): + """Test gradients and hessians with numerical derivatives. + + Gradient should equal the numerical derivatives of the loss function. + Hessians should equal the numerical derivatives of gradients. + """ + loss = LinearModelLoss(base_loss=base_loss(), fit_intercept=fit_intercept) + n_samples, n_features = 10, 5 + X, y, coef = random_X_y_coef( + linear_model_loss=loss, n_samples=n_samples, n_features=n_features, seed=42 + ) + coef = coef.ravel(order="F") # this is important only for multinomial loss + + if sample_weight == "range": + sample_weight = np.linspace(1, y.shape[0], num=y.shape[0]) + + # 1. Check gradients numerically + eps = 1e-6 + g, hessp = loss.gradient_hessian_product( + coef, X, y, sample_weight=sample_weight, l2_reg_strength=l2_reg_strength + ) + # Use a trick to get central finite difference of accuracy 4 (five-point stencil) + # https://en.wikipedia.org/wiki/Numerical_differentiation + # https://en.wikipedia.org/wiki/Finite_difference_coefficient + # approx_g1 = (f(x + eps) - f(x - eps)) / (2*eps) + approx_g1 = optimize.approx_fprime( + coef, + lambda coef: loss.loss( + coef - eps, + X, + y, + sample_weight=sample_weight, + l2_reg_strength=l2_reg_strength, + ), + 2 * eps, + ) + # approx_g2 = (f(x + 2*eps) - f(x - 2*eps)) / (4*eps) + approx_g2 = optimize.approx_fprime( + coef, + lambda coef: loss.loss( + coef - 2 * eps, + X, + y, + sample_weight=sample_weight, + l2_reg_strength=l2_reg_strength, + ), + 4 * eps, + ) + # Five-point stencil approximation + # See: https://en.wikipedia.org/wiki/Five-point_stencil#1D_first_derivative + approx_g = (4 * approx_g1 - approx_g2) / 3 + assert_allclose(g, approx_g, rtol=1e-2, atol=1e-8) + + # 2. Check hessp numerically along the second direction of the gradient + vector = np.zeros_like(g) + vector[1] = 1 + hess_col = hessp(vector) + # Computation of the Hessian is particularly fragile to numerical errors when doing + # simple finite differences. Here we compute the grad along a path in the direction + # of the vector and then use a least-square regression to estimate the slope + eps = 1e-3 + d_x = np.linspace(-eps, eps, 30) + d_grad = np.array( + [ + loss.gradient( + coef + t * vector, + X, + y, + sample_weight=sample_weight, + l2_reg_strength=l2_reg_strength, + ) + for t in d_x + ] + ) + d_grad -= d_grad.mean(axis=0) + approx_hess_col = linalg.lstsq(d_x[:, np.newaxis], d_grad)[0].ravel() + assert_allclose(approx_hess_col, hess_col, rtol=1e-3) + + [email protected]("fit_intercept", [False, True]) +def test_multinomial_coef_shape(fit_intercept): + """Test that multinomial LinearModelLoss respects shape of coef.""" + loss = LinearModelLoss(base_loss=HalfMultinomialLoss(), fit_intercept=fit_intercept) + n_samples, n_features = 10, 5 + X, y, coef = random_X_y_coef( + linear_model_loss=loss, n_samples=n_samples, n_features=n_features, seed=42 + ) + s = np.random.RandomState(42).randn(*coef.shape) + + l, g = loss.loss_gradient(coef, X, y) + g1 = loss.gradient(coef, X, y) + g2, hessp = loss.gradient_hessian_product(coef, X, y) + h = hessp(s) + assert g.shape == coef.shape + assert h.shape == coef.shape + assert_allclose(g, g1) + assert_allclose(g, g2) + + coef_r = coef.ravel(order="F") + s_r = s.ravel(order="F") + l_r, g_r = loss.loss_gradient(coef_r, X, y) + g1_r = loss.gradient(coef_r, X, y) + g2_r, hessp_r = loss.gradient_hessian_product(coef_r, X, y) + h_r = hessp_r(s_r) + assert g_r.shape == coef_r.shape + assert h_r.shape == coef_r.shape + assert_allclose(g_r, g1_r) + assert_allclose(g_r, g2_r) + + assert_allclose(g, g_r.reshape(loss.base_loss.n_classes, -1, order="F")) + assert_allclose(h, h_r.reshape(loss.base_loss.n_classes, -1, order="F")) diff --git a/sklearn/linear_model/tests/test_logistic.py b/sklearn/linear_model/tests/test_logistic.py index 3bdfec46e30dc..0c35795b8b642 100644 --- a/sklearn/linear_model/tests/test_logistic.py +++ b/sklearn/linear_model/tests/test_logistic.py @@ -5,8 +5,7 @@ import numpy as np from numpy.testing import assert_allclose, assert_almost_equal from numpy.testing import assert_array_almost_equal, assert_array_equal -import scipy.sparse as sp -from scipy import linalg, optimize, sparse +from scipy import sparse import pytest @@ -28,18 +27,14 @@ from sklearn.exceptions import ConvergenceWarning from sklearn.linear_model._logistic import ( - LogisticRegression, + _log_reg_scoring_path, _logistic_regression_path, + LogisticRegression, LogisticRegressionCV, - _logistic_loss_and_grad, - _logistic_grad_hess, - _multinomial_grad_hess, - _logistic_loss, - _log_reg_scoring_path, ) X = [[-1, 0], [0, 1], [1, 1]] -X_sp = sp.csr_matrix(X) +X_sp = sparse.csr_matrix(X) Y1 = [0, 1, 1] Y2 = [2, 1, 0] iris = load_iris() @@ -317,10 +312,10 @@ def test_sparsify(): pred_d_d = clf.decision_function(iris.data) clf.sparsify() - assert sp.issparse(clf.coef_) + assert sparse.issparse(clf.coef_) pred_s_d = clf.decision_function(iris.data) - sp_data = sp.coo_matrix(iris.data) + sp_data = sparse.coo_matrix(iris.data) pred_s_s = clf.decision_function(sp_data) clf.densify() @@ -501,82 +496,6 @@ def test_liblinear_dual_random_state(): assert_array_almost_equal(lr1.coef_, lr3.coef_) -def test_logistic_loss_and_grad(): - X_ref, y = make_classification(n_samples=20, random_state=0) - n_features = X_ref.shape[1] - - X_sp = X_ref.copy() - X_sp[X_sp < 0.1] = 0 - X_sp = sp.csr_matrix(X_sp) - for X in (X_ref, X_sp): - w = np.zeros(n_features) - - # First check that our derivation of the grad is correct - loss, grad = _logistic_loss_and_grad(w, X, y, alpha=1.0) - approx_grad = optimize.approx_fprime( - w, lambda w: _logistic_loss_and_grad(w, X, y, alpha=1.0)[0], 1e-3 - ) - assert_array_almost_equal(grad, approx_grad, decimal=2) - - # Second check that our intercept implementation is good - w = np.zeros(n_features + 1) - loss_interp, grad_interp = _logistic_loss_and_grad(w, X, y, alpha=1.0) - assert_array_almost_equal(loss, loss_interp) - - approx_grad = optimize.approx_fprime( - w, lambda w: _logistic_loss_and_grad(w, X, y, alpha=1.0)[0], 1e-3 - ) - assert_array_almost_equal(grad_interp, approx_grad, decimal=2) - - -def test_logistic_grad_hess(): - rng = np.random.RandomState(0) - n_samples, n_features = 50, 5 - X_ref = rng.randn(n_samples, n_features) - y = np.sign(X_ref.dot(5 * rng.randn(n_features))) - X_ref -= X_ref.mean() - X_ref /= X_ref.std() - X_sp = X_ref.copy() - X_sp[X_sp < 0.1] = 0 - X_sp = sp.csr_matrix(X_sp) - for X in (X_ref, X_sp): - w = np.full(n_features, 0.1) - - # First check that _logistic_grad_hess is consistent - # with _logistic_loss_and_grad - loss, grad = _logistic_loss_and_grad(w, X, y, alpha=1.0) - grad_2, hess = _logistic_grad_hess(w, X, y, alpha=1.0) - assert_array_almost_equal(grad, grad_2) - - # Now check our hessian along the second direction of the grad - vector = np.zeros_like(grad) - vector[1] = 1 - hess_col = hess(vector) - - # Computation of the Hessian is particularly fragile to numerical - # errors when doing simple finite differences. Here we compute the - # grad along a path in the direction of the vector and then use a - # least-square regression to estimate the slope - e = 1e-3 - d_x = np.linspace(-e, e, 30) - d_grad = np.array( - [_logistic_loss_and_grad(w + t * vector, X, y, alpha=1.0)[1] for t in d_x] - ) - - d_grad -= d_grad.mean(axis=0) - approx_hess_col = linalg.lstsq(d_x[:, np.newaxis], d_grad)[0].ravel() - - assert_array_almost_equal(approx_hess_col, hess_col, decimal=3) - - # Second check that our intercept implementation is good - w = np.zeros(n_features + 1) - loss_interp, grad_interp = _logistic_loss_and_grad(w, X, y, alpha=1.0) - loss_interp_2 = _logistic_loss(w, X, y, alpha=1.0) - grad_interp_2, hess = _logistic_grad_hess(w, X, y, alpha=1.0) - assert_array_almost_equal(loss_interp, loss_interp_2) - assert_array_almost_equal(grad_interp, grad_interp_2) - - def test_logistic_cv(): # test for LogisticRegressionCV object n_samples, n_features = 50, 5 @@ -690,7 +609,7 @@ def test_multinomial_logistic_regression_string_inputs(): def test_logistic_cv_sparse(): X, y = make_classification(n_samples=50, n_features=5, random_state=0) X[X < 1.0] = 0.0 - csr = sp.csr_matrix(X) + csr = sparse.csr_matrix(X) clf = LogisticRegressionCV() clf.fit(X, y) @@ -701,40 +620,6 @@ def test_logistic_cv_sparse(): assert clfs.C_ == clf.C_ -def test_intercept_logistic_helper(): - n_samples, n_features = 10, 5 - X, y = make_classification( - n_samples=n_samples, n_features=n_features, random_state=0 - ) - - # Fit intercept case. - alpha = 1.0 - w = np.ones(n_features + 1) - grad_interp, hess_interp = _logistic_grad_hess(w, X, y, alpha) - loss_interp = _logistic_loss(w, X, y, alpha) - - # Do not fit intercept. This can be considered equivalent to adding - # a feature vector of ones, i.e column of one vectors. - X_ = np.hstack((X, np.ones(10)[:, np.newaxis])) - grad, hess = _logistic_grad_hess(w, X_, y, alpha) - loss = _logistic_loss(w, X_, y, alpha) - - # In the fit_intercept=False case, the feature vector of ones is - # penalized. This should be taken care of. - assert_almost_equal(loss_interp + 0.5 * (w[-1] ** 2), loss) - - # Check gradient. - assert_array_almost_equal(grad_interp[:n_features], grad[:n_features]) - assert_almost_equal(grad_interp[-1] + alpha * w[-1], grad[-1]) - - rng = np.random.RandomState(0) - grad = rng.rand(n_features + 1) - hess_interp = hess_interp(grad) - hess = hess(grad) - assert_array_almost_equal(hess_interp[:n_features], hess[:n_features]) - assert_almost_equal(hess_interp[-1] + alpha * grad[-1], hess[-1]) - - def test_ovr_multinomial_iris(): # Test that OvR and multinomial are correct using the iris dataset. train, target = iris.data, iris.target @@ -1107,41 +992,6 @@ def test_logistic_regression_multinomial(): assert_allclose(clf_path.intercept_, ref_i.intercept_, rtol=2e-2) -def test_multinomial_grad_hess(): - rng = np.random.RandomState(0) - n_samples, n_features, n_classes = 100, 5, 3 - X = rng.randn(n_samples, n_features) - w = rng.rand(n_classes, n_features) - Y = np.zeros((n_samples, n_classes)) - ind = np.argmax(np.dot(X, w.T), axis=1) - Y[range(0, n_samples), ind] = 1 - w = w.ravel() - sample_weights = np.ones(X.shape[0]) - grad, hessp = _multinomial_grad_hess( - w, X, Y, alpha=1.0, sample_weight=sample_weights - ) - # extract first column of hessian matrix - vec = np.zeros(n_features * n_classes) - vec[0] = 1 - hess_col = hessp(vec) - - # Estimate hessian using least squares as done in - # test_logistic_grad_hess - e = 1e-3 - d_x = np.linspace(-e, e, 30) - d_grad = np.array( - [ - _multinomial_grad_hess( - w + t * vec, X, Y, alpha=1.0, sample_weight=sample_weights - )[0] - for t in d_x - ] - ) - d_grad -= d_grad.mean(axis=0) - approx_hess_col = linalg.lstsq(d_x[:, np.newaxis], d_grad)[0].ravel() - assert_array_almost_equal(hess_col, approx_hess_col) - - def test_liblinear_decision_function_zero(): # Test negative prediction when decision_function values are zero. # Liblinear predicts the positive class when decision_function values @@ -1533,8 +1383,8 @@ def test_dtype_match(solver, multi_class, fit_intercept): y_32 = np.array(Y1).astype(np.float32) X_64 = np.array(X).astype(np.float64) y_64 = np.array(Y1).astype(np.float64) - X_sparse_32 = sp.csr_matrix(X, dtype=np.float32) - X_sparse_64 = sp.csr_matrix(X, dtype=np.float64) + X_sparse_32 = sparse.csr_matrix(X, dtype=np.float32) + X_sparse_64 = sparse.csr_matrix(X, dtype=np.float64) solver_tol = 5e-4 lr_templ = LogisticRegression( @@ -2236,7 +2086,7 @@ def test_large_sparse_matrix(solver): # Non-regression test for pull-request #21093. # generate sparse matrix with int64 indices - X = sp.rand(20, 10, format="csr") + X = sparse.rand(20, 10, format="csr") for attr in ["indices", "indptr"]: setattr(X, attr, getattr(X, attr).astype("int64")) y = np.random.randint(2, size=X.shape[0]) diff --git a/sklearn/linear_model/tests/test_sag.py b/sklearn/linear_model/tests/test_sag.py index 88df6621f8176..d3a27c4088ab7 100644 --- a/sklearn/linear_model/tests/test_sag.py +++ b/sklearn/linear_model/tests/test_sag.py @@ -10,11 +10,12 @@ import scipy.sparse as sp from scipy.special import logsumexp +from sklearn._loss.loss import HalfMultinomialLoss +from sklearn.linear_model._linear_loss import LinearModelLoss from sklearn.linear_model._sag import get_auto_step_size from sklearn.linear_model._sag_fast import _multinomial_grad_loss_all_samples from sklearn.linear_model import LogisticRegression, Ridge from sklearn.linear_model._base import make_dataset -from sklearn.linear_model._logistic import _multinomial_loss_grad from sklearn.utils.extmath import row_norms from sklearn.utils._testing import assert_almost_equal @@ -933,13 +934,14 @@ def test_multinomial_loss(): dataset, weights, intercept, n_samples, n_features, n_classes ) # compute loss and gradient like in multinomial LogisticRegression - lbin = LabelBinarizer() - Y_bin = lbin.fit_transform(y) - weights_intercept = np.vstack((weights, intercept)).T.ravel() - loss_2, grad_2, _ = _multinomial_loss_grad( - weights_intercept, X, Y_bin, 0.0, sample_weights + loss = LinearModelLoss( + base_loss=HalfMultinomialLoss(n_classes=n_classes), + fit_intercept=True, + ) + weights_intercept = np.vstack((weights, intercept)).T + loss_2, grad_2 = loss.loss_gradient( + weights_intercept, X, y, l2_reg_strength=0.0, sample_weight=sample_weights ) - grad_2 = grad_2.reshape(n_classes, -1) grad_2 = grad_2[:, :-1].T # comparison @@ -951,7 +953,7 @@ def test_multinomial_loss_ground_truth(): # n_samples, n_features, n_classes = 4, 2, 3 n_classes = 3 X = np.array([[1.1, 2.2], [2.2, -4.4], [3.3, -2.2], [1.1, 1.1]]) - y = np.array([0, 1, 2, 0]) + y = np.array([0, 1, 2, 0], dtype=np.float64) lbin = LabelBinarizer() Y_bin = lbin.fit_transform(y) @@ -966,11 +968,14 @@ def test_multinomial_loss_ground_truth(): diff = sample_weights[:, np.newaxis] * (np.exp(p) - Y_bin) grad_1 = np.dot(X.T, diff) - weights_intercept = np.vstack((weights, intercept)).T.ravel() - loss_2, grad_2, _ = _multinomial_loss_grad( - weights_intercept, X, Y_bin, 0.0, sample_weights + loss = LinearModelLoss( + base_loss=HalfMultinomialLoss(n_classes=n_classes), + fit_intercept=True, + ) + weights_intercept = np.vstack((weights, intercept)).T + loss_2, grad_2 = loss.loss_gradient( + weights_intercept, X, y, l2_reg_strength=0.0, sample_weight=sample_weights ) - grad_2 = grad_2.reshape(n_classes, -1) grad_2 = grad_2[:, :-1].T assert_almost_equal(loss_1, loss_2)
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 39f8e405ebf7c..b88e54b46a4bf 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -393,6 +393,15 @@ Changelog\n beginning which speeds up fitting.\n :pr:`22206` by :user:`Christian Lorentzen <lorentzenchr>`.\n \n+- |Enhancement| :class:`~linear_model.LogisticRegression` is faster for\n+ ``solvers=\"lbfgs\"`` and ``solver=\"newton-cg\"``, for binary and in particular for\n+ multiclass problems thanks to the new private loss function module. In the multiclass\n+ case, the memory consumption has also been reduced for these solvers as the target is\n+ now label encoded (mapped to integers) instead of label binarized (one-hot encoded).\n+ The more classes, the larger the benefit.\n+ :pr:`21808`, :pr:`20567` and :pr:`21814` by\n+ :user:`Christian Lorentzen <lorentzenchr>`.\n+\n - |Enhancement| Rename parameter `base_estimator` to `estimator` in\n :class:`linear_model.RANSACRegressor` to improve readability and consistency.\n `base_estimator` is deprecated and will be removed in 1.3.\n" } ]
1.01
39c341ad91b545c895ede9c6240a04659b82defb
[ "sklearn/linear_model/tests/test_logistic.py::test_max_iter[newton-cg-newton-cg failed to converge. Increase the number of iterations.-multinomial-max_iter2]", "sklearn/linear_model/tests/test_logistic.py::test_multinomial_validation[newton-cg]", "sklearn/linear_model/tests/test_logistic.py::test_sample_weight_not_modified[class_weight0-ovr]", "sklearn/linear_model/tests/test_logistic.py::test_max_iter[lbfgs-lbfgs failed to converge-multinomial-max_iter1]", "sklearn/linear_model/tests/test_logistic.py::test_logistic_regression_solvers_multiclass", "sklearn/linear_model/tests/test_logistic.py::test_LogisticRegression_elastic_net_objective[0.9-0.046415888336127795]", "sklearn/linear_model/tests/test_logistic.py::test_logistic_regression_cv_refit[l2-42]", "sklearn/linear_model/tests/test_logistic.py::test_max_iter[newton-cg-newton-cg failed to converge. Increase the number of iterations.-ovr-max_iter0]", "sklearn/linear_model/tests/test_logistic.py::test_LogisticRegressionCV_no_refit[ovr-elasticnet]", "sklearn/linear_model/tests/test_logistic.py::test_l1_ratio_param[2]", "sklearn/linear_model/tests/test_logistic.py::test_elastic_net_versus_sgd[0.5-2.1544346900318843]", "sklearn/linear_model/tests/test_logistic.py::test_sample_weight_not_modified[class_weight0-multinomial]", "sklearn/linear_model/tests/test_logistic.py::test_max_iter[lbfgs-lbfgs failed to converge-multinomial-max_iter2]", "sklearn/linear_model/tests/test_logistic.py::test_scores_attribute_layout_elasticnet", "sklearn/linear_model/tests/test_logistic.py::test_elastic_net_l1_l2_equivalence[l2-0-10]", "sklearn/linear_model/tests/test_logistic.py::test_max_iter[saga-The max_iter was reached which means the coef_ did not converge-multinomial-max_iter3]", "sklearn/linear_model/tests/test_logistic.py::test_check_solver_option[LogisticRegression]", "sklearn/linear_model/tests/test_logistic.py::test_elastic_net_vs_l1_l2[0.001]", "sklearn/linear_model/tests/test_logistic.py::test_elastic_net_versus_sgd[0.9-100.0]", "sklearn/linear_model/tests/test_logistic.py::test_multinomial_logistic_regression_string_inputs", "sklearn/linear_model/tests/test_logistic.py::test_logistic_cv_multinomial_score[precision-multiclass_agg_list1]", "sklearn/linear_model/tests/test_logistic.py::test_saga_sparse", "sklearn/linear_model/tests/test_logistic.py::test_n_iter[liblinear]", "sklearn/linear_model/tests/test_logistic.py::test_max_iter[newton-cg-newton-cg failed to converge. Increase the number of iterations.-multinomial-max_iter3]", "sklearn/linear_model/tests/test_logistic.py::test_liblinear_logregcv_sparse", "sklearn/linear_model/tests/test_logistic.py::test_dtype_match[False-liblinear-ovr]", "sklearn/linear_model/tests/test_logistic.py::test_logreg_l1_sparse_data", "sklearn/linear_model/tests/test_logistic.py::test_predict_2_classes", "sklearn/linear_model/tests/test_logistic.py::test_warm_start[multinomial-False-False-sag]", "sklearn/linear_model/tests/test_logistic.py::test_large_sparse_matrix[liblinear]", "sklearn/linear_model/tests/test_logistic.py::test_max_iter[newton-cg-newton-cg failed to converge. Increase the number of iterations.-ovr-max_iter1]", "sklearn/linear_model/tests/test_logistic.py::test_warm_start[ovr-False-True-sag]", "sklearn/linear_model/tests/test_logistic.py::test_LogisticRegression_elastic_net_objective[0.1-0.046415888336127795]", "sklearn/linear_model/tests/test_logistic.py::test_liblinear_decision_function_zero", "sklearn/linear_model/tests/test_logistic.py::test_warm_start[ovr-True-True-lbfgs]", "sklearn/linear_model/tests/test_logistic.py::test_max_iter[lbfgs-lbfgs failed to converge-ovr-max_iter2]", "sklearn/linear_model/tests/test_logistic.py::test_max_iter[saga-The max_iter was reached which means the coef_ did not converge-ovr-max_iter2]", "sklearn/linear_model/tests/test_logistic.py::test_max_iter[saga-The max_iter was reached which means the coef_ did not converge-ovr-max_iter1]", "sklearn/linear_model/tests/test_logistic.py::test_warm_start[multinomial-False-False-saga]", "sklearn/linear_model/tests/test_logistic.py::test_multinomial_binary[lbfgs]", "sklearn/linear_model/tests/test_logistic.py::test_max_iter[newton-cg-newton-cg failed to converge. Increase the number of iterations.-multinomial-max_iter1]", "sklearn/linear_model/tests/test_logistic.py::test_l1_ratios_param[l1_ratios1]", "sklearn/linear_model/tests/test_logistic.py::test_lr_liblinear_warning", "sklearn/linear_model/tests/test_logistic.py::test_sample_weight_not_modified[balanced-auto]", "sklearn/linear_model/tests/test_logistic.py::test_max_iter[lbfgs-lbfgs failed to converge-multinomial-max_iter3]", "sklearn/linear_model/tests/test_logistic.py::test_max_iter[sag-The max_iter was reached which means the coef_ did not converge-multinomial-max_iter1]", "sklearn/linear_model/tests/test_logistic.py::test_max_iter[saga-The max_iter was reached which means the coef_ did not converge-multinomial-max_iter2]", "sklearn/linear_model/tests/test_logistic.py::test_logistic_regression_path_coefs_multinomial", "sklearn/linear_model/tests/test_logistic.py::test_logistic_regression_sample_weights", "sklearn/linear_model/tests/test_logistic.py::test_ovr_multinomial_iris", "sklearn/linear_model/tests/test_logistic.py::test_elastic_net_versus_sgd[0.1-2.1544346900318843]", "sklearn/linear_model/tests/test_logistic.py::test_sample_weight_not_modified[class_weight0-auto]", "sklearn/linear_model/tests/test_logistic.py::test_nan", "sklearn/linear_model/tests/test_logistic.py::test_max_iter[liblinear-Liblinear failed to converge, increase the number of iterations.-ovr-max_iter3]", "sklearn/linear_model/tests/test_logistic.py::test_warm_start[ovr-True-False-saga]", "sklearn/linear_model/tests/test_logistic.py::test_LogisticRegression_elastic_net_objective[0.1-2.1544346900318843]", "sklearn/linear_model/tests/test_logistic.py::test_max_iter[saga-The max_iter was reached which means the coef_ did not converge-multinomial-max_iter1]", "sklearn/linear_model/tests/test_logistic.py::test_logistic_regression_multi_class_auto[saga-LogisticRegressionCV]", "sklearn/linear_model/tests/test_logistic.py::test_warm_start[ovr-True-True-saga]", "sklearn/linear_model/tests/test_logistic.py::test_multinomial_binary_probabilities", "sklearn/linear_model/tests/test_logistic.py::test_warm_start[multinomial-False-True-newton-cg]", "sklearn/linear_model/tests/test_logistic.py::test_write_parameters", "sklearn/linear_model/tests/test_logistic.py::test_elastic_net_versus_sgd[0.5-100.0]", "sklearn/linear_model/tests/test_logistic.py::test_warm_start[multinomial-False-False-newton-cg]", "sklearn/linear_model/tests/test_logistic.py::test_logistic_cv_multinomial_score[recall-multiclass_agg_list4]", "sklearn/linear_model/tests/test_logistic.py::test_dtype_match[False-saga-ovr]", "sklearn/linear_model/tests/test_logistic.py::test_logistic_regression_multi_class_auto[liblinear-LogisticRegression]", "sklearn/linear_model/tests/test_logistic.py::test_multinomial_validation[lbfgs]", "sklearn/linear_model/tests/test_logistic.py::test_max_iter[saga-The max_iter was reached which means the coef_ did not converge-ovr-max_iter0]", "sklearn/linear_model/tests/test_logistic.py::test_multinomial_identifiability_on_iris[False]", "sklearn/linear_model/tests/test_logistic.py::test_logistic_cv_multinomial_score[f1-multiclass_agg_list2]", "sklearn/linear_model/tests/test_logistic.py::test_elastic_net_l1_l2_equivalence[l1-1-10]", "sklearn/linear_model/tests/test_logistic.py::test_warm_start[ovr-False-False-newton-cg]", "sklearn/linear_model/tests/test_logistic.py::test_penalty_none[newton-cg]", "sklearn/linear_model/tests/test_logistic.py::test_logistic_regression_multi_class_auto[liblinear-LogisticRegressionCV]", "sklearn/linear_model/tests/test_logistic.py::test_dtype_match[False-newton-cg-multinomial]", "sklearn/linear_model/tests/test_logistic.py::test_LogisticRegression_elastic_net_objective[0.9-0.001]", "sklearn/linear_model/tests/test_logistic.py::test_consistency_path", "sklearn/linear_model/tests/test_logistic.py::test_logistic_regression_multi_class_auto[sag-LogisticRegressionCV]", "sklearn/linear_model/tests/test_logistic.py::test_dtype_match[True-liblinear-ovr]", "sklearn/linear_model/tests/test_logistic.py::test_elastic_net_l1_l2_equivalence[l1-1-1000000.0]", "sklearn/linear_model/tests/test_logistic.py::test_warm_start[ovr-True-False-lbfgs]", "sklearn/linear_model/tests/test_logistic.py::test_predict_3_classes", "sklearn/linear_model/tests/test_logistic.py::test_logistic_regression_multi_class_auto[newton-cg-LogisticRegression]", "sklearn/linear_model/tests/test_logistic.py::test_logistic_regression_multi_class_auto[sag-LogisticRegression]", "sklearn/linear_model/tests/test_logistic.py::test_large_sparse_matrix[lbfgs]", "sklearn/linear_model/tests/test_logistic.py::test_l1_ratios_param[something_wrong]", "sklearn/linear_model/tests/test_logistic.py::test_elastic_net_l1_l2_equivalence[l1-1-0.1]", "sklearn/linear_model/tests/test_logistic.py::test_LogisticRegression_elastic_net_objective[0.9-100.0]", "sklearn/linear_model/tests/test_logistic.py::test_large_sparse_matrix[newton-cg]", "sklearn/linear_model/tests/test_logistic.py::test_error", "sklearn/linear_model/tests/test_logistic.py::test_warm_start[ovr-False-True-newton-cg]", "sklearn/linear_model/tests/test_logistic.py::test_liblinear_dual_random_state", "sklearn/linear_model/tests/test_logistic.py::test_max_iter[liblinear-Liblinear failed to converge, increase the number of iterations.-ovr-max_iter1]", "sklearn/linear_model/tests/test_logistic.py::test_max_iter[sag-The max_iter was reached which means the coef_ did not converge-ovr-max_iter2]", "sklearn/linear_model/tests/test_logistic.py::test_LogisticRegressionCV_no_refit[multinomial-elasticnet]", "sklearn/linear_model/tests/test_logistic.py::test_warm_start[ovr-False-True-saga]", "sklearn/linear_model/tests/test_logistic.py::test_LogisticRegressionCV_elasticnet_attribute_shapes", "sklearn/linear_model/tests/test_logistic.py::test_max_iter[sag-The max_iter was reached which means the coef_ did not converge-ovr-max_iter3]", "sklearn/linear_model/tests/test_logistic.py::test_multinomial_validation[sag]", "sklearn/linear_model/tests/test_logistic.py::test_n_iter[saga]", "sklearn/linear_model/tests/test_logistic.py::test_logistic_regression_class_weights", "sklearn/linear_model/tests/test_logistic.py::test_LogisticRegressionCV_no_refit[multinomial-l2]", "sklearn/linear_model/tests/test_logistic.py::test_elastic_net_versus_sgd[0.1-0.046415888336127795]", "sklearn/linear_model/tests/test_logistic.py::test_warm_start[ovr-False-False-lbfgs]", "sklearn/linear_model/tests/test_logistic.py::test_max_iter[lbfgs-lbfgs failed to converge-multinomial-max_iter0]", "sklearn/linear_model/tests/test_logistic.py::test_warm_start[multinomial-False-True-lbfgs]", "sklearn/linear_model/tests/test_logistic.py::test_max_iter[lbfgs-lbfgs failed to converge-ovr-max_iter0]", "sklearn/linear_model/tests/test_logistic.py::test_penalty_none[saga]", "sklearn/linear_model/tests/test_logistic.py::test_elastic_net_versus_sgd[0.5-0.046415888336127795]", "sklearn/linear_model/tests/test_logistic.py::test_LogisticRegressionCV_GridSearchCV_elastic_net_ovr", "sklearn/linear_model/tests/test_logistic.py::test_logistic_cv_mock_scorer", "sklearn/linear_model/tests/test_logistic.py::test_penalty_none[sag]", "sklearn/linear_model/tests/test_logistic.py::test_l1_ratio_param[-1]", "sklearn/linear_model/tests/test_logistic.py::test_check_solver_option[LogisticRegressionCV]", "sklearn/linear_model/tests/test_logistic.py::test_logistic_regression_cv_refit[l1-42]", "sklearn/linear_model/tests/test_logistic.py::test_max_iter[sag-The max_iter was reached which means the coef_ did not converge-ovr-max_iter1]", "sklearn/linear_model/tests/test_logistic.py::test_logreg_intercept_scaling", "sklearn/linear_model/tests/test_logistic.py::test_inconsistent_input", "sklearn/linear_model/tests/test_logistic.py::test_elastic_net_versus_sgd[0.1-100.0]", "sklearn/linear_model/tests/test_logistic.py::test_max_iter[lbfgs-lbfgs failed to converge-ovr-max_iter3]", "sklearn/linear_model/tests/test_logistic.py::test_warm_start[multinomial-True-True-saga]", "sklearn/linear_model/tests/test_logistic.py::test_l1_ratios_param[l1_ratios0]", "sklearn/linear_model/tests/test_logistic.py::test_warm_start[multinomial-True-True-newton-cg]", "sklearn/linear_model/tests/test_logistic.py::test_logisticregression_liblinear_sample_weight[params2]", "sklearn/linear_model/tests/test_logistic.py::test_warm_start[ovr-False-False-sag]", "sklearn/linear_model/tests/test_logistic.py::test_max_iter[sag-The max_iter was reached which means the coef_ did not converge-multinomial-max_iter0]", "sklearn/linear_model/tests/test_logistic.py::test_warm_start[ovr-True-True-sag]", "sklearn/linear_model/tests/test_logistic.py::test_warm_start[multinomial-False-True-saga]", "sklearn/linear_model/tests/test_logistic.py::test_predict_iris", "sklearn/linear_model/tests/test_logistic.py::test_multinomial_validation[saga]", "sklearn/linear_model/tests/test_logistic.py::test_elastic_net_l1_l2_equivalence[l2-0-1]", "sklearn/linear_model/tests/test_logistic.py::test_elastic_net_vs_l1_l2[1000000.0]", "sklearn/linear_model/tests/test_logistic.py::test_dtype_match[True-newton-cg-multinomial]", "sklearn/linear_model/tests/test_logistic.py::test_logistic_regression_multi_class_auto[lbfgs-LogisticRegressionCV]", "sklearn/linear_model/tests/test_logistic.py::test_warm_start[ovr-True-False-newton-cg]", "sklearn/linear_model/tests/test_logistic.py::test_n_iter[lbfgs]", "sklearn/linear_model/tests/test_logistic.py::test_n_iter[newton-cg]", "sklearn/linear_model/tests/test_logistic.py::test_max_iter[liblinear-Liblinear failed to converge, increase the number of iterations.-ovr-max_iter2]", "sklearn/linear_model/tests/test_logistic.py::test_sample_weight_not_modified[balanced-ovr]", "sklearn/linear_model/tests/test_logistic.py::test_dtype_match[True-saga-ovr]", "sklearn/linear_model/tests/test_logistic.py::test_elastic_net_l1_l2_equivalence[l2-0-100]", "sklearn/linear_model/tests/test_logistic.py::test_multinomial_binary[saga]", "sklearn/linear_model/tests/test_logistic.py::test_logreg_l1", "sklearn/linear_model/tests/test_logistic.py::test_LogisticRegression_elastic_net_objective[0.1-0.001]", "sklearn/linear_model/tests/test_logistic.py::test_logistic_cv_multinomial_score[neg_log_loss-multiclass_agg_list3]", "sklearn/linear_model/tests/test_logistic.py::test_warm_start[multinomial-True-False-sag]", "sklearn/linear_model/tests/test_logistic.py::test_logistic_regression_multi_class_auto[newton-cg-LogisticRegressionCV]", "sklearn/linear_model/tests/test_logistic.py::test_LogisticRegressionCV_GridSearchCV_elastic_net[ovr]", "sklearn/linear_model/tests/test_logistic.py::test_elastic_net_versus_sgd[0.1-0.001]", "sklearn/linear_model/tests/test_logistic.py::test_elastic_net_versus_sgd[0.9-2.1544346900318843]", "sklearn/linear_model/tests/test_logistic.py::test_penalty_none[lbfgs]", "sklearn/linear_model/tests/test_logistic.py::test_n_iter[sag]", "sklearn/linear_model/tests/test_logistic.py::test_elastic_net_vs_l1_l2[1]", "sklearn/linear_model/tests/test_logistic.py::test_LogisticRegression_elastic_net_objective[0.5-2.1544346900318843]", "sklearn/linear_model/tests/test_logistic.py::test_elastic_net_l1_l2_equivalence[l2-0-1000000.0]", "sklearn/linear_model/tests/test_logistic.py::test_l1_ratios_param[None]", "sklearn/linear_model/tests/test_logistic.py::test_max_iter[liblinear-Liblinear failed to converge, increase the number of iterations.-ovr-max_iter0]", "sklearn/linear_model/tests/test_logistic.py::test_LogisticRegressionCV_no_refit[auto-l2]", "sklearn/linear_model/tests/test_logistic.py::test_warm_start[multinomial-True-False-newton-cg]", "sklearn/linear_model/tests/test_logistic.py::test_max_iter[sag-The max_iter was reached which means the coef_ did not converge-multinomial-max_iter2]", "sklearn/linear_model/tests/test_logistic.py::test_elastic_net_l1_l2_equivalence[l1-1-100]", "sklearn/linear_model/tests/test_logistic.py::test_elastic_net_versus_sgd[0.5-0.001]", "sklearn/linear_model/tests/test_logistic.py::test_logistic_regression_multi_class_auto[lbfgs-LogisticRegression]", "sklearn/linear_model/tests/test_logistic.py::test_LogisticRegressionCV_no_refit[ovr-l2]", "sklearn/linear_model/tests/test_logistic.py::test_LogisticRegression_elastic_net_objective[0.9-2.1544346900318843]", "sklearn/linear_model/tests/test_logistic.py::test_warm_start[ovr-False-False-saga]", "sklearn/linear_model/tests/test_logistic.py::test_elastic_net_versus_sgd[0.9-0.046415888336127795]", "sklearn/linear_model/tests/test_logistic.py::test_warm_start[multinomial-False-False-lbfgs]", "sklearn/linear_model/tests/test_logistic.py::test_logistic_regression_solvers", "sklearn/linear_model/tests/test_logistic.py::test_logreg_intercept_scaling_zero", "sklearn/linear_model/tests/test_logistic.py::test_logistic_regressioncv_class_weights", "sklearn/linear_model/tests/test_logistic.py::test_logistic_regression_multinomial", "sklearn/linear_model/tests/test_logistic.py::test_LogisticRegressionCV_no_refit[auto-elasticnet]", "sklearn/linear_model/tests/test_logistic.py::test_warm_start[ovr-True-False-sag]", "sklearn/linear_model/tests/test_logistic.py::test_warm_start[multinomial-True-False-saga]", "sklearn/linear_model/tests/test_logistic.py::test_max_iter[sag-The max_iter was reached which means the coef_ did not converge-ovr-max_iter0]", "sklearn/linear_model/tests/test_logistic.py::test_elastic_net_l1_l2_equivalence[l1-1-0.001]", "sklearn/linear_model/tests/test_logistic.py::test_LogisticRegressionCV_GridSearchCV_elastic_net[multinomial]", "sklearn/linear_model/tests/test_logistic.py::test_warm_start_converge_LR", "sklearn/linear_model/tests/test_logistic.py::test_multinomial_binary[sag]", "sklearn/linear_model/tests/test_logistic.py::test_warm_start[ovr-True-True-newton-cg]", "sklearn/linear_model/tests/test_logistic.py::test_max_iter[lbfgs-lbfgs failed to converge-ovr-max_iter1]", "sklearn/linear_model/tests/test_logistic.py::test_max_iter[newton-cg-newton-cg failed to converge. Increase the number of iterations.-ovr-max_iter2]", "sklearn/linear_model/tests/test_logistic.py::test_dtype_match[True-newton-cg-ovr]", "sklearn/linear_model/tests/test_logistic.py::test_elastic_net_l1_l2_equivalence[l1-1-1000]", "sklearn/linear_model/tests/test_logistic.py::test_multinomial_binary[newton-cg]", "sklearn/linear_model/tests/test_logistic.py::test_max_iter[sag-The max_iter was reached which means the coef_ did not converge-multinomial-max_iter3]", "sklearn/linear_model/tests/test_logistic.py::test_dtype_match[False-newton-cg-ovr]", "sklearn/linear_model/tests/test_logistic.py::test_elastic_net_coeffs", "sklearn/linear_model/tests/test_logistic.py::test_elastic_net_l1_l2_equivalence[l2-0-0.001]", "sklearn/linear_model/tests/test_logistic.py::test_warm_start[multinomial-True-False-lbfgs]", "sklearn/linear_model/tests/test_logistic.py::test_logistic_cv", "sklearn/linear_model/tests/test_logistic.py::test_warm_start[multinomial-True-True-sag]", "sklearn/linear_model/tests/test_logistic.py::test_multinomial_identifiability_on_iris[True]", "sklearn/linear_model/tests/test_logistic.py::test_LogisticRegression_elastic_net_objective[0.5-0.001]", "sklearn/linear_model/tests/test_logistic.py::test_warm_start[ovr-False-True-lbfgs]", "sklearn/linear_model/tests/test_logistic.py::test_logistic_regression_multi_class_auto[saga-LogisticRegression]", "sklearn/linear_model/tests/test_logistic.py::test_warm_start[multinomial-False-True-sag]", "sklearn/linear_model/tests/test_logistic.py::test_LogisticRegression_elastic_net_objective[0.5-0.046415888336127795]", "sklearn/linear_model/tests/test_logistic.py::test_max_iter[saga-The max_iter was reached which means the coef_ did not converge-multinomial-max_iter0]", "sklearn/linear_model/tests/test_logistic.py::test_LogisticRegression_elastic_net_objective[0.5-100.0]", "sklearn/linear_model/tests/test_logistic.py::test_max_iter[saga-The max_iter was reached which means the coef_ did not converge-ovr-max_iter3]", "sklearn/linear_model/tests/test_logistic.py::test_elastic_net_l1_l2_equivalence[l2-0-0.1]", "sklearn/linear_model/tests/test_logistic.py::test_warm_start[multinomial-True-True-lbfgs]", "sklearn/linear_model/tests/test_logistic.py::test_logistic_cv_sparse", "sklearn/linear_model/tests/test_logistic.py::test_logistic_regression_path_convergence_fail", "sklearn/linear_model/tests/test_logistic.py::test_dtype_match[False-saga-multinomial]", "sklearn/linear_model/tests/test_logistic.py::test_elastic_net_l1_l2_equivalence[l2-0-1000]", "sklearn/linear_model/tests/test_logistic.py::test_logreg_predict_proba_multinomial", "sklearn/linear_model/tests/test_logistic.py::test_logisticregression_liblinear_sample_weight[params0]", "sklearn/linear_model/tests/test_logistic.py::test_elastic_net_versus_sgd[0.9-0.001]", "sklearn/linear_model/tests/test_logistic.py::test_elastic_net_vs_l1_l2[100]", "sklearn/linear_model/tests/test_logistic.py::test_logistic_cv_multinomial_score[accuracy-multiclass_agg_list0]", "sklearn/linear_model/tests/test_logistic.py::test_max_iter[newton-cg-newton-cg failed to converge. Increase the number of iterations.-multinomial-max_iter0]", "sklearn/linear_model/tests/test_logistic.py::test_max_iter[newton-cg-newton-cg failed to converge. Increase the number of iterations.-ovr-max_iter3]", "sklearn/linear_model/tests/test_logistic.py::test_elastic_net_l1_l2_equivalence[l1-1-1]", "sklearn/linear_model/tests/test_logistic.py::test_l1_ratio_param[something_wrong]", "sklearn/linear_model/tests/test_logistic.py::test_l1_ratio_param[None]", "sklearn/linear_model/tests/test_logistic.py::test_large_sparse_matrix[saga]", "sklearn/linear_model/tests/test_logistic.py::test_sample_weight_not_modified[balanced-multinomial]", "sklearn/linear_model/tests/test_logistic.py::test_logisticregression_liblinear_sample_weight[params1]", "sklearn/linear_model/tests/test_logistic.py::test_large_sparse_matrix[sag]", "sklearn/linear_model/tests/test_logistic.py::test_dtype_match[True-saga-multinomial]", "sklearn/linear_model/tests/test_logistic.py::test_sparsify", "sklearn/linear_model/tests/test_logistic.py::test_saga_vs_liblinear", "sklearn/linear_model/tests/test_logistic.py::test_LogisticRegression_elastic_net_objective[0.1-100.0]" ]
[ "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_are_the_same[1-None-False-HalfMultinomialLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_gradients_hessians_numerically[1-range-False-HalfMultinomialLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_hessp_intercept[True-0-range-HalfMultinomialLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_hessp_intercept[True-1-None-HalfPoissonLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_are_the_same[1-None-False-HalfBinomialLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_gradients_hessians_numerically[1-None-False-HalfBinomialLoss]", "sklearn/linear_model/tests/test_sag.py::test_sag_regressor_computed_correctly", "sklearn/linear_model/tests/test_linear_loss.py::test_gradients_hessians_numerically[0-range-False-HalfPoissonLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_hessp_intercept[True-0-None-HalfPoissonLoss]", "sklearn/linear_model/tests/test_sag.py::test_sag_pobj_matches_logistic_regression", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_hessp_intercept[True-0-None-HalfBinomialLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_gradients_hessians_numerically[0-None-False-HalfPoissonLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_gradients_hessians_numerically[1-range-False-HalfBinomialLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_are_the_same[0-None-True-HalfMultinomialLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_gradients_hessians_numerically[0-None-True-HalfPoissonLoss]", "sklearn/linear_model/tests/test_sag.py::test_binary_classifier_class_weight", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_hessp_intercept[False-1-range-HalfBinomialLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_are_the_same[0-None-False-HalfBinomialLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_hessp_intercept[False-1-range-HalfMultinomialLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_are_the_same[1-None-True-HalfPoissonLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_hessp_intercept[False-1-None-HalfMultinomialLoss]", "sklearn/linear_model/tests/test_sag.py::test_classifier_single_class", "sklearn/linear_model/tests/test_sag.py::test_multinomial_loss", "sklearn/linear_model/tests/test_linear_loss.py::test_gradients_hessians_numerically[0-range-True-HalfMultinomialLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_hessp_intercept[True-1-None-HalfMultinomialLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_hessp_intercept[False-1-None-HalfBinomialLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_gradients_hessians_numerically[1-range-True-HalfPoissonLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_hessp_intercept[False-0-range-HalfBinomialLoss]", "sklearn/linear_model/tests/test_sag.py::test_sag_classifier_raises_error[saga]", "sklearn/linear_model/tests/test_sag.py::test_multinomial_loss_ground_truth", "sklearn/linear_model/tests/test_linear_loss.py::test_gradients_hessians_numerically[1-None-False-HalfMultinomialLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_are_the_same[0-None-True-HalfPoissonLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_gradients_hessians_numerically[1-range-True-HalfMultinomialLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_gradients_hessians_numerically[1-range-False-HalfPoissonLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_are_the_same[0-range-True-HalfBinomialLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_are_the_same[1-range-False-HalfMultinomialLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_hessp_intercept[False-0-range-HalfMultinomialLoss]", "sklearn/linear_model/tests/test_sag.py::test_sag_classifier_computed_correctly", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_hessp_intercept[False-1-range-HalfPoissonLoss]", "sklearn/linear_model/tests/test_sag.py::test_sag_classifier_raises_error[sag]", "sklearn/linear_model/tests/test_linear_loss.py::test_gradients_hessians_numerically[1-None-True-HalfPoissonLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_hessp_intercept[True-1-range-HalfMultinomialLoss]", "sklearn/linear_model/tests/test_sag.py::test_sag_regressor[0]", "sklearn/linear_model/tests/test_linear_loss.py::test_gradients_hessians_numerically[0-range-True-HalfPoissonLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_multinomial_coef_shape[False]", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_are_the_same[0-range-True-HalfMultinomialLoss]", "sklearn/linear_model/tests/test_sag.py::test_get_auto_step_size", "sklearn/linear_model/tests/test_sag.py::test_classifier_matching", "sklearn/linear_model/tests/test_sag.py::test_sag_regressor[2]", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_hessp_intercept[True-1-None-HalfBinomialLoss]", "sklearn/linear_model/tests/test_sag.py::test_sag_regressor[1]", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_hessp_intercept[True-1-range-HalfPoissonLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_gradients_hessians_numerically[0-range-False-HalfBinomialLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_are_the_same[0-range-False-HalfPoissonLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_are_the_same[0-None-False-HalfPoissonLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_gradients_hessians_numerically[1-None-True-HalfMultinomialLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_hessp_intercept[False-0-None-HalfPoissonLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_gradients_hessians_numerically[1-None-False-HalfPoissonLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_gradients_hessians_numerically[0-None-False-HalfBinomialLoss]", "sklearn/linear_model/tests/test_sag.py::test_step_size_alpha_error", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_are_the_same[0-range-False-HalfMultinomialLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_are_the_same[1-range-False-HalfBinomialLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_are_the_same[1-None-True-HalfBinomialLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_gradients_hessians_numerically[0-range-False-HalfMultinomialLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_are_the_same[1-range-False-HalfPoissonLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_multinomial_coef_shape[True]", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_are_the_same[1-None-True-HalfMultinomialLoss]", "sklearn/linear_model/tests/test_sag.py::test_sag_multiclass_computed_correctly", "sklearn/linear_model/tests/test_linear_loss.py::test_gradients_hessians_numerically[0-None-True-HalfBinomialLoss]", "sklearn/linear_model/tests/test_sag.py::test_multiclass_classifier_class_weight", "sklearn/linear_model/tests/test_linear_loss.py::test_gradients_hessians_numerically[0-range-True-HalfBinomialLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_are_the_same[0-range-False-HalfBinomialLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_are_the_same[1-None-False-HalfPoissonLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_hessp_intercept[False-0-None-HalfBinomialLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_hessp_intercept[True-0-None-HalfMultinomialLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_are_the_same[1-range-True-HalfPoissonLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_hessp_intercept[False-0-None-HalfMultinomialLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_are_the_same[1-range-True-HalfMultinomialLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_are_the_same[0-range-True-HalfPoissonLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_hessp_intercept[False-0-range-HalfPoissonLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_gradients_hessians_numerically[1-None-True-HalfBinomialLoss]", "sklearn/linear_model/tests/test_sag.py::test_sag_pobj_matches_ridge_regression", "sklearn/linear_model/tests/test_linear_loss.py::test_gradients_hessians_numerically[0-None-True-HalfMultinomialLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_are_the_same[1-range-True-HalfBinomialLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_hessp_intercept[False-1-None-HalfPoissonLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_are_the_same[0-None-False-HalfMultinomialLoss]", "sklearn/linear_model/tests/test_sag.py::test_classifier_results", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_are_the_same[0-None-True-HalfBinomialLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_gradients_hessians_numerically[0-None-False-HalfMultinomialLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_hessp_intercept[True-0-range-HalfBinomialLoss]", "sklearn/linear_model/tests/test_sag.py::test_regressor_matching", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_hessp_intercept[True-1-range-HalfBinomialLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_gradients_hessians_numerically[1-range-True-HalfBinomialLoss]", "sklearn/linear_model/tests/test_linear_loss.py::test_loss_gradients_hessp_intercept[True-0-range-HalfPoissonLoss]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [ { "type": "file", "name": "sklearn/linear_model/_linear_loss.py" } ] }
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 39f8e405ebf7c..b88e54b46a4bf 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -393,6 +393,15 @@ Changelog\n beginning which speeds up fitting.\n :pr:`<PRID>` by :user:`<NAME>`.\n \n+- |Enhancement| :class:`~linear_model.LogisticRegression` is faster for\n+ ``solvers=\"lbfgs\"`` and ``solver=\"newton-cg\"``, for binary and in particular for\n+ multiclass problems thanks to the new private loss function module. In the multiclass\n+ case, the memory consumption has also been reduced for these solvers as the target is\n+ now label encoded (mapped to integers) instead of label binarized (one-hot encoded).\n+ The more classes, the larger the benefit.\n+ :pr:`<PRID>`, :pr:`<PRID>` and :pr:`<PRID>` by\n+ :user:`<NAME>`.\n+\n - |Enhancement| Rename parameter `base_estimator` to `estimator` in\n :class:`linear_model.RANSACRegressor` to improve readability and consistency.\n `base_estimator` is deprecated and will be removed in 1.3.\n" } ]
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 39f8e405ebf7c..b88e54b46a4bf 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -393,6 +393,15 @@ Changelog beginning which speeds up fitting. :pr:`<PRID>` by :user:`<NAME>`. +- |Enhancement| :class:`~linear_model.LogisticRegression` is faster for + ``solvers="lbfgs"`` and ``solver="newton-cg"``, for binary and in particular for + multiclass problems thanks to the new private loss function module. In the multiclass + case, the memory consumption has also been reduced for these solvers as the target is + now label encoded (mapped to integers) instead of label binarized (one-hot encoded). + The more classes, the larger the benefit. + :pr:`<PRID>`, :pr:`<PRID>` and :pr:`<PRID>` by + :user:`<NAME>`. + - |Enhancement| Rename parameter `base_estimator` to `estimator` in :class:`linear_model.RANSACRegressor` to improve readability and consistency. `base_estimator` is deprecated and will be removed in 1.3. If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names: [{'type': 'file', 'name': 'sklearn/linear_model/_linear_loss.py'}]
scikit-learn/scikit-learn
scikit-learn__scikit-learn-22062
https://github.com/scikit-learn/scikit-learn/pull/22062
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index fa634e3e600fd..0674f1493b34b 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -303,6 +303,17 @@ Changelog for the highs based solvers. :pr:`21086` by :user:`Venkatachalam Natchiappan <venkyyuvy>`. +- |Enhancement| Rename parameter `base_estimator` to `estimator` in + :class:`linear_model.RANSACRegressor` to improve readability and consistency. + `base_estimator` is deprecated and will be removed in 1.3. + :pr:`22062` by :user:`Adrian Trujillo <trujillo9616>`. + +- |Fix| :class:`linear_model.LassoLarsIC` now correctly computes AIC + and BIC. An error is now raised when `n_features > n_samples` and + when the noise variance is not provided. + :pr:`21481` by :user:`Guillaume Lemaitre <glemaitre>` and + :user:`Andrés Babino <ababino>`. + :mod:`sklearn.metrics` ...................... diff --git a/sklearn/linear_model/_ransac.py b/sklearn/linear_model/_ransac.py index c565c8c6ce403..7702e361d51d0 100644 --- a/sklearn/linear_model/_ransac.py +++ b/sklearn/linear_model/_ransac.py @@ -65,7 +65,7 @@ class RANSACRegressor( Parameters ---------- - base_estimator : object, default=None + estimator : object, default=None Base estimator object which implements the following methods: * `fit(X, y)`: Fit model to given training data and target values. @@ -76,7 +76,7 @@ class RANSACRegressor( * `predict(X)`: Returns predicted values using the linear model, which is used to compute residual error using loss function. - If `base_estimator` is None, then + If `estimator` is None, then :class:`~sklearn.linear_model.LinearRegression` is used for target values of dtype float. @@ -88,10 +88,10 @@ class RANSACRegressor( as an absolute number of samples for `min_samples >= 1`, treated as a relative number `ceil(min_samples * X.shape[0])` for `min_samples < 1`. This is typically chosen as the minimal number of - samples necessary to estimate the given `base_estimator`. By default a + samples necessary to estimate the given `estimator`. By default a ``sklearn.linear_model.LinearRegression()`` estimator is assumed and `min_samples` is chosen as ``X.shape[1] + 1``. This parameter is highly - dependent upon the model, so if a `base_estimator` other than + dependent upon the model, so if a `estimator` other than :class:`linear_model.LinearRegression` is used, the user is encouraged to provide a value. @@ -174,10 +174,17 @@ class RANSACRegressor( Pass an int for reproducible output across multiple function calls. See :term:`Glossary <random_state>`. + base_estimator : object, default="deprecated" + Use `estimator` instead. + + .. deprecated:: 1.1 + `base_estimator` is deprecated and will be removed in 1.3. + Use `estimator` instead. + Attributes ---------- estimator_ : object - Best fitted model (copy of the `base_estimator` object). + Best fitted model (copy of the `estimator` object). n_trials_ : int Number of random selection trials until one of the stop criteria is @@ -241,7 +248,7 @@ class RANSACRegressor( def __init__( self, - base_estimator=None, + estimator=None, *, min_samples=None, residual_threshold=None, @@ -254,9 +261,10 @@ def __init__( stop_probability=0.99, loss="absolute_error", random_state=None, + base_estimator="deprecated", ): - self.base_estimator = base_estimator + self.estimator = estimator self.min_samples = min_samples self.residual_threshold = residual_threshold self.is_data_valid = is_data_valid @@ -268,6 +276,7 @@ def __init__( self.stop_probability = stop_probability self.random_state = random_state self.loss = loss + self.base_estimator = base_estimator def fit(self, X, y, sample_weight=None): """Fit estimator using RANSAC algorithm. @@ -282,7 +291,7 @@ def fit(self, X, y, sample_weight=None): sample_weight : array-like of shape (n_samples,), default=None Individual weights for each sample - raises error if sample_weight is passed and base_estimator + raises error if sample_weight is passed and estimator fit method does not support it. .. versionadded:: 0.18 @@ -301,7 +310,7 @@ def fit(self, X, y, sample_weight=None): """ # Need to validate separately here. We can't pass multi_ouput=True # because that would allow y to be csr. Delay expensive finiteness - # check to the base estimator's own input validation. + # check to the estimator's own input validation. check_X_params = dict(accept_sparse="csr", force_all_finite=False) check_y_params = dict(ensure_2d=False) X, y = self._validate_data( @@ -309,13 +318,21 @@ def fit(self, X, y, sample_weight=None): ) check_consistent_length(X, y) - if self.base_estimator is not None: - base_estimator = clone(self.base_estimator) + if self.base_estimator != "deprecated": + warnings.warn( + "`base_estimator` was renamed to `estimator` in version 1.1 and " + "will be removed in 1.3.", + FutureWarning, + ) + self.estimator = self.base_estimator + + if self.estimator is not None: + estimator = clone(self.estimator) else: - base_estimator = LinearRegression() + estimator = LinearRegression() if self.min_samples is None: - if not isinstance(base_estimator, LinearRegression): + if not isinstance(estimator, LinearRegression): # FIXME: in 1.2, turn this warning into an error warnings.warn( "From version 1.2, `min_samples` needs to be explicitly " @@ -392,14 +409,12 @@ def fit(self, X, y, sample_weight=None): random_state = check_random_state(self.random_state) try: # Not all estimator accept a random_state - base_estimator.set_params(random_state=random_state) + estimator.set_params(random_state=random_state) except ValueError: pass - estimator_fit_has_sample_weight = has_fit_parameter( - base_estimator, "sample_weight" - ) - estimator_name = type(base_estimator).__name__ + estimator_fit_has_sample_weight = has_fit_parameter(estimator, "sample_weight") + estimator_name = type(estimator).__name__ if sample_weight is not None and not estimator_fit_has_sample_weight: raise ValueError( "%s does not support sample_weight. Samples" @@ -451,21 +466,21 @@ def fit(self, X, y, sample_weight=None): # fit model for current random sample set if sample_weight is None: - base_estimator.fit(X_subset, y_subset) + estimator.fit(X_subset, y_subset) else: - base_estimator.fit( + estimator.fit( X_subset, y_subset, sample_weight=sample_weight[subset_idxs] ) # check if estimated model is valid if self.is_model_valid is not None and not self.is_model_valid( - base_estimator, X_subset, y_subset + estimator, X_subset, y_subset ): self.n_skips_invalid_model_ += 1 continue # residuals of all data for current random sample model - y_pred = base_estimator.predict(X) + y_pred = estimator.predict(X) residuals_subset = loss_function(y, y_pred) # classify data into inliers and outliers @@ -483,7 +498,7 @@ def fit(self, X, y, sample_weight=None): y_inlier_subset = y[inlier_idxs_subset] # score of inlier data set - score_subset = base_estimator.score(X_inlier_subset, y_inlier_subset) + score_subset = estimator.score(X_inlier_subset, y_inlier_subset) # same number of inliers but worse score -> skip current random # sample @@ -546,15 +561,15 @@ def fit(self, X, y, sample_weight=None): # estimate final model using all inliers if sample_weight is None: - base_estimator.fit(X_inlier_best, y_inlier_best) + estimator.fit(X_inlier_best, y_inlier_best) else: - base_estimator.fit( + estimator.fit( X_inlier_best, y_inlier_best, sample_weight=sample_weight[inlier_best_idxs_subset], ) - self.estimator_ = base_estimator + self.estimator_ = estimator self.inlier_mask_ = inlier_mask_best return self
diff --git a/sklearn/linear_model/tests/test_ransac.py b/sklearn/linear_model/tests/test_ransac.py index f26d2088263b8..53f6b2d1f75eb 100644 --- a/sklearn/linear_model/tests/test_ransac.py +++ b/sklearn/linear_model/tests/test_ransac.py @@ -30,9 +30,9 @@ def test_ransac_inliers_outliers(): - base_estimator = LinearRegression() + estimator = LinearRegression() ransac_estimator = RANSACRegressor( - base_estimator, min_samples=2, residual_threshold=5, random_state=0 + estimator, min_samples=2, residual_threshold=5, random_state=0 ) # Estimate parameters of corrupted data @@ -55,9 +55,9 @@ def is_data_valid(X, y): X = rng.rand(10, 2) y = rng.rand(10, 1) - base_estimator = LinearRegression() + estimator = LinearRegression() ransac_estimator = RANSACRegressor( - base_estimator, + estimator, min_samples=2, residual_threshold=5, is_data_valid=is_data_valid, @@ -73,9 +73,9 @@ def is_model_valid(estimator, X, y): assert y.shape[0] == 2 return False - base_estimator = LinearRegression() + estimator = LinearRegression() ransac_estimator = RANSACRegressor( - base_estimator, + estimator, min_samples=2, residual_threshold=5, is_model_valid=is_model_valid, @@ -86,10 +86,10 @@ def is_model_valid(estimator, X, y): def test_ransac_max_trials(): - base_estimator = LinearRegression() + estimator = LinearRegression() ransac_estimator = RANSACRegressor( - base_estimator, + estimator, min_samples=2, residual_threshold=5, max_trials=0, @@ -102,7 +102,7 @@ def test_ransac_max_trials(): # 1e-2 isn't enough, can still happen # 2 is the what ransac defines as min_samples = X.shape[1] + 1 max_trials = _dynamic_max_trials(len(X) - len(outliers), X.shape[0], 2, 1 - 1e-9) - ransac_estimator = RANSACRegressor(base_estimator, min_samples=2) + ransac_estimator = RANSACRegressor(estimator, min_samples=2) for i in range(50): ransac_estimator.set_params(min_samples=2, random_state=i) ransac_estimator.fit(X, y) @@ -110,9 +110,9 @@ def test_ransac_max_trials(): def test_ransac_stop_n_inliers(): - base_estimator = LinearRegression() + estimator = LinearRegression() ransac_estimator = RANSACRegressor( - base_estimator, + estimator, min_samples=2, residual_threshold=5, stop_n_inliers=2, @@ -124,9 +124,9 @@ def test_ransac_stop_n_inliers(): def test_ransac_stop_score(): - base_estimator = LinearRegression() + estimator = LinearRegression() ransac_estimator = RANSACRegressor( - base_estimator, + estimator, min_samples=2, residual_threshold=5, stop_score=0, @@ -143,9 +143,9 @@ def test_ransac_score(): y[0] = 1 y[1] = 100 - base_estimator = LinearRegression() + estimator = LinearRegression() ransac_estimator = RANSACRegressor( - base_estimator, min_samples=2, residual_threshold=0.5, random_state=0 + estimator, min_samples=2, residual_threshold=0.5, random_state=0 ) ransac_estimator.fit(X, y) @@ -159,9 +159,9 @@ def test_ransac_predict(): y[0] = 1 y[1] = 100 - base_estimator = LinearRegression() + estimator = LinearRegression() ransac_estimator = RANSACRegressor( - base_estimator, min_samples=2, residual_threshold=0.5, random_state=0 + estimator, min_samples=2, residual_threshold=0.5, random_state=0 ) ransac_estimator.fit(X, y) @@ -171,9 +171,9 @@ def test_ransac_predict(): def test_ransac_residuals_threshold_no_inliers(): # When residual_threshold=nan there are no inliers and a # ValueError with a message should be raised - base_estimator = LinearRegression() + estimator = LinearRegression() ransac_estimator = RANSACRegressor( - base_estimator, + estimator, min_samples=2, residual_threshold=float("nan"), random_state=0, @@ -192,9 +192,9 @@ def test_ransac_no_valid_data(): def is_data_valid(X, y): return False - base_estimator = LinearRegression() + estimator = LinearRegression() ransac_estimator = RANSACRegressor( - base_estimator, is_data_valid=is_data_valid, max_trials=5 + estimator, is_data_valid=is_data_valid, max_trials=5 ) msg = "RANSAC could not find a valid consensus set" @@ -209,9 +209,9 @@ def test_ransac_no_valid_model(): def is_model_valid(estimator, X, y): return False - base_estimator = LinearRegression() + estimator = LinearRegression() ransac_estimator = RANSACRegressor( - base_estimator, is_model_valid=is_model_valid, max_trials=5 + estimator, is_model_valid=is_model_valid, max_trials=5 ) msg = "RANSAC could not find a valid consensus set" @@ -226,9 +226,9 @@ def test_ransac_exceed_max_skips(): def is_data_valid(X, y): return False - base_estimator = LinearRegression() + estimator = LinearRegression() ransac_estimator = RANSACRegressor( - base_estimator, is_data_valid=is_data_valid, max_trials=5, max_skips=3 + estimator, is_data_valid=is_data_valid, max_trials=5, max_skips=3 ) msg = "RANSAC skipped more iterations than `max_skips`" @@ -251,9 +251,9 @@ def is_data_valid(X, y): else: return False - base_estimator = LinearRegression() + estimator = LinearRegression() ransac_estimator = RANSACRegressor( - base_estimator, is_data_valid=is_data_valid, max_skips=3, max_trials=5 + estimator, is_data_valid=is_data_valid, max_skips=3, max_trials=5 ) warning_message = ( "RANSAC found a valid consensus set but exited " @@ -271,9 +271,9 @@ def is_data_valid(X, y): def test_ransac_sparse_coo(): X_sparse = sparse.coo_matrix(X) - base_estimator = LinearRegression() + estimator = LinearRegression() ransac_estimator = RANSACRegressor( - base_estimator, min_samples=2, residual_threshold=5, random_state=0 + estimator, min_samples=2, residual_threshold=5, random_state=0 ) ransac_estimator.fit(X_sparse, y) @@ -286,9 +286,9 @@ def test_ransac_sparse_coo(): def test_ransac_sparse_csr(): X_sparse = sparse.csr_matrix(X) - base_estimator = LinearRegression() + estimator = LinearRegression() ransac_estimator = RANSACRegressor( - base_estimator, min_samples=2, residual_threshold=5, random_state=0 + estimator, min_samples=2, residual_threshold=5, random_state=0 ) ransac_estimator.fit(X_sparse, y) @@ -301,9 +301,9 @@ def test_ransac_sparse_csr(): def test_ransac_sparse_csc(): X_sparse = sparse.csc_matrix(X) - base_estimator = LinearRegression() + estimator = LinearRegression() ransac_estimator = RANSACRegressor( - base_estimator, min_samples=2, residual_threshold=5, random_state=0 + estimator, min_samples=2, residual_threshold=5, random_state=0 ) ransac_estimator.fit(X_sparse, y) @@ -315,10 +315,10 @@ def test_ransac_sparse_csc(): def test_ransac_none_estimator(): - base_estimator = LinearRegression() + estimator = LinearRegression() ransac_estimator = RANSACRegressor( - base_estimator, min_samples=2, residual_threshold=5, random_state=0 + estimator, min_samples=2, residual_threshold=5, random_state=0 ) ransac_none_estimator = RANSACRegressor( None, min_samples=2, residual_threshold=5, random_state=0 @@ -333,30 +333,28 @@ def test_ransac_none_estimator(): def test_ransac_min_n_samples(): - base_estimator = LinearRegression() + estimator = LinearRegression() ransac_estimator1 = RANSACRegressor( - base_estimator, min_samples=2, residual_threshold=5, random_state=0 + estimator, min_samples=2, residual_threshold=5, random_state=0 ) ransac_estimator2 = RANSACRegressor( - base_estimator, + estimator, min_samples=2.0 / X.shape[0], residual_threshold=5, random_state=0, ) ransac_estimator3 = RANSACRegressor( - base_estimator, min_samples=-1, residual_threshold=5, random_state=0 + estimator, min_samples=-1, residual_threshold=5, random_state=0 ) ransac_estimator4 = RANSACRegressor( - base_estimator, min_samples=5.2, residual_threshold=5, random_state=0 + estimator, min_samples=5.2, residual_threshold=5, random_state=0 ) ransac_estimator5 = RANSACRegressor( - base_estimator, min_samples=2.0, residual_threshold=5, random_state=0 - ) - ransac_estimator6 = RANSACRegressor( - base_estimator, residual_threshold=5, random_state=0 + estimator, min_samples=2.0, residual_threshold=5, random_state=0 ) + ransac_estimator6 = RANSACRegressor(estimator, residual_threshold=5, random_state=0) ransac_estimator7 = RANSACRegressor( - base_estimator, min_samples=X.shape[0] + 1, residual_threshold=5, random_state=0 + estimator, min_samples=X.shape[0] + 1, residual_threshold=5, random_state=0 ) # GH #19390 ransac_estimator8 = RANSACRegressor( @@ -394,9 +392,9 @@ def test_ransac_min_n_samples(): def test_ransac_multi_dimensional_targets(): - base_estimator = LinearRegression() + estimator = LinearRegression() ransac_estimator = RANSACRegressor( - base_estimator, min_samples=2, residual_threshold=5, random_state=0 + estimator, min_samples=2, residual_threshold=5, random_state=0 ) # 3-D target values @@ -424,19 +422,19 @@ def loss_mono(y_true, y_pred): yyy = np.column_stack([y, y, y]) - base_estimator = LinearRegression() + estimator = LinearRegression() ransac_estimator0 = RANSACRegressor( - base_estimator, min_samples=2, residual_threshold=5, random_state=0 + estimator, min_samples=2, residual_threshold=5, random_state=0 ) ransac_estimator1 = RANSACRegressor( - base_estimator, + estimator, min_samples=2, residual_threshold=5, random_state=0, loss=loss_multi1, ) ransac_estimator2 = RANSACRegressor( - base_estimator, + estimator, min_samples=2, residual_threshold=5, random_state=0, @@ -462,7 +460,7 @@ def loss_mono(y_true, y_pred): ransac_estimator0.predict(X), ransac_estimator2.predict(X) ) ransac_estimator3 = RANSACRegressor( - base_estimator, + estimator, min_samples=2, residual_threshold=5, random_state=0, @@ -475,8 +473,8 @@ def loss_mono(y_true, y_pred): def test_ransac_default_residual_threshold(): - base_estimator = LinearRegression() - ransac_estimator = RANSACRegressor(base_estimator, min_samples=2, random_state=0) + estimator = LinearRegression() + ransac_estimator = RANSACRegressor(estimator, min_samples=2, random_state=0) # Estimate parameters of corrupted data ransac_estimator.fit(X, y) @@ -519,17 +517,13 @@ def test_ransac_dynamic_max_trials(): assert _dynamic_max_trials(1, 100, 10, 0) == 0 assert _dynamic_max_trials(1, 100, 10, 1) == float("inf") - base_estimator = LinearRegression() - ransac_estimator = RANSACRegressor( - base_estimator, min_samples=2, stop_probability=-0.1 - ) + estimator = LinearRegression() + ransac_estimator = RANSACRegressor(estimator, min_samples=2, stop_probability=-0.1) with pytest.raises(ValueError): ransac_estimator.fit(X, y) - ransac_estimator = RANSACRegressor( - base_estimator, min_samples=2, stop_probability=1.1 - ) + ransac_estimator = RANSACRegressor(estimator, min_samples=2, stop_probability=1.1) with pytest.raises(ValueError): ransac_estimator.fit(X, y) @@ -579,12 +573,12 @@ def test_ransac_fit_sample_weight(): assert_allclose(ransac_estimator.estimator_.coef_, ref_coef_) - # check that if base_estimator.fit doesn't support + # check that if estimator.fit doesn't support # sample_weight, raises error - base_estimator = OrthogonalMatchingPursuit() - ransac_estimator = RANSACRegressor(base_estimator, min_samples=10) + estimator = OrthogonalMatchingPursuit() + ransac_estimator = RANSACRegressor(estimator, min_samples=10) - err_msg = f"{base_estimator.__class__.__name__} does not support sample_weight." + err_msg = f"{estimator.__class__.__name__} does not support sample_weight." with pytest.raises(ValueError, match=err_msg): ransac_estimator.fit(X, y, weights) @@ -594,7 +588,7 @@ def test_ransac_final_model_fit_sample_weight(): rng = check_random_state(42) sample_weight = rng.randint(1, 4, size=y.shape[0]) sample_weight = sample_weight / sample_weight.sum() - ransac = RANSACRegressor(base_estimator=LinearRegression(), random_state=0) + ransac = RANSACRegressor(estimator=LinearRegression(), random_state=0) ransac.fit(X, y, sample_weight=sample_weight) final_model = LinearRegression() @@ -614,8 +608,8 @@ def test_perfect_horizontal_line(): X = np.arange(100)[:, None] y = np.zeros((100,)) - base_estimator = LinearRegression() - ransac_estimator = RANSACRegressor(base_estimator, random_state=0) + estimator = LinearRegression() + ransac_estimator = RANSACRegressor(estimator, random_state=0) ransac_estimator.fit(X, y) assert_allclose(ransac_estimator.estimator_.coef_, 0.0) @@ -639,3 +633,18 @@ def test_loss_deprecated(old_loss, new_loss): est2 = RANSACRegressor(loss=new_loss, random_state=0) est2.fit(X, y) assert_allclose(est1.predict(X), est2.predict(X)) + + +def test_base_estimator_deprecated(): + ransac_estimator = RANSACRegressor( + base_estimator=LinearRegression(), + min_samples=2, + residual_threshold=5, + random_state=0, + ) + err_msg = ( + "`base_estimator` was renamed to `estimator` in version 1.1 and " + "will be removed in 1.3." + ) + with pytest.warns(FutureWarning, match=err_msg): + ransac_estimator.fit(X, y)
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex fa634e3e600fd..0674f1493b34b 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -303,6 +303,17 @@ Changelog\n for the highs based solvers.\n :pr:`21086` by :user:`Venkatachalam Natchiappan <venkyyuvy>`.\n \n+- |Enhancement| Rename parameter `base_estimator` to `estimator` in\n+ :class:`linear_model.RANSACRegressor` to improve readability and consistency.\n+ `base_estimator` is deprecated and will be removed in 1.3.\n+ :pr:`22062` by :user:`Adrian Trujillo <trujillo9616>`.\n+\n+- |Fix| :class:`linear_model.LassoLarsIC` now correctly computes AIC\n+ and BIC. An error is now raised when `n_features > n_samples` and\n+ when the noise variance is not provided.\n+ :pr:`21481` by :user:`Guillaume Lemaitre <glemaitre>` and\n+ :user:`Andrés Babino <ababino>`.\n+\n :mod:`sklearn.metrics`\n ......................\n \n" } ]
1.01
e4015289e0eeb390190ce0d051cee756bc5ecb33
[ "sklearn/linear_model/tests/test_ransac.py::test_ransac_sparse_csc", "sklearn/linear_model/tests/test_ransac.py::test_ransac_is_model_valid", "sklearn/linear_model/tests/test_ransac.py::test_ransac_predict", "sklearn/linear_model/tests/test_ransac.py::test_ransac_sparse_csr", "sklearn/linear_model/tests/test_ransac.py::test_ransac_max_trials", "sklearn/linear_model/tests/test_ransac.py::test_ransac_dynamic_max_trials", "sklearn/linear_model/tests/test_ransac.py::test_ransac_exceed_max_skips", "sklearn/linear_model/tests/test_ransac.py::test_ransac_min_n_samples", "sklearn/linear_model/tests/test_ransac.py::test_ransac_multi_dimensional_targets", "sklearn/linear_model/tests/test_ransac.py::test_loss_deprecated[squared_loss-absolute_error]", "sklearn/linear_model/tests/test_ransac.py::test_ransac_is_data_valid", "sklearn/linear_model/tests/test_ransac.py::test_ransac_stop_score", "sklearn/linear_model/tests/test_ransac.py::test_ransac_inliers_outliers", "sklearn/linear_model/tests/test_ransac.py::test_ransac_score", "sklearn/linear_model/tests/test_ransac.py::test_ransac_warn_exceed_max_skips", "sklearn/linear_model/tests/test_ransac.py::test_ransac_no_valid_data", "sklearn/linear_model/tests/test_ransac.py::test_ransac_sparse_coo", "sklearn/linear_model/tests/test_ransac.py::test_loss_deprecated[absolute_loss-squared_error]", "sklearn/linear_model/tests/test_ransac.py::test_ransac_stop_n_inliers", "sklearn/linear_model/tests/test_ransac.py::test_ransac_residual_loss", "sklearn/linear_model/tests/test_ransac.py::test_ransac_residuals_threshold_no_inliers", "sklearn/linear_model/tests/test_ransac.py::test_ransac_default_residual_threshold", "sklearn/linear_model/tests/test_ransac.py::test_ransac_none_estimator", "sklearn/linear_model/tests/test_ransac.py::test_perfect_horizontal_line", "sklearn/linear_model/tests/test_ransac.py::test_ransac_fit_sample_weight", "sklearn/linear_model/tests/test_ransac.py::test_ransac_no_valid_model" ]
[ "sklearn/linear_model/tests/test_ransac.py::test_base_estimator_deprecated", "sklearn/linear_model/tests/test_ransac.py::test_ransac_final_model_fit_sample_weight" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex fa634e3e600fd..0674f1493b34b 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -303,6 +303,17 @@ Changelog\n for the highs based solvers.\n :pr:`<PRID>` by :user:`<NAME>`.\n \n+- |Enhancement| Rename parameter `base_estimator` to `estimator` in\n+ :class:`linear_model.RANSACRegressor` to improve readability and consistency.\n+ `base_estimator` is deprecated and will be removed in 1.3.\n+ :pr:`<PRID>` by :user:`<NAME>`.\n+\n+- |Fix| :class:`linear_model.LassoLarsIC` now correctly computes AIC\n+ and BIC. An error is now raised when `n_features > n_samples` and\n+ when the noise variance is not provided.\n+ :pr:`<PRID>` by :user:`<NAME>` and\n+ :user:`<NAME>`.\n+\n :mod:`sklearn.metrics`\n ......................\n \n" } ]
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index fa634e3e600fd..0674f1493b34b 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -303,6 +303,17 @@ Changelog for the highs based solvers. :pr:`<PRID>` by :user:`<NAME>`. +- |Enhancement| Rename parameter `base_estimator` to `estimator` in + :class:`linear_model.RANSACRegressor` to improve readability and consistency. + `base_estimator` is deprecated and will be removed in 1.3. + :pr:`<PRID>` by :user:`<NAME>`. + +- |Fix| :class:`linear_model.LassoLarsIC` now correctly computes AIC + and BIC. An error is now raised when `n_features > n_samples` and + when the noise variance is not provided. + :pr:`<PRID>` by :user:`<NAME>` and + :user:`<NAME>`. + :mod:`sklearn.metrics` ......................
scikit-learn/scikit-learn
scikit-learn__scikit-learn-22148
https://github.com/scikit-learn/scikit-learn/pull/22148
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index eef1135855560..75cd2414647c4 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -337,6 +337,11 @@ Changelog :pr:`21481` by :user:`Guillaume Lemaitre <glemaitre>` and :user:`Andrés Babino <ababino>`. +- |Enhancement| :func:`linear_model.ElasticNet` and + and other linear model classes using coordinate descent show error + messages when non-finite parameter weights are produced. :pr:`22148` + by :user:`Christian Ritter <chritter>` and :user:`Norbert Preining <norbusan>`. + - |Fix| :class:`linear_model.ElasticNetCV` now produces correct warning when `l1_ratio=0`. :pr:`21724` by :user:`Yar Khine Phyo <yarkhinephyo>`. diff --git a/sklearn/linear_model/_coordinate_descent.py b/sklearn/linear_model/_coordinate_descent.py index 7e4906962bffc..8785aa913fec2 100644 --- a/sklearn/linear_model/_coordinate_descent.py +++ b/sklearn/linear_model/_coordinate_descent.py @@ -1075,6 +1075,14 @@ def fit(self, X, y, sample_weight=None, check_input=True): # workaround since _set_intercept will cast self.coef_ into X.dtype self.coef_ = np.asarray(self.coef_, dtype=X.dtype) + # check for finiteness of coefficients + if not all(np.isfinite(w).all() for w in [self.coef_, self.intercept_]): + raise ValueError( + "Coordinate descent iterations resulted in non-finite parameter" + " values. The input data may contain large values and need to" + " be preprocessed." + ) + # return self for chaining fit and predict calls return self
diff --git a/sklearn/linear_model/tests/test_coordinate_descent.py b/sklearn/linear_model/tests/test_coordinate_descent.py index c5ff1156875d4..2e65fb1fa23bb 100644 --- a/sklearn/linear_model/tests/test_coordinate_descent.py +++ b/sklearn/linear_model/tests/test_coordinate_descent.py @@ -167,6 +167,21 @@ def test_lasso_zero(): assert_almost_equal(clf.dual_gap_, 0) +def test_enet_nonfinite_params(): + # Check ElasticNet throws ValueError when dealing with non-finite parameter + # values + rng = np.random.RandomState(0) + n_samples = 10 + fmax = np.finfo(np.float64).max + X = fmax * rng.uniform(size=(n_samples, 2)) + y = rng.randint(0, 2, size=n_samples) + + clf = ElasticNet(alpha=0.1) + msg = "Coordinate descent iterations resulted in non-finite parameter values" + with pytest.raises(ValueError, match=msg): + clf.fit(X, y) + + def test_lasso_toy(): # Test Lasso on a toy example for various values of alpha. # When validating this against glmnet notice that glmnet divides it
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex eef1135855560..75cd2414647c4 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -337,6 +337,11 @@ Changelog\n :pr:`21481` by :user:`Guillaume Lemaitre <glemaitre>` and\n :user:`Andrés Babino <ababino>`.\n \n+- |Enhancement| :func:`linear_model.ElasticNet` and \n+ and other linear model classes using coordinate descent show error\n+ messages when non-finite parameter weights are produced. :pr:`22148`\n+ by :user:`Christian Ritter <chritter>` and :user:`Norbert Preining <norbusan>`.\n+\n - |Fix| :class:`linear_model.ElasticNetCV` now produces correct\n warning when `l1_ratio=0`.\n :pr:`21724` by :user:`Yar Khine Phyo <yarkhinephyo>`.\n" } ]
1.01
1d1aadd0711b87d2a11c80aad15df6f8cf156712
[ "sklearn/linear_model/tests/test_coordinate_descent.py::test_warm_start", "sklearn/linear_model/tests/test_coordinate_descent.py::test_path_unknown_parameter[enet_path]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[Lars-params12]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_toy", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_correctness[True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_ridge_consistency[True-1.0]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_ridge_consistency[False-1.0]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[False-0.5-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_warm_start_convergence_with_regularizer_decrement", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-True-RidgeClassifier-params1]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[ARDRegression-params7]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lassoCV_does_not_set_precompute[False-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[False-1-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_warm_start_convergence", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lassoCV_does_not_set_precompute[auto-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_sparse[ElasticNet]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[OrthogonalMatchingPursuit-params8]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[MultiTaskLasso-params11]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_set_order_dense[C-F]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_precompute_invalid_argument", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[True-1-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_l1_ratio", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_multitarget", "sklearn/linear_model/tests/test_coordinate_descent.py::test_warm_start_multitask_lasso", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[Ridge-params6]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_consistency[True-False-0.01-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[BayesianRidge-params6]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_elasticnet_precompute_gram_weighted_samples", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[False-0-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-False-RidgeCV-params6]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_sparse_dense_descent_paths", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[True-0-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[ElasticNet-params3]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_consistency[True-False-0.01-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[MultiTaskElasticNet-params9]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_models_cv_fit_with_loky[LassoCV]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_positive_constraint", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_coordinate_descent[Lasso-1-kwargs0]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_cv_with_some_model_selection", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_copy_X_True[False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_sparse[Lasso]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_ridge_consistency[True-1000000.0]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-True-RidgeClassifierCV-params7]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_coordinate_descent[MultiTaskLasso-2-kwargs3]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[ElasticNetCV-params2]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_path_parameters", "sklearn/linear_model/tests/test_coordinate_descent.py::test_sparse_input_dtype_enet_and_lassocv", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[RidgeClassifier-params2]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_consistency[False-True-0.01-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_random_descent", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_ridge_consistency[False-0.1]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_consistency[True-True-0.01-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_set_order_sparse[C-C]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-True-ElasticNet-params2]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[True-False-LinearRegression-params5]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[LassoCV-params1]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_sparse[ElasticNetCV]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_models_cv_fit_with_loky[ElasticNetCV]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-True-Lasso-params0]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[True-0.5-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_consistency[False-False-0.01-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_elasticnet_precompute_incorrect_gram", "sklearn/linear_model/tests/test_coordinate_descent.py::test_multi_task_lasso_and_enet", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_path_positive", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_cv_positive_constraint", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_path", "sklearn/linear_model/tests/test_coordinate_descent.py::test_multi_task_lasso_readonly_data", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[MultiTaskElasticNet-params10]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_non_float_y[Lasso]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_does_not_overwrite_sample_weight[False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[Ridge-params5]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_dual_gap", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[ElasticNet-params4]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[True-False-RidgeClassifier-params1]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_does_not_overwrite_sample_weight[True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lassoCV_does_not_set_precompute[True-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_coef_shape_not_zero", "sklearn/linear_model/tests/test_coordinate_descent.py::test_check_input_false", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_readonly_data", "sklearn/linear_model/tests/test_coordinate_descent.py::test_1d_multioutput_lasso_and_multitask_lasso_cv", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[True-False-RidgeCV-params6]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[LinearRegression-params7]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[True-0-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_consistency[True-True-0.01-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_path_return_models_vs_new_return_gives_same_coefficients", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[True-1-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_sample_weight_invariance[estimator1]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_multitask_enet_and_lasso_cv", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[False-1-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_l1_ratio_param_invalid[-1]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_positive_constraint", "sklearn/linear_model/tests/test_coordinate_descent.py::test_set_order_sparse[F-C]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_positive_constraint", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_correctness[False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-False-Lasso-params0]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-False-LinearRegression-params5]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_non_float_y[ElasticNet]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-True-RidgeCV-params6]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_ridge_consistency[False-1000000.0]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_set_order_dense[F-C]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[False-0.5-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_set_order_sparse[C-F]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-False-ElasticNet-params3]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_set_order_dense[F-F]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_grid_search[True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_consistency[False-True-0.01-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[ElasticNet-params4]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[LassoLarsIC-params14]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[Lasso-params0]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[RidgeClassifierCV-params9]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[True-0.5-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-False-ElasticNet-params2]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-True-ElasticNet-params3]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_coordinate_descent[MultiTaskLasso-2-kwargs2]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_consistency[False-False-0.01-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_float_precision", "sklearn/linear_model/tests/test_coordinate_descent.py::test_set_order_dense[C-C]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_l1_ratio_param_invalid[something_wrong]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[RidgeClassifierCV-params16]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[LinearRegression-params13]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_path_unknown_parameter[lasso_path]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_zero", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_sparse[LassoCV]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_l1_ratio_param_invalid[10]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_cv", "sklearn/linear_model/tests/test_coordinate_descent.py::test_multi_task_lasso_cv_dtype", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_copy_X_False_check_input_False", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-False-Ridge-params4]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[RidgeCV-params15]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_uniform_targets", "sklearn/linear_model/tests/test_coordinate_descent.py::test_multioutput_enetcv_error", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_copy_X_True[True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[RidgeClassifier-params3]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_l1_ratio_param_invalid[None]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[False-0-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_sample_weight_invariance[estimator0]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[ElasticNet-params5]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-False-RidgeClassifier-params1]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_toy", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_ridge_consistency[True-0.1]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-True-Ridge-params4]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-True-LinearRegression-params5]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_coordinate_descent[Lasso-1-kwargs1]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[True-False-RidgeClassifierCV-params7]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_l1_ratio_param_invalid[2]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_set_order_sparse[F-F]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_overrided_gram_matrix", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_alpha_warning", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[LassoLars-params1]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[True-False-Ridge-params4]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_grid_search[False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_1d_multioutput_enet_and_multitask_enet_cv", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-False-RidgeClassifierCV-params7]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[RidgeCV-params8]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[Lasso-params0]" ]
[ "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_nonfinite_params" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex eef1135855560..75cd2414647c4 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -337,6 +337,11 @@ Changelog\n :pr:`<PRID>` by :user:`<NAME>` and\n :user:`<NAME>`.\n \n+- |Enhancement| :func:`linear_model.ElasticNet` and \n+ and other linear model classes using coordinate descent show error\n+ messages when non-finite parameter weights are produced. :pr:`<PRID>`\n+ by :user:`<NAME>` and :user:`<NAME>`.\n+\n - |Fix| :class:`linear_model.ElasticNetCV` now produces correct\n warning when `l1_ratio=0`.\n :pr:`<PRID>` by :user:`<NAME>`.\n" } ]
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index eef1135855560..75cd2414647c4 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -337,6 +337,11 @@ Changelog :pr:`<PRID>` by :user:`<NAME>` and :user:`<NAME>`. +- |Enhancement| :func:`linear_model.ElasticNet` and + and other linear model classes using coordinate descent show error + messages when non-finite parameter weights are produced. :pr:`<PRID>` + by :user:`<NAME>` and :user:`<NAME>`. + - |Fix| :class:`linear_model.ElasticNetCV` now produces correct warning when `l1_ratio=0`. :pr:`<PRID>` by :user:`<NAME>`.
scikit-learn/scikit-learn
scikit-learn__scikit-learn-22240
https://github.com/scikit-learn/scikit-learn/pull/22240
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index eef1135855560..496219491fd97 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -341,6 +341,11 @@ Changelog warning when `l1_ratio=0`. :pr:`21724` by :user:`Yar Khine Phyo <yarkhinephyo>`. +- |Enhancement| :class:`linear_model.ElasticNet` and :class:`linear_model.Lasso` + now raise consistent error messages when passed invalid values for `l1_ratio`, + `alpha`, `max_iter` and `tol`. + :pr:`22240` by :user:`Arturo Amor <ArturoAmorQ>`. + :mod:`sklearn.metrics` ...................... diff --git a/sklearn/linear_model/_coordinate_descent.py b/sklearn/linear_model/_coordinate_descent.py index 7e4906962bffc..0c7ae0a7374d3 100644 --- a/sklearn/linear_model/_coordinate_descent.py +++ b/sklearn/linear_model/_coordinate_descent.py @@ -18,6 +18,7 @@ from ..base import RegressorMixin, MultiOutputMixin from ._base import _preprocess_data, _deprecate_normalize from ..utils import check_array +from ..utils import check_scalar from ..utils.validation import check_random_state from ..model_selection import check_cv from ..utils.extmath import safe_sparse_dot @@ -903,6 +904,13 @@ def fit(self, X, y, sample_weight=None, check_input=True): self.normalize, default=False, estimator_name=self.__class__.__name__ ) + check_scalar( + self.alpha, + "alpha", + target_type=numbers.Real, + min_val=0.0, + ) + if self.alpha == 0: warnings.warn( "With alpha=0, this algorithm does not converge " @@ -917,15 +925,21 @@ def fit(self, X, y, sample_weight=None, check_input=True): % self.precompute ) - if ( - not isinstance(self.l1_ratio, numbers.Number) - or self.l1_ratio < 0 - or self.l1_ratio > 1 - ): - raise ValueError( - f"l1_ratio must be between 0 and 1; got l1_ratio={self.l1_ratio}" + check_scalar( + self.l1_ratio, + "l1_ratio", + target_type=numbers.Real, + min_val=0.0, + max_val=1.0, + ) + + if self.max_iter is not None: + check_scalar( + self.max_iter, "max_iter", target_type=numbers.Integral, min_val=1 ) + check_scalar(self.tol, "tol", target_type=numbers.Real, min_val=0.0) + # Remember if X is copied X_copied = False # We expect X and y to be float64 or float32 Fortran ordered arrays
diff --git a/sklearn/linear_model/tests/test_coordinate_descent.py b/sklearn/linear_model/tests/test_coordinate_descent.py index c5ff1156875d4..6e7efe0930a00 100644 --- a/sklearn/linear_model/tests/test_coordinate_descent.py +++ b/sklearn/linear_model/tests/test_coordinate_descent.py @@ -106,17 +106,41 @@ def test_assure_warning_when_normalize(CoordinateDescentModel, normalize, n_warn assert len(record) == n_warnings [email protected]("l1_ratio", (-1, 2, None, 10, "something_wrong")) -def test_l1_ratio_param_invalid(l1_ratio): [email protected]( + "params, err_type, err_msg", + [ + ({"alpha": -1}, ValueError, "alpha == -1, must be >= 0.0"), + ({"l1_ratio": -1}, ValueError, "l1_ratio == -1, must be >= 0.0"), + ({"l1_ratio": 2}, ValueError, "l1_ratio == 2, must be <= 1.0"), + ( + {"l1_ratio": "1"}, + TypeError, + "l1_ratio must be an instance of <class 'numbers.Real'>, not <class 'str'>", + ), + ({"tol": -1.0}, ValueError, "tol == -1.0, must be >= 0."), + ( + {"tol": "1"}, + TypeError, + "tol must be an instance of <class 'numbers.Real'>, not <class 'str'>", + ), + ({"max_iter": 0}, ValueError, "max_iter == 0, must be >= 1."), + ( + {"max_iter": "1"}, + TypeError, + "max_iter must be an instance of <class 'numbers.Integral'>, not <class" + " 'str'>", + ), + ], +) +def test_param_invalid(params, err_type, err_msg): # Check that correct error is raised when l1_ratio in ElasticNet # is outside the correct range X = np.array([[-1.0], [0.0], [1.0]]) - Y = [-1, 0, 1] # just a straight line + y = [-1, 0, 1] # just a straight line - msg = "l1_ratio must be between 0 and 1; got l1_ratio=" - clf = ElasticNet(alpha=0.1, l1_ratio=l1_ratio) - with pytest.raises(ValueError, match=msg): - clf.fit(X, Y) + enet = ElasticNet(**params) + with pytest.raises(err_type, match=err_msg): + enet.fit(X, y) @pytest.mark.parametrize("order", ["C", "F"])
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex eef1135855560..496219491fd97 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -341,6 +341,11 @@ Changelog\n warning when `l1_ratio=0`.\n :pr:`21724` by :user:`Yar Khine Phyo <yarkhinephyo>`.\n \n+- |Enhancement| :class:`linear_model.ElasticNet` and :class:`linear_model.Lasso`\n+ now raise consistent error messages when passed invalid values for `l1_ratio`,\n+ `alpha`, `max_iter` and `tol`.\n+ :pr:`22240` by :user:`Arturo Amor <ArturoAmorQ>`.\n+\n :mod:`sklearn.metrics`\n ......................\n \n" } ]
1.01
c131f7c96bc163b8c069854305ee9f6a51e24000
[ "sklearn/linear_model/tests/test_coordinate_descent.py::test_lassoCV_does_not_set_precompute[auto-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_sparse[LassoCV]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[BayesianRidge-params6]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_sample_weight_invariance[estimator0]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[RidgeCV-params8]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_overrided_gram_matrix", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[LassoLarsIC-params14]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_coordinate_descent[MultiTaskLasso-2-kwargs2]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_multioutput_enetcv_error", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[True-False-RidgeClassifierCV-params7]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_ridge_consistency[False-1000000.0]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_positive_constraint", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[True-False-RidgeClassifier-params1]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_readonly_data", "sklearn/linear_model/tests/test_coordinate_descent.py::test_check_input_false", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[Lasso-params0]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[MultiTaskElasticNet-params9]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-False-Lasso-params0]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_consistency[False-False-0.01-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-False-ElasticNet-params3]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_multi_task_lasso_cv_dtype", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_sparse[ElasticNetCV]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_zero", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_cv_positive_constraint", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_dual_gap", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-False-ElasticNet-params2]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_multitask_enet_and_lasso_cv", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_coordinate_descent[Lasso-1-kwargs1]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_ridge_consistency[True-1000000.0]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_non_float_y[Lasso]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_consistency[False-True-0.01-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_multi_task_lasso_readonly_data", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[ElasticNet-params3]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_path_positive", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_consistency[True-False-0.01-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_correctness[True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_path_unknown_parameter[enet_path]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_ridge_consistency[False-1.0]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[ElasticNetCV-params2]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[ElasticNet-params4]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-True-ElasticNet-params3]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-False-LinearRegression-params5]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-False-RidgeClassifierCV-params7]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_positive_constraint", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[RidgeClassifierCV-params9]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_ridge_consistency[True-0.1]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_cv_with_some_model_selection", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_consistency[False-False-0.01-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_consistency[True-True-0.01-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_correctness[False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[True-False-Ridge-params4]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[LassoCV-params1]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[False-0-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-True-LinearRegression-params5]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[Ridge-params5]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_1d_multioutput_lasso_and_multitask_lasso_cv", "sklearn/linear_model/tests/test_coordinate_descent.py::test_warm_start_multitask_lasso", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_copy_X_True[True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[True-0.5-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_coordinate_descent[MultiTaskLasso-2-kwargs3]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_set_order_sparse[F-F]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[ARDRegression-params7]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_path_unknown_parameter[lasso_path]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[ElasticNet-params5]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_set_order_dense[C-C]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_copy_X_False_check_input_False", "sklearn/linear_model/tests/test_coordinate_descent.py::test_path_parameters", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_path", "sklearn/linear_model/tests/test_coordinate_descent.py::test_set_order_dense[F-C]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-True-ElasticNet-params2]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[False-0-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-False-RidgeCV-params6]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_set_order_sparse[C-F]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_sparse[ElasticNet]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[False-1-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_coordinate_descent[Lasso-1-kwargs0]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_sparse_input_dtype_enet_and_lassocv", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[False-1-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_set_order_dense[C-F]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_alpha_warning", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[True-1-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_positive_constraint", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[LinearRegression-params13]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_non_float_y[ElasticNet]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_multitarget", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-False-Ridge-params4]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_ridge_consistency[False-0.1]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_copy_X_True[False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_toy", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[Lasso-params0]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[RidgeCV-params15]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_toy", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lassoCV_does_not_set_precompute[False-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_elasticnet_precompute_gram_weighted_samples", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[False-0.5-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_multi_task_lasso_and_enet", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[True-False-LinearRegression-params5]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[True-False-RidgeCV-params6]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_sparse_dense_descent_paths", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lassoCV_does_not_set_precompute[True-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-False-RidgeClassifier-params1]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_warm_start_convergence", "sklearn/linear_model/tests/test_coordinate_descent.py::test_elasticnet_precompute_incorrect_gram", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_grid_search[False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-True-RidgeCV-params6]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[False-0.5-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[True-1-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_1d_multioutput_enet_and_multitask_enet_cv", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[Lars-params12]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_sparse[Lasso]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[True-0-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_set_order_dense[F-F]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_cv", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[LinearRegression-params7]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[MultiTaskElasticNet-params10]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[MultiTaskLasso-params11]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_consistency[False-True-0.01-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-True-Lasso-params0]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_set_order_sparse[F-C]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-True-RidgeClassifierCV-params7]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_path_return_models_vs_new_return_gives_same_coefficients", "sklearn/linear_model/tests/test_coordinate_descent.py::test_warm_start_convergence_with_regularizer_decrement", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[RidgeClassifier-params3]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[True-0.5-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[ElasticNet-params4]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_random_descent", "sklearn/linear_model/tests/test_coordinate_descent.py::test_warm_start", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_grid_search[True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_set_order_sparse[C-C]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_uniform_targets", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[True-0-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_does_not_overwrite_sample_weight[True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_float_precision", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_l1_ratio", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_models_cv_fit_with_loky[LassoCV]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_does_not_overwrite_sample_weight[False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-True-RidgeClassifier-params1]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_ridge_consistency[True-1.0]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[OrthogonalMatchingPursuit-params8]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[Ridge-params6]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[RidgeClassifierCV-params16]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_precompute_invalid_argument", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_consistency[True-True-0.01-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-True-Ridge-params4]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_coef_shape_not_zero", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_consistency[True-False-0.01-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_sample_weight_invariance[estimator1]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_models_cv_fit_with_loky[ElasticNetCV]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[RidgeClassifier-params2]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[LassoLars-params1]" ]
[ "sklearn/linear_model/tests/test_coordinate_descent.py::test_param_invalid[params6-ValueError-max_iter == 0, must be >= 1.]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_param_invalid[params0-ValueError-alpha == -1, must be >= 0.0]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_param_invalid[params5-TypeError-tol must be an instance of <class 'numbers.Real'>, not <class 'str'>]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_param_invalid[params4-ValueError-tol == -1.0, must be >= 0.]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_param_invalid[params3-TypeError-l1_ratio must be an instance of <class 'numbers.Real'>, not <class 'str'>]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_param_invalid[params7-TypeError-max_iter must be an instance of <class 'numbers.Integral'>, not <class 'str'>]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_param_invalid[params1-ValueError-l1_ratio == -1, must be >= 0.0]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_param_invalid[params2-ValueError-l1_ratio == 2, must be <= 1.0]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex eef1135855560..496219491fd97 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -341,6 +341,11 @@ Changelog\n warning when `l1_ratio=0`.\n :pr:`<PRID>` by :user:`<NAME>`.\n \n+- |Enhancement| :class:`linear_model.ElasticNet` and :class:`linear_model.Lasso`\n+ now raise consistent error messages when passed invalid values for `l1_ratio`,\n+ `alpha`, `max_iter` and `tol`.\n+ :pr:`<PRID>` by :user:`<NAME>`.\n+\n :mod:`sklearn.metrics`\n ......................\n \n" } ]
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index eef1135855560..496219491fd97 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -341,6 +341,11 @@ Changelog warning when `l1_ratio=0`. :pr:`<PRID>` by :user:`<NAME>`. +- |Enhancement| :class:`linear_model.ElasticNet` and :class:`linear_model.Lasso` + now raise consistent error messages when passed invalid values for `l1_ratio`, + `alpha`, `max_iter` and `tol`. + :pr:`<PRID>` by :user:`<NAME>`. + :mod:`sklearn.metrics` ......................
scikit-learn/scikit-learn
scikit-learn__scikit-learn-22950
https://github.com/scikit-learn/scikit-learn/pull/22950
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 732d2e8035aa6..4c61e08c15149 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -636,6 +636,10 @@ Changelog of sample weights when the input is sparse. :pr:`22899` by :user:`Jérémie du Boisberranger <jeremiedbb>`. +- |Feature| :class:`Ridge` with `solver="lsqr"` now supports to fit sparse input with + `fit_intercept=True`. + :pr:`22950` by :user:`Christian Lorentzen <lorentzenchr>`. + :mod:`sklearn.manifold` ....................... diff --git a/sklearn/linear_model/_ridge.py b/sklearn/linear_model/_ridge.py index 900b5f7c221db..e05f68388ffd6 100644 --- a/sklearn/linear_model/_ridge.py +++ b/sklearn/linear_model/_ridge.py @@ -40,6 +40,22 @@ from ..utils.sparsefuncs import mean_variance_axis +def _get_rescaled_operator(X, X_offset, sample_weight_sqrt): + """Create LinearOperator for matrix products with implicit centering. + + Matrix product `LinearOperator @ coef` returns `(X - X_offset) @ coef`. + """ + + def matvec(b): + return X.dot(b) - sample_weight_sqrt * b.dot(X_offset) + + def rmatvec(b): + return X.T.dot(b) - X_offset * b.dot(sample_weight_sqrt) + + X1 = sparse.linalg.LinearOperator(shape=X.shape, matvec=matvec, rmatvec=rmatvec) + return X1 + + def _solve_sparse_cg( X, y, @@ -54,25 +70,13 @@ def _solve_sparse_cg( if sample_weight_sqrt is None: sample_weight_sqrt = np.ones(X.shape[0], dtype=X.dtype) - def _get_rescaled_operator(X): - - X_offset_scale = X_offset / X_scale - - def matvec(b): - return X.dot(b) - sample_weight_sqrt * b.dot(X_offset_scale) - - def rmatvec(b): - return X.T.dot(b) - X_offset_scale * b.dot(sample_weight_sqrt) - - X1 = sparse.linalg.LinearOperator(shape=X.shape, matvec=matvec, rmatvec=rmatvec) - return X1 - n_samples, n_features = X.shape if X_offset is None or X_scale is None: X1 = sp_linalg.aslinearoperator(X) else: - X1 = _get_rescaled_operator(X) + X_offset_scale = X_offset / X_scale + X1 = _get_rescaled_operator(X, X_offset_scale, sample_weight_sqrt) coefs = np.empty((y.shape[1], n_features), dtype=X.dtype) @@ -137,7 +141,44 @@ def _mv(x): return coefs -def _solve_lsqr(X, y, alpha, max_iter=None, tol=1e-3): +def _solve_lsqr( + X, + y, + *, + alpha, + fit_intercept=True, + max_iter=None, + tol=1e-3, + X_offset=None, + X_scale=None, + sample_weight_sqrt=None, +): + """Solve Ridge regression via LSQR. + + We expect that y is always mean centered. + If X is dense, we expect it to be mean centered such that we can solve + ||y - Xw||_2^2 + alpha * ||w||_2^2 + + If X is sparse, we expect X_offset to be given such that we can solve + ||y - (X - X_offset)w||_2^2 + alpha * ||w||_2^2 + + With sample weights S=diag(sample_weight), this becomes + ||sqrt(S) (y - (X - X_offset) w)||_2^2 + alpha * ||w||_2^2 + and we expect y and X to already be rescaled, i.e. sqrt(S) @ y, sqrt(S) @ X. In + this case, X_offset is the sample_weight weighted mean of X before scaling by + sqrt(S). The objective then reads + ||y - (X - sqrt(S) X_offset) w)||_2^2 + alpha * ||w||_2^2 + """ + if sample_weight_sqrt is None: + sample_weight_sqrt = np.ones(X.shape[0], dtype=X.dtype) + + if sparse.issparse(X) and fit_intercept: + X_offset_scale = X_offset / X_scale + X1 = _get_rescaled_operator(X, X_offset_scale, sample_weight_sqrt) + else: + # No need to touch anything + X1 = X + n_samples, n_features = X.shape coefs = np.empty((y.shape[1], n_features), dtype=X.dtype) n_iter = np.empty(y.shape[1], dtype=np.int32) @@ -148,7 +189,7 @@ def _solve_lsqr(X, y, alpha, max_iter=None, tol=1e-3): for i in range(y.shape[1]): y_column = y[:, i] info = sp_linalg.lsqr( - X, y_column, damp=sqrt_alpha[i], atol=tol, btol=tol, iter_lim=max_iter + X1, y_column, damp=sqrt_alpha[i], atol=tol, btol=tol, iter_lim=max_iter ) coefs[i] = info[0] n_iter[i] = info[2] @@ -351,7 +392,7 @@ def ridge_regression( ---------- X : {ndarray, sparse matrix, LinearOperator} of shape \ (n_samples, n_features) - Training data + Training data. y : ndarray of shape (n_samples,) or (n_samples, n_targets) Target values. @@ -409,9 +450,9 @@ def ridge_regression( `scipy.optimize.minimize`. It can be used only when `positive` is True. - All last six solvers support both dense and sparse data. However, only - 'sag', 'sparse_cg', and 'lbfgs' support sparse input when `fit_intercept` - is True. + All solvers except 'svd' support both dense and sparse data. However, only + 'lsqr', 'sag', 'sparse_cg', and 'lbfgs' support sparse input when + `fit_intercept` is True. .. versionadded:: 0.17 Stochastic Average Gradient descent solver. @@ -518,6 +559,7 @@ def _ridge_regression( X_scale=None, X_offset=None, check_input=True, + fit_intercept=False, ): has_sw = sample_weight is not None @@ -629,7 +671,17 @@ def _ridge_regression( ) elif solver == "lsqr": - coef, n_iter = _solve_lsqr(X, y, alpha, max_iter, tol) + coef, n_iter = _solve_lsqr( + X, + y, + alpha=alpha, + fit_intercept=fit_intercept, + max_iter=max_iter, + tol=tol, + X_offset=X_offset, + X_scale=X_scale, + sample_weight_sqrt=sample_weight_sqrt if has_sw else None, + ) elif solver == "cholesky": if n_features > n_samples: @@ -764,15 +816,15 @@ def fit(self, X, y, sample_weight=None): else: solver = self.solver elif sparse.issparse(X) and self.fit_intercept: - if self.solver not in ["auto", "sparse_cg", "sag", "lbfgs"]: + if self.solver not in ["auto", "lbfgs", "lsqr", "sag", "sparse_cg"]: raise ValueError( "solver='{}' does not support fitting the intercept " "on sparse data. Please set the solver to 'auto' or " - "'sparse_cg', 'sag', 'lbfgs' " + "'lsqr', 'sparse_cg', 'sag', 'lbfgs' " "or set `fit_intercept=False`".format(self.solver) ) - if self.solver == "lbfgs": - solver = "lbfgs" + if self.solver in ["lsqr", "lbfgs"]: + solver = self.solver elif self.solver == "sag" and self.max_iter is None and self.tol > 1e-4: warnings.warn( '"sag" solver requires many iterations to fit ' @@ -846,6 +898,7 @@ def fit(self, X, y, sample_weight=None): return_n_iter=True, return_intercept=False, check_input=False, + fit_intercept=self.fit_intercept, **params, ) self._set_intercept(X_offset, y_offset, X_scale) @@ -944,9 +997,9 @@ class Ridge(MultiOutputMixin, RegressorMixin, _BaseRidge): `scipy.optimize.minimize`. It can be used only when `positive` is True. - All last six solvers support both dense and sparse data. However, only - 'sag', 'sparse_cg', and 'lbfgs' support sparse input when `fit_intercept` - is True. + All solvers except 'svd' support both dense and sparse data. However, only + 'lsqr', 'sag', 'sparse_cg', and 'lbfgs' support sparse input when + `fit_intercept` is True. .. versionadded:: 0.17 Stochastic Average Gradient descent solver.
diff --git a/sklearn/linear_model/tests/test_ridge.py b/sklearn/linear_model/tests/test_ridge.py index 269952ddad659..e3bd6c6146ee9 100644 --- a/sklearn/linear_model/tests/test_ridge.py +++ b/sklearn/linear_model/tests/test_ridge.py @@ -1362,7 +1362,7 @@ def test_n_iter(): assert reg.n_iter_ is None [email protected]("solver", ["sparse_cg", "lbfgs", "auto"]) [email protected]("solver", ["lsqr", "sparse_cg", "lbfgs", "auto"]) @pytest.mark.parametrize("with_sample_weight", [True, False]) def test_ridge_fit_intercept_sparse(solver, with_sample_weight, global_random_seed): """Check that ridge finds the same coefs and intercept on dense and sparse input @@ -1400,7 +1400,7 @@ def test_ridge_fit_intercept_sparse(solver, with_sample_weight, global_random_se assert_allclose(dense_ridge.coef_, sparse_ridge.coef_) [email protected]("solver", ["saga", "lsqr", "svd", "cholesky"]) [email protected]("solver", ["saga", "svd", "cholesky"]) def test_ridge_fit_intercept_sparse_error(solver): X, y = _make_sparse_offset_regression(n_features=20, random_state=0) X_csr = sp.csr_matrix(X)
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 732d2e8035aa6..4c61e08c15149 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -636,6 +636,10 @@ Changelog\n of sample weights when the input is sparse.\n :pr:`22899` by :user:`Jérémie du Boisberranger <jeremiedbb>`.\n \n+- |Feature| :class:`Ridge` with `solver=\"lsqr\"` now supports to fit sparse input with\n+ `fit_intercept=True`.\n+ :pr:`22950` by :user:`Christian Lorentzen <lorentzenchr>`.\n+\n :mod:`sklearn.manifold`\n .......................\n \n" } ]
1.01
48f363f35abec5b3611f96a2b91e9d4e2e1ce527
[ "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[True-shape4]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[0.001-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[svd-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_alphas_conversion[RidgeClassifierCV]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.001-True-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_int_alphas", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape0-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weights", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[auto-svd-eigen-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge[sag]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[SPARSE_FILTER-None-None]", "sklearn/linear_model/tests/test_ridge.py::test_X_CenterStackOp[n_col1]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-csr_matrix-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_best_score[None-ridge1-make_classification]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sag_with_X_fortran", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.01-False-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-csr_matrix-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-csr_matrix-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape1-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-array-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_error[True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_class_weight_vs_sample_weight[RidgeClassifier]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.1-False-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[auto-svd-eigen-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape0-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_alphas_validation[params2-TypeError-alphas\\\\[2\\\\] must be an instance of float, not str-RidgeCV]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[svd-svd-svd-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_fit_intercept_sparse[42-False-auto]", "sklearn/linear_model/tests/test_ridge.py::test_X_CenterStackOp[n_col2]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[False-shape1]", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_ridge_classifiers]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_fit_intercept_sparse[42-True-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[False-shape4]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[SPARSE_FILTER-None-_accuracy_callable]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_error[1]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-8-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_store_cv_values[_mean_squared_error_callable]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape1-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_fit_intercept_sparse[42-True-sparse_cg]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-csr_matrix-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-20-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-csr_matrix-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_custom_scoring[SPARSE_FILTER-cv1]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[True-shape0]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_error[5]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-csr_matrix-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-array-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape1-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-csr_matrix-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-8-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-20-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape1-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_params_validation[params0-ValueError-alpha == -1, must be >= 0.0]", "sklearn/linear_model/tests/test_ridge.py::test_lbfgs_solver_consistency[0.01]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[lsqr-True]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[lsqr]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[lbfgs-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-8-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_alphas_scalar[RidgeClassifierCV]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.01-True-auto]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape0-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-8-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_fit_intercept_sparse[42-False-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape1-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-csr_matrix-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_cv_values_not_stored[ridge1-make_classification]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[0.01-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_params_validation[params1-TypeError-alpha must be an instance of float, not str]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-array-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[False-shape1]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape1-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_primal_dual_relationship", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_cv_store_cv_values[None]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[None-svd-eigen-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-20-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_custom_scoring[DENSE_FILTER-None]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_custom_scoring[SPARSE_FILTER-None]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-array-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape0-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape0-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[DENSE_FILTER-cv1-None]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-csr_matrix-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-8-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape0-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.1-True-auto]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[cholesky-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-csr_matrix-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[True-shape1]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_error_test[sparse_cg]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-8-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_ridge_loo]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[False-shape0]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_error[bad]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.1-False-auto]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_alphas_validation[params0-ValueError-alphas\\\\[1\\\\] == -1, must be > 0.0-RidgeClassifierCV]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_fit_intercept_sparse_error[saga]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[False-shape2]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-csr_matrix-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_X_CenterStackOp[n_col0]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_ridge_cv_normalize]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape0-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[True-shape3]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[False-shape2]", "sklearn/linear_model/tests/test_ridge.py::test_ridge[sparse_cg]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-csr_matrix-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-csr_matrix-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-csr_matrix-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_shapes", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-array-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[DENSE_FILTER-None-accuracy]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_vs_lstsq", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape0-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[False-shape0]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-8-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.1-True-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_store_cv_values[neg_mean_squared_error]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[1.0-True-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-8-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[1.0-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_raises_value_error_if_solver_not_supported", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-array-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-csr_matrix-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape1-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-array-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-array-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape1-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-array-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_best_score[3-ridge0-make_regression]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape0-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_sample_weight", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[True-shape4]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[DENSE_FILTER-None-_accuracy_callable]", "sklearn/linear_model/tests/test_ridge.py::test_sparse_design_with_sample_weights", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-array-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_normalize_deprecated[RidgeClassifierCV]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-20-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape1-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[SPARSE_FILTER-cv1-_accuracy_callable]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_alphas_conversion[RidgeCV]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-array-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.001-False-auto]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_params_validation[params5-TypeError-tol must be an instance of float, not str]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[sparse_cg]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_class_weight_vs_sample_weight[RidgeClassifierCV]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[DENSE_FILTER-cv1-accuracy]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.001-False-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_alphas_validation[params2-TypeError-alphas\\\\[2\\\\] must be an instance of float, not str-RidgeClassifierCV]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[True-shape2]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[0.1-True]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[eigen-eigen-eigen-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match_cholesky", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-array-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[1.0-False-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.01-True-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[DENSE_FILTER-None-None]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape1-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_fit_intercept_sparse_sag[42-False]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[False-shape4]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-20-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-array-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape1-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape1-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-csr_matrix-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape1-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_ridge_cv]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.001-True-auto]", "sklearn/linear_model/tests/test_ridge.py::test_positive_ridge_loss[0.1]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-array-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-20-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_best_score[3-ridge1-make_classification]", "sklearn/linear_model/tests/test_ridge.py::test_ridge[cholesky]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape0-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape0-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape0-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-8-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_individual_penalties", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape0-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_lbfgs_solver_consistency[0.1]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-20-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_error_test[sag]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_sample_weights", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_sparse_cg_max_iter", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-array-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-cholesky]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_fit_intercept_sparse_error[svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_cv_values_not_stored[ridge0-make_regression]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sparse_svd", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-20-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_normalize_deprecated[RidgeCV]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_params_validation[params2-ValueError-max_iter == 0, must be >= 1.]", "sklearn/linear_model/tests/test_ridge.py::test_positive_ridge_loss[0.001]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[False-shape3]", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_ridge_diabetes]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[SPARSE_FILTER-None-accuracy]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-8-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_lbfgs_solver_error", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-array-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-20-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-csr_matrix-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-array-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-8-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-20-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridgeclassifier_multilabel[RidgeClassifierCV-params1]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[True-shape0]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[True-shape3]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-array-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[DENSE_FILTER-cv1-_accuracy_callable]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_fit_intercept_sparse[42-False-sparse_cg]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-20-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-array-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-8-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_tolerance]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_alphas_validation[params0-ValueError-alphas\\\\[1\\\\] == -1, must be > 0.0-RidgeCV]", "sklearn/linear_model/tests/test_ridge.py::test_class_weights", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape1-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-array-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-array-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_error_test[cholesky]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape1-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridgeclassifier_multilabel[RidgeClassifier-params0]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_alphas_scalar[RidgeCV]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_error_test[saga]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_alphas_validation[params1-ValueError-alphas\\\\[0\\\\] == -0.1, must be > 0.0-RidgeCV]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_loo_cv_asym_scoring", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[saga]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-csr_matrix-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-20-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_singular", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape1-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_alphas_validation[params1-ValueError-alphas\\\\[0\\\\] == -0.1, must be > 0.0-RidgeClassifierCV]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-20-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-csr_matrix-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_fit_intercept_sparse[42-True-auto]", "sklearn/linear_model/tests/test_ridge.py::test_positive_ridge_loss[0.01]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-array-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape0-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_store_cv_values[None]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape0-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape0-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape0-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_intercept", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape1-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[1.0-True-auto]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[SPARSE_FILTER-cv1-accuracy]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[cholesky]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[0.001-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_fit_intercept_sparse_error[cholesky]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_error_test[lsqr]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape0-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[1.0-False-auto]", "sklearn/linear_model/tests/test_ridge.py::test_positive_ridge_loss[1.0]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-8-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_cv_store_cv_values[accuracy]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[svd-svd-svd-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_params_validation[params3-TypeError-max_iter must be an instance of int, not str]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape0-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[svd-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-8-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-array-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape1-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-sag]", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_multi_ridge_diabetes]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-array-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape1-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-csr_matrix-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape1-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-csr_matrix-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridgeclassifier_multilabel[RidgeClassifierCV-params2]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[True-shape2]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_error[gcv]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-20-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[eigen-eigen-eigen-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-array-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[lbfgs-False]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[True-shape1]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape0-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[sag]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-csr_matrix-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-csr_matrix-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[None-svd-eigen-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[0.1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_cv_individual_penalties", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-csr_matrix-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-saga]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-array-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape1-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge[svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape1-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape1-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-csr_matrix-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-lsqr]", "sklearn/linear_model/tests/test_ridge.py::test_lbfgs_solver_consistency[1.0]", "sklearn/linear_model/tests/test_ridge.py::test_n_iter", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[SPARSE_FILTER-cv1-None]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape0-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-csr_matrix-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_error_test[svd]", "sklearn/linear_model/tests/test_ridge.py::test_raises_value_error_if_sample_weights_greater_than_1d", "sklearn/linear_model/tests/test_ridge.py::test_ridge_fit_intercept_sparse_sag[42-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-csr_matrix-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-20-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-8-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-8-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape0-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_convergence_fail", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-array-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-20-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_toy_ridge_object", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[1.0-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape0-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape1-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_lbfgs_solver_consistency[0.001]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[0.01-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_params_validation[params4-ValueError-tol == -1.0, must be >= 0.]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.01-False-auto]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-array-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape0-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_custom_scoring[DENSE_FILTER-cv1]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[False-shape3]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_class_weights_cv", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-sparse_cg]", "sklearn/linear_model/tests/test_ridge.py::test_ridge[lsqr]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_best_score[None-ridge0-make_regression]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-csr_matrix-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_cv_store_cv_values[_accuracy_callable]" ]
[ "sklearn/linear_model/tests/test_ridge.py::test_ridge_fit_intercept_sparse[42-False-lsqr]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_fit_intercept_sparse[42-True-lsqr]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 732d2e8035aa6..4c61e08c15149 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -636,6 +636,10 @@ Changelog\n of sample weights when the input is sparse.\n :pr:`<PRID>` by :user:`<NAME>`.\n \n+- |Feature| :class:`Ridge` with `solver=\"lsqr\"` now supports to fit sparse input with\n+ `fit_intercept=True`.\n+ :pr:`<PRID>` by :user:`<NAME>`.\n+\n :mod:`sklearn.manifold`\n .......................\n \n" } ]
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 732d2e8035aa6..4c61e08c15149 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -636,6 +636,10 @@ Changelog of sample weights when the input is sparse. :pr:`<PRID>` by :user:`<NAME>`. +- |Feature| :class:`Ridge` with `solver="lsqr"` now supports to fit sparse input with + `fit_intercept=True`. + :pr:`<PRID>` by :user:`<NAME>`. + :mod:`sklearn.manifold` .......................
scikit-learn/scikit-learn
scikit-learn__scikit-learn-21219
https://github.com/scikit-learn/scikit-learn/pull/21219
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 95367bb35ce10..2cf9d9226dbff 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -38,6 +38,13 @@ Changelog :pr:`123456` by :user:`Joe Bloggs <joeongithub>`. where 123456 is the *pull request* number, not the issue number. +- |Enhancement| All scikit-learn models now generate a more informative + error message when some input contains unexpected `NaN` or infinite values. + In particular the message contains the input name ("X", "y" or + "sample_weight") and if an unexpected `NaN` value is found in `X`, the error + message suggests potential solutions. + :pr:`21219` by :user:`Olivier Grisel <ogrisel>`. + :mod:`sklearn.calibration` .......................... @@ -131,6 +138,12 @@ Changelog instead of `__init__`. :pr:`21430` by :user:`Desislava Vasileva <DessyVV>` and :user:`Lucy Jimenez <LucyJimenez>`. +- |Enhancement| `utils.validation.check_array` and `utils.validation.type_of_target` + now accept an `input_name` parameter to make the error message more + informative when passed invalid input data (e.g. with NaN or infinite + values). + :pr:`21219` by :user:`Olivier Grisel <ogrisel>`. + - |Enhancement| :func:`utils.validation.check_array` returns a float ndarray with `np.nan` when passed a `Float32` or `Float64` pandas extension array with `pd.NA`. :pr:`21278` by `Thomas Fan`_. diff --git a/sklearn/_config.py b/sklearn/_config.py index fe2d27f64857c..21c3cc1b4d142 100644 --- a/sklearn/_config.py +++ b/sklearn/_config.py @@ -148,7 +148,7 @@ def config_context(**new_config): ... assert_all_finite([float('nan')]) Traceback (most recent call last): ... - ValueError: Input contains NaN, ... + ValueError: Input contains NaN... See Also -------- diff --git a/sklearn/base.py b/sklearn/base.py index 557b2c25b2691..9fd41fcf247c8 100644 --- a/sklearn/base.py +++ b/sklearn/base.py @@ -531,15 +531,23 @@ def _validate_data( It is recommended to call reset=True in `fit` and in the first call to `partial_fit`. All other methods that validate `X` should set `reset=False`. + validate_separately : False or tuple of dicts, default=False Only used if y is not None. If False, call validate_X_y(). Else, it must be a tuple of kwargs to be used for calling check_array() on X and y respectively. + + `estimator=self` is automatically added to these dicts to generate + more informative error message in case of invalid input data. + **check_params : kwargs Parameters passed to :func:`sklearn.utils.check_array` or :func:`sklearn.utils.check_X_y`. Ignored if validate_separately is not False. + `estimator=self` is automatically added to these params to generate + more informative error message in case of invalid input data. + Returns ------- out : {ndarray, sparse matrix} or tuple of these @@ -557,10 +565,13 @@ def _validate_data( no_val_X = isinstance(X, str) and X == "no_validation" no_val_y = y is None or isinstance(y, str) and y == "no_validation" + default_check_params = {"estimator": self} + check_params = {**default_check_params, **check_params} + if no_val_X and no_val_y: raise ValueError("Validation should be done on X, y or both.") elif not no_val_X and no_val_y: - X = check_array(X, **check_params) + X = check_array(X, input_name="X", **check_params) out = X elif no_val_X and not no_val_y: y = _check_y(y, **check_params) @@ -572,8 +583,12 @@ def _validate_data( # on X and y isn't equivalent to just calling check_X_y() # :( check_X_params, check_y_params = validate_separately - X = check_array(X, **check_X_params) - y = check_array(y, **check_y_params) + if "estimator" not in check_X_params: + check_X_params = {**default_check_params, **check_X_params} + X = check_array(X, input_name="X", **check_X_params) + if "estimator" not in check_y_params: + check_y_params = {**default_check_params, **check_y_params} + y = check_array(y, input_name="y", **check_y_params) else: X, y = check_X_y(X, y, **check_params) out = X, y diff --git a/sklearn/cluster/_agglomerative.py b/sklearn/cluster/_agglomerative.py index a4a22c73e182f..0a57278e99ba2 100644 --- a/sklearn/cluster/_agglomerative.py +++ b/sklearn/cluster/_agglomerative.py @@ -914,7 +914,7 @@ def fit(self, X, y=None): self : object Returns the fitted instance. """ - X = self._validate_data(X, ensure_min_samples=2, estimator=self) + X = self._validate_data(X, ensure_min_samples=2) return self._fit(X) def _fit(self, X): @@ -1234,7 +1234,7 @@ def fit(self, X, y=None): self : object Returns the transformer. """ - X = self._validate_data(X, ensure_min_features=2, estimator=self) + X = self._validate_data(X, ensure_min_features=2) super()._fit(X.T) return self diff --git a/sklearn/compose/_target.py b/sklearn/compose/_target.py index 7814db9aabe75..e96729b2d91d7 100644 --- a/sklearn/compose/_target.py +++ b/sklearn/compose/_target.py @@ -209,6 +209,7 @@ def fit(self, X, y, **fit_params): """ y = check_array( y, + input_name="y", accept_sparse=False, force_all_finite=True, ensure_2d=False, diff --git a/sklearn/covariance/_graph_lasso.py b/sklearn/covariance/_graph_lasso.py index 81087c17de344..3bdda14de6ad0 100644 --- a/sklearn/covariance/_graph_lasso.py +++ b/sklearn/covariance/_graph_lasso.py @@ -465,9 +465,7 @@ def fit(self, X, y=None): Returns the instance itself. """ # Covariance does not make sense for a single feature - X = self._validate_data( - X, ensure_min_features=2, ensure_min_samples=2, estimator=self - ) + X = self._validate_data(X, ensure_min_features=2, ensure_min_samples=2) if self.assume_centered: self.location_ = np.zeros(X.shape[1]) @@ -856,7 +854,7 @@ def fit(self, X, y=None): Returns the instance itself. """ # Covariance does not make sense for a single feature - X = self._validate_data(X, ensure_min_features=2, estimator=self) + X = self._validate_data(X, ensure_min_features=2) if self.assume_centered: self.location_ = np.zeros(X.shape[1]) else: diff --git a/sklearn/cross_decomposition/_pls.py b/sklearn/cross_decomposition/_pls.py index 3d4012e6050ff..202a3c3cca064 100644 --- a/sklearn/cross_decomposition/_pls.py +++ b/sklearn/cross_decomposition/_pls.py @@ -212,7 +212,9 @@ def fit(self, X, Y): X = self._validate_data( X, dtype=np.float64, copy=self.copy, ensure_min_samples=2 ) - Y = check_array(Y, dtype=np.float64, copy=self.copy, ensure_2d=False) + Y = check_array( + Y, input_name="Y", dtype=np.float64, copy=self.copy, ensure_2d=False + ) if Y.ndim == 1: Y = Y.reshape(-1, 1) @@ -388,7 +390,9 @@ def transform(self, X, Y=None, copy=True): # Apply rotation x_scores = np.dot(X, self.x_rotations_) if Y is not None: - Y = check_array(Y, ensure_2d=False, copy=copy, dtype=FLOAT_DTYPES) + Y = check_array( + Y, input_name="Y", ensure_2d=False, copy=copy, dtype=FLOAT_DTYPES + ) if Y.ndim == 1: Y = Y.reshape(-1, 1) Y -= self._y_mean @@ -424,7 +428,7 @@ def inverse_transform(self, X, Y=None): This transformation will only be exact if `n_components=n_features`. """ check_is_fitted(self) - X = check_array(X, dtype=FLOAT_DTYPES) + X = check_array(X, input_name="X", dtype=FLOAT_DTYPES) # From pls space to original space X_reconstructed = np.matmul(X, self.x_loadings_.T) # Denormalize @@ -432,7 +436,7 @@ def inverse_transform(self, X, Y=None): X_reconstructed += self._x_mean if Y is not None: - Y = check_array(Y, dtype=FLOAT_DTYPES) + Y = check_array(Y, input_name="Y", dtype=FLOAT_DTYPES) # From pls space to original space Y_reconstructed = np.matmul(Y, self.y_loadings_.T) # Denormalize @@ -1036,7 +1040,9 @@ def fit(self, X, Y): X = self._validate_data( X, dtype=np.float64, copy=self.copy, ensure_min_samples=2 ) - Y = check_array(Y, dtype=np.float64, copy=self.copy, ensure_2d=False) + Y = check_array( + Y, input_name="Y", dtype=np.float64, copy=self.copy, ensure_2d=False + ) if Y.ndim == 1: Y = Y.reshape(-1, 1) @@ -1151,7 +1157,7 @@ def transform(self, X, Y=None): Xr = (X - self._x_mean) / self._x_std x_scores = np.dot(Xr, self.x_weights_) if Y is not None: - Y = check_array(Y, ensure_2d=False, dtype=np.float64) + Y = check_array(Y, input_name="Y", ensure_2d=False, dtype=np.float64) if Y.ndim == 1: Y = Y.reshape(-1, 1) Yr = (Y - self._y_mean) / self._y_std diff --git a/sklearn/discriminant_analysis.py b/sklearn/discriminant_analysis.py index 001b4a23d0686..79faa8694a535 100644 --- a/sklearn/discriminant_analysis.py +++ b/sklearn/discriminant_analysis.py @@ -542,7 +542,7 @@ def fit(self, X, y): Fitted estimator. """ X, y = self._validate_data( - X, y, ensure_min_samples=2, estimator=self, dtype=[np.float64, np.float32] + X, y, ensure_min_samples=2, dtype=[np.float64, np.float32] ) self.classes_ = unique_labels(y) n_samples, _ = X.shape diff --git a/sklearn/dummy.py b/sklearn/dummy.py index 6b2133defce6f..fde922634d01b 100644 --- a/sklearn/dummy.py +++ b/sklearn/dummy.py @@ -530,7 +530,7 @@ def fit(self, X, y, sample_weight=None): % (self.strategy, allowed_strategies) ) - y = check_array(y, ensure_2d=False) + y = check_array(y, ensure_2d=False, input_name="y") if len(y) == 0: raise ValueError("y must not be empty.") diff --git a/sklearn/isotonic.py b/sklearn/isotonic.py index b61efc29ebdda..4b1687dea9605 100644 --- a/sklearn/isotonic.py +++ b/sklearn/isotonic.py @@ -116,7 +116,7 @@ def isotonic_regression( by Michael J. Best and Nilotpal Chakravarti, section 3. """ order = np.s_[:] if increasing else np.s_[::-1] - y = check_array(y, ensure_2d=False, dtype=[np.float64, np.float32]) + y = check_array(y, ensure_2d=False, input_name="y", dtype=[np.float64, np.float32]) y = np.array(y[order], dtype=y.dtype) sample_weight = _check_sample_weight(sample_weight, y, dtype=y.dtype, copy=True) sample_weight = np.ascontiguousarray(sample_weight[order]) @@ -337,8 +337,10 @@ def fit(self, X, y, sample_weight=None): new input data. """ check_params = dict(accept_sparse=False, ensure_2d=False) - X = check_array(X, dtype=[np.float64, np.float32], **check_params) - y = check_array(y, dtype=X.dtype, **check_params) + X = check_array( + X, input_name="X", dtype=[np.float64, np.float32], **check_params + ) + y = check_array(y, input_name="y", dtype=X.dtype, **check_params) check_consistent_length(X, y, sample_weight) # Transform y by running the isotonic regression algorithm and diff --git a/sklearn/linear_model/_omp.py b/sklearn/linear_model/_omp.py index 8b94e4a32087f..7790171042d0f 100644 --- a/sklearn/linear_model/_omp.py +++ b/sklearn/linear_model/_omp.py @@ -1022,9 +1022,7 @@ def fit(self, X, y): self.normalize, default=True, estimator_name=self.__class__.__name__ ) - X, y = self._validate_data( - X, y, y_numeric=True, ensure_min_features=2, estimator=self - ) + X, y = self._validate_data(X, y, y_numeric=True, ensure_min_features=2) X = as_float_array(X, copy=False, force_all_finite=False) cv = check_cv(self.cv, classifier=False) max_iter = ( diff --git a/sklearn/manifold/_spectral_embedding.py b/sklearn/manifold/_spectral_embedding.py index 18e647307754e..e8cf61bfe783b 100644 --- a/sklearn/manifold/_spectral_embedding.py +++ b/sklearn/manifold/_spectral_embedding.py @@ -619,9 +619,7 @@ def fit(self, X, y=None): Returns the instance itself. """ - X = self._validate_data( - X, accept_sparse="csr", ensure_min_samples=2, estimator=self - ) + X = self._validate_data(X, accept_sparse="csr", ensure_min_samples=2) random_state = check_random_state(self.random_state) if isinstance(self.affinity, str): diff --git a/sklearn/metrics/_classification.py b/sklearn/metrics/_classification.py index 81b35f1cf6f9e..07956c765ff3f 100644 --- a/sklearn/metrics/_classification.py +++ b/sklearn/metrics/_classification.py @@ -82,8 +82,8 @@ def _check_targets(y_true, y_pred): y_pred : array or indicator matrix """ check_consistent_length(y_true, y_pred) - type_true = type_of_target(y_true) - type_pred = type_of_target(y_pred) + type_true = type_of_target(y_true, input_name="y_true") + type_pred = type_of_target(y_pred, input_name="y_pred") y_type = {type_true, type_pred} if y_type == {"binary", "multiclass"}: @@ -2641,7 +2641,7 @@ def brier_score_loss(y_true, y_prob, *, sample_weight=None, pos_label=None): assert_all_finite(y_prob) check_consistent_length(y_true, y_prob, sample_weight) - y_type = type_of_target(y_true) + y_type = type_of_target(y_true, input_name="y_true") if y_type != "binary": raise ValueError( "Only binary classification is supported. The type of the target " diff --git a/sklearn/metrics/_ranking.py b/sklearn/metrics/_ranking.py index badfff094f7fa..0707c8d2a951d 100644 --- a/sklearn/metrics/_ranking.py +++ b/sklearn/metrics/_ranking.py @@ -210,7 +210,7 @@ def _binary_uninterpolated_average_precision( # guaranteed to be 1, as returned by precision_recall_curve return -np.sum(np.diff(recall) * np.array(precision)[:-1]) - y_type = type_of_target(y_true) + y_type = type_of_target(y_true, input_name="y_true") if y_type == "multilabel-indicator" and pos_label != 1: raise ValueError( "Parameter pos_label is fixed to 1 for " @@ -541,7 +541,7 @@ class scores must correspond to the order of ``labels``, array([0.81..., 0.84... , 0.93..., 0.87..., 0.94...]) """ - y_type = type_of_target(y_true) + y_type = type_of_target(y_true, input_name="y_true") y_true = check_array(y_true, ensure_2d=False, dtype=None) y_score = check_array(y_score, ensure_2d=False) @@ -726,7 +726,7 @@ def _binary_clf_curve(y_true, y_score, pos_label=None, sample_weight=None): Decreasing score values. """ # Check to make sure y_true is valid - y_type = type_of_target(y_true) + y_type = type_of_target(y_true, input_name="y_true") if not (y_type == "binary" or (y_type == "multiclass" and pos_label is not None)): raise ValueError("{0} format is not supported".format(y_type)) @@ -1059,7 +1059,7 @@ def label_ranking_average_precision_score(y_true, y_score, *, sample_weight=None raise ValueError("y_true and y_score have different shape") # Handle badly formatted array and the degenerate case with one label - y_type = type_of_target(y_true) + y_type = type_of_target(y_true, input_name="y_true") if y_type != "multilabel-indicator" and not ( y_type == "binary" and y_true.ndim == 2 ): @@ -1140,7 +1140,7 @@ def coverage_error(y_true, y_score, *, sample_weight=None): y_score = check_array(y_score, ensure_2d=False) check_consistent_length(y_true, y_score, sample_weight) - y_type = type_of_target(y_true) + y_type = type_of_target(y_true, input_name="y_true") if y_type != "multilabel-indicator": raise ValueError("{0} format is not supported".format(y_type)) @@ -1198,7 +1198,7 @@ def label_ranking_loss(y_true, y_score, *, sample_weight=None): y_score = check_array(y_score, ensure_2d=False) check_consistent_length(y_true, y_score, sample_weight) - y_type = type_of_target(y_true) + y_type = type_of_target(y_true, input_name="y_true") if y_type not in ("multilabel-indicator",): raise ValueError("{0} format is not supported".format(y_type)) @@ -1345,7 +1345,7 @@ def _tie_averaged_dcg(y_true, y_score, discount_cumsum): def _check_dcg_target_type(y_true): - y_type = type_of_target(y_true) + y_type = type_of_target(y_true, input_name="y_true") supported_fmt = ( "multilabel-indicator", "continuous-multioutput", @@ -1697,7 +1697,7 @@ def top_k_accuracy_score( """ y_true = check_array(y_true, ensure_2d=False, dtype=None) y_true = column_or_1d(y_true) - y_type = type_of_target(y_true) + y_type = type_of_target(y_true, input_name="y_true") if y_type == "binary" and labels is not None and len(labels) > 2: y_type = "multiclass" y_score = check_array(y_score, ensure_2d=False) diff --git a/sklearn/model_selection/_split.py b/sklearn/model_selection/_split.py index fc38f3355d04e..e2939f6d96096 100644 --- a/sklearn/model_selection/_split.py +++ b/sklearn/model_selection/_split.py @@ -508,7 +508,7 @@ def __init__(self, n_splits=5): def _iter_test_indices(self, X, y, groups): if groups is None: raise ValueError("The 'groups' parameter should not be None.") - groups = check_array(groups, ensure_2d=False, dtype=None) + groups = check_array(groups, input_name="groups", ensure_2d=False, dtype=None) unique_groups, groups = np.unique(groups, return_inverse=True) n_groups = len(unique_groups) @@ -744,7 +744,7 @@ def split(self, X, y, groups=None): split. You can make the results identical by setting `random_state` to an integer. """ - y = check_array(y, ensure_2d=False, dtype=None) + y = check_array(y, input_name="y", ensure_2d=False, dtype=None) return super().split(X, y, groups) @@ -1144,7 +1144,9 @@ def _iter_test_masks(self, X, y, groups): if groups is None: raise ValueError("The 'groups' parameter should not be None.") # We make a copy of groups to avoid side-effects during iteration - groups = check_array(groups, copy=True, ensure_2d=False, dtype=None) + groups = check_array( + groups, input_name="groups", copy=True, ensure_2d=False, dtype=None + ) unique_groups = np.unique(groups) if len(unique_groups) <= 1: raise ValueError( @@ -1178,7 +1180,7 @@ def get_n_splits(self, X=None, y=None, groups=None): """ if groups is None: raise ValueError("The 'groups' parameter should not be None.") - groups = check_array(groups, ensure_2d=False, dtype=None) + groups = check_array(groups, input_name="groups", ensure_2d=False, dtype=None) return len(np.unique(groups)) def split(self, X, y=None, groups=None): @@ -1270,7 +1272,9 @@ def __init__(self, n_groups): def _iter_test_masks(self, X, y, groups): if groups is None: raise ValueError("The 'groups' parameter should not be None.") - groups = check_array(groups, copy=True, ensure_2d=False, dtype=None) + groups = check_array( + groups, input_name="groups", copy=True, ensure_2d=False, dtype=None + ) unique_groups = np.unique(groups) if self.n_groups >= len(unique_groups): raise ValueError( @@ -1310,7 +1314,7 @@ def get_n_splits(self, X=None, y=None, groups=None): """ if groups is None: raise ValueError("The 'groups' parameter should not be None.") - groups = check_array(groups, ensure_2d=False, dtype=None) + groups = check_array(groups, input_name="groups", ensure_2d=False, dtype=None) return int(comb(len(np.unique(groups)), self.n_groups, exact=True)) def split(self, X, y=None, groups=None): @@ -1802,7 +1806,7 @@ def __init__( def _iter_indices(self, X, y, groups): if groups is None: raise ValueError("The 'groups' parameter should not be None.") - groups = check_array(groups, ensure_2d=False, dtype=None) + groups = check_array(groups, input_name="groups", ensure_2d=False, dtype=None) classes, group_indices = np.unique(groups, return_inverse=True) for group_train, group_test in super()._iter_indices(X=classes): # these are the indices of classes in the partition @@ -1919,7 +1923,7 @@ def __init__( def _iter_indices(self, X, y, groups=None): n_samples = _num_samples(X) - y = check_array(y, ensure_2d=False, dtype=None) + y = check_array(y, input_name="y", ensure_2d=False, dtype=None) n_train, n_test = _validate_shuffle_split( n_samples, self.test_size, @@ -2019,7 +2023,7 @@ def split(self, X, y, groups=None): split. You can make the results identical by setting `random_state` to an integer. """ - y = check_array(y, ensure_2d=False, dtype=None) + y = check_array(y, input_name="y", ensure_2d=False, dtype=None) return super().split(X, y, groups) @@ -2300,7 +2304,7 @@ def check_cv(cv=5, y=None, *, classifier=False): if ( classifier and (y is not None) - and (type_of_target(y) in ("binary", "multiclass")) + and (type_of_target(y, input_name="y") in ("binary", "multiclass")) ): return StratifiedKFold(cv) else: diff --git a/sklearn/preprocessing/_data.py b/sklearn/preprocessing/_data.py index db865456db7e0..88fdc7ea85c48 100644 --- a/sklearn/preprocessing/_data.py +++ b/sklearn/preprocessing/_data.py @@ -453,7 +453,6 @@ def partial_fit(self, X, y=None): X = self._validate_data( X, reset=first_pass, - estimator=self, dtype=FLOAT_DTYPES, force_all_finite="allow-nan", ) @@ -841,7 +840,6 @@ def partial_fit(self, X, y=None, sample_weight=None): X = self._validate_data( X, accept_sparse=("csr", "csc"), - estimator=self, dtype=FLOAT_DTYPES, force_all_finite="allow-nan", reset=first_call, @@ -975,7 +973,6 @@ def transform(self, X, copy=None): reset=False, accept_sparse="csr", copy=copy, - estimator=self, dtype=FLOAT_DTYPES, force_all_finite="allow-nan", ) @@ -1017,7 +1014,6 @@ def inverse_transform(self, X, copy=None): X, accept_sparse="csr", copy=copy, - estimator=self, dtype=FLOAT_DTYPES, force_all_finite="allow-nan", ) @@ -1175,7 +1171,6 @@ def partial_fit(self, X, y=None): X, reset=first_pass, accept_sparse=("csr", "csc"), - estimator=self, dtype=FLOAT_DTYPES, force_all_finite="allow-nan", ) @@ -1215,7 +1210,6 @@ def transform(self, X): accept_sparse=("csr", "csc"), copy=self.copy, reset=False, - estimator=self, dtype=FLOAT_DTYPES, force_all_finite="allow-nan", ) @@ -1244,7 +1238,6 @@ def inverse_transform(self, X): X, accept_sparse=("csr", "csc"), copy=self.copy, - estimator=self, dtype=FLOAT_DTYPES, force_all_finite="allow-nan", ) @@ -1488,7 +1481,6 @@ def fit(self, X, y=None): X = self._validate_data( X, accept_sparse="csc", - estimator=self, dtype=FLOAT_DTYPES, force_all_finite="allow-nan", ) @@ -1551,7 +1543,6 @@ def transform(self, X): X, accept_sparse=("csr", "csc"), copy=self.copy, - estimator=self, dtype=FLOAT_DTYPES, reset=False, force_all_finite="allow-nan", @@ -1585,7 +1576,6 @@ def inverse_transform(self, X): X, accept_sparse=("csr", "csc"), copy=self.copy, - estimator=self, dtype=FLOAT_DTYPES, force_all_finite="allow-nan", ) diff --git a/sklearn/preprocessing/_label.py b/sklearn/preprocessing/_label.py index 4410988513f39..b475bd031a059 100644 --- a/sklearn/preprocessing/_label.py +++ b/sklearn/preprocessing/_label.py @@ -289,7 +289,7 @@ def fit(self, y): self : object Returns the instance itself. """ - self.y_type_ = type_of_target(y) + self.y_type_ = type_of_target(y, input_name="y") if "multioutput" in self.y_type_: raise ValueError( "Multioutput target data is not supported with label binarization" @@ -475,7 +475,9 @@ def label_binarize(y, *, classes, neg_label=0, pos_label=1, sparse_output=False) if not isinstance(y, list): # XXX Workaround that will be removed when list of list format is # dropped - y = check_array(y, accept_sparse="csr", ensure_2d=False, dtype=None) + y = check_array( + y, input_name="y", accept_sparse="csr", ensure_2d=False, dtype=None + ) else: if _num_samples(y) == 0: raise ValueError("y has 0 samples: %r" % y) diff --git a/sklearn/utils/estimator_checks.py b/sklearn/utils/estimator_checks.py index ccc6ff23ed8fc..1f7b91621457a 100644 --- a/sklearn/utils/estimator_checks.py +++ b/sklearn/utils/estimator_checks.py @@ -168,17 +168,33 @@ def check_supervised_y_no_nan(name, estimator_orig): estimator = clone(estimator_orig) rng = np.random.RandomState(888) X = rng.randn(10, 5) - y = np.full(10, np.inf) - y = _enforce_estimator_tags_y(estimator, y) - match = ( - "Input contains NaN, infinity or a value too large for " r"dtype\('float64'\)." - ) - err_msg = ( - f"Estimator {name} should have raised error on fitting array y with NaN value." - ) - with raises(ValueError, match=match, err_msg=err_msg): - estimator.fit(X, y) + for value in [np.nan, np.inf]: + y = np.full(10, value) + y = _enforce_estimator_tags_y(estimator, y) + + module_name = estimator.__module__ + if module_name.startswith("sklearn.") and not ( + "test_" in module_name or module_name.endswith("_testing") + ): + # In scikit-learn we want the error message to mention the input + # name and be specific about the kind of unexpected value. + if np.isinf(value): + match = ( + r"Input (y|Y) contains infinity or a value too large for" + r" dtype\('float64'\)." + ) + else: + match = r"Input (y|Y) contains NaN." + else: + # Do not impose a particular error message to third-party libraries. + match = None + err_msg = ( + f"Estimator {name} should have raised error on fitting array y with inf" + " value." + ) + with raises(ValueError, match=match, err_msg=err_msg): + estimator.fit(X, y) def _yield_regressor_checks(regressor): @@ -1725,9 +1741,11 @@ def check_estimators_nan_inf(name, estimator_orig): y = np.ones(10) y[:5] = 0 y = _enforce_estimator_tags_y(estimator_orig, y) - error_string_fit = "Estimator doesn't check for NaN and inf in fit." - error_string_predict = "Estimator doesn't check for NaN and inf in predict." - error_string_transform = "Estimator doesn't check for NaN and inf in transform." + error_string_fit = f"Estimator {name} doesn't check for NaN and inf in fit." + error_string_predict = f"Estimator {name} doesn't check for NaN and inf in predict." + error_string_transform = ( + f"Estimator {name} doesn't check for NaN and inf in transform." + ) for X_train in [X_train_nan, X_train_inf]: # catch deprecation warnings with ignore_warnings(category=FutureWarning): diff --git a/sklearn/utils/multiclass.py b/sklearn/utils/multiclass.py index d734ab591ce2a..62183c91a5fcd 100644 --- a/sklearn/utils/multiclass.py +++ b/sklearn/utils/multiclass.py @@ -28,7 +28,9 @@ def _unique_multiclass(y): def _unique_indicator(y): - return np.arange(check_array(y, accept_sparse=["csr", "csc", "coo"]).shape[1]) + return np.arange( + check_array(y, input_name="y", accept_sparse=["csr", "csc", "coo"]).shape[1] + ) _FN_UNIQUE_LABELS = { @@ -187,7 +189,7 @@ def check_classification_targets(y): ---------- y : array-like """ - y_type = type_of_target(y) + y_type = type_of_target(y, input_name="y") if y_type not in [ "binary", "multiclass", @@ -198,7 +200,7 @@ def check_classification_targets(y): raise ValueError("Unknown label type: %r" % y_type) -def type_of_target(y): +def type_of_target(y, input_name=""): """Determine the type of data indicated by the target. Note that this type is the most specific type that can be inferred. @@ -214,6 +216,11 @@ def type_of_target(y): ---------- y : array-like + input_name : str, default="" + The data name used to construct the error message. + + .. versionadded:: 1.1.0 + Returns ------- target_type : str @@ -322,7 +329,7 @@ def type_of_target(y): # check float and contains non-integer float values if y.dtype.kind == "f" and np.any(y != y.astype(int)): # [.1, .2, 3] or [[.1, .2, 3]] or [[1., .2]] and not [1., 2., 3.] - _assert_all_finite(y) + _assert_all_finite(y, input_name=input_name) return "continuous" + suffix if (len(np.unique(y)) > 2) or (y.ndim >= 2 and len(y[0]) > 1): diff --git a/sklearn/utils/validation.py b/sklearn/utils/validation.py index 7c16ca5cc5f5e..6dc16f5761d05 100644 --- a/sklearn/utils/validation.py +++ b/sklearn/utils/validation.py @@ -87,7 +87,9 @@ def inner_f(*args, **kwargs): return _inner_deprecate_positional_args -def _assert_all_finite(X, allow_nan=False, msg_dtype=None): +def _assert_all_finite( + X, allow_nan=False, msg_dtype=None, estimator_name=None, input_name="" +): """Like assert_all_finite, but only for ndarray.""" # validation is also imported in extmath from .extmath import _safe_accumulator_op @@ -103,26 +105,52 @@ def _assert_all_finite(X, allow_nan=False, msg_dtype=None): if is_float and (np.isfinite(_safe_accumulator_op(np.sum, X))): pass elif is_float: - msg_err = "Input contains {} or a value too large for {!r}." if ( allow_nan and np.isinf(X).any() or not allow_nan and not np.isfinite(X).all() ): - type_err = "infinity" if allow_nan else "NaN, infinity" - raise ValueError( - msg_err.format( - type_err, msg_dtype if msg_dtype is not None else X.dtype + if not allow_nan and np.isnan(X).any(): + type_err = "NaN" + else: + msg_dtype = msg_dtype if msg_dtype is not None else X.dtype + type_err = f"infinity or a value too large for {msg_dtype!r}" + padded_input_name = input_name + " " if input_name else "" + msg_err = f"Input {padded_input_name}contains {type_err}." + if ( + not allow_nan + and estimator_name + and input_name == "X" + and np.isnan(X).any() + ): + # Improve the error message on how to handle missing values in + # scikit-learn. + msg_err += ( + f"\n{estimator_name} does not accept missing values" + " encoded as NaN natively. For supervised learning, you might want" + " to consider sklearn.ensemble.HistGradientBoostingClassifier and" + " Regressor which accept missing values encoded as NaNs natively." + " Alternatively, it is possible to preprocess the data, for" + " instance by using an imputer transformer in a pipeline or drop" + " samples with missing values. See" + " https://scikit-learn.org/stable/modules/impute.html" ) - ) + raise ValueError(msg_err) + # for object dtype data, we only check for NaNs (GH-13254) elif X.dtype == np.dtype("object") and not allow_nan: if _object_dtype_isnan(X).any(): raise ValueError("Input contains NaN") -def assert_all_finite(X, *, allow_nan=False): +def assert_all_finite( + X, + *, + allow_nan=False, + estimator_name=None, + input_name="", +): """Throw a ValueError if X contains NaN or infinity. Parameters @@ -130,8 +158,22 @@ def assert_all_finite(X, *, allow_nan=False): X : {ndarray, sparse matrix} allow_nan : bool, default=False + + estimator_name : str, default=None + The estimator name, used to construct the error message. + + input_name : str, default="" + The data name used to construct the error message. In particular + if `input_name` is "X" and the data has NaN values and + allow_nan is False, the error message will link to the imputer + documentation. """ - _assert_all_finite(X.data if sp.issparse(X) else X, allow_nan) + _assert_all_finite( + X.data if sp.issparse(X) else X, + allow_nan=allow_nan, + estimator_name=estimator_name, + input_name=input_name, + ) def as_float_array(X, *, copy=True, force_all_finite=True): @@ -379,7 +421,14 @@ def indexable(*iterables): def _ensure_sparse_format( - spmatrix, accept_sparse, dtype, copy, force_all_finite, accept_large_sparse + spmatrix, + accept_sparse, + dtype, + copy, + force_all_finite, + accept_large_sparse, + estimator_name=None, + input_name="", ): """Convert a sparse matrix to a given format. @@ -419,6 +468,16 @@ def _ensure_sparse_format( .. versionchanged:: 0.23 Accepts `pd.NA` and converts it into `np.nan` + + estimator_name : str, default=None + The estimator name, used to construct the error message. + + input_name : str, default="" + The data name used to construct the error message. In particular + if `input_name` is "X" and the data has NaN values and + allow_nan is False, the error message will link to the imputer + documentation. + Returns ------- spmatrix_converted : sparse matrix. @@ -475,7 +534,12 @@ def _ensure_sparse_format( stacklevel=2, ) else: - _assert_all_finite(spmatrix.data, allow_nan=force_all_finite == "allow-nan") + _assert_all_finite( + spmatrix.data, + allow_nan=force_all_finite == "allow-nan", + estimator_name=estimator_name, + input_name=input_name, + ) return spmatrix @@ -490,6 +554,15 @@ def _ensure_no_complex_data(array): raise ValueError("Complex data not supported\n{}\n".format(array)) +def _check_estimator_name(estimator): + if estimator is not None: + if isinstance(estimator, str): + return estimator + else: + return estimator.__class__.__name__ + return None + + def _pandas_dtype_needs_early_conversion(pd_dtype): """Return True if pandas extension pd_dtype need to be converted early.""" try: @@ -531,6 +604,7 @@ def check_array( ensure_min_samples=1, ensure_min_features=1, estimator=None, + input_name="", ): """Input validation on an array, list, sparse matrix or similar. @@ -610,6 +684,14 @@ def check_array( estimator : str or estimator instance, default=None If passed, include the name of the estimator in warning messages. + input_name : str, default="" + The data name used to construct the error message. In particular + if `input_name` is "X" and the data has NaN values and + allow_nan is False, the error message will link to the imputer + documentation. + + .. versionadded:: 1.1.0 + Returns ------- array_converted : object @@ -695,13 +777,7 @@ def check_array( ) ) - if estimator is not None: - if isinstance(estimator, str): - estimator_name = estimator - else: - estimator_name = estimator.__class__.__name__ - else: - estimator_name = "Estimator" + estimator_name = _check_estimator_name(estimator) context = " by %s" % estimator_name if estimator is not None else "" # When all dataframe columns are sparse, convert to a sparse array @@ -728,6 +804,8 @@ def check_array( copy=copy, force_all_finite=force_all_finite, accept_large_sparse=accept_large_sparse, + estimator_name=estimator_name, + input_name=input_name, ) else: # If np.array(..) gives ComplexWarning, then we convert the warning @@ -744,7 +822,13 @@ def check_array( # then conversion float -> int would be disallowed. array = np.asarray(array, order=order) if array.dtype.kind == "f": - _assert_all_finite(array, allow_nan=False, msg_dtype=dtype) + _assert_all_finite( + array, + allow_nan=False, + msg_dtype=dtype, + estimator_name=estimator_name, + input_name=input_name, + ) array = array.astype(dtype, casting="unsafe", copy=False) else: array = np.asarray(array, order=order, dtype=dtype) @@ -801,7 +885,12 @@ def check_array( ) if force_all_finite: - _assert_all_finite(array, allow_nan=force_all_finite == "allow-nan") + _assert_all_finite( + array, + input_name=input_name, + estimator_name=estimator_name, + allow_nan=force_all_finite == "allow-nan", + ) if ensure_min_samples > 0: n_samples = _num_samples(array) @@ -978,24 +1067,32 @@ def check_X_y( ensure_min_samples=ensure_min_samples, ensure_min_features=ensure_min_features, estimator=estimator, + input_name="X", ) - y = _check_y(y, multi_output=multi_output, y_numeric=y_numeric) + y = _check_y(y, multi_output=multi_output, y_numeric=y_numeric, estimator=estimator) check_consistent_length(X, y) return X, y -def _check_y(y, multi_output=False, y_numeric=False): +def _check_y(y, multi_output=False, y_numeric=False, estimator=None): """Isolated part of check_X_y dedicated to y validation""" if multi_output: y = check_array( - y, accept_sparse="csr", force_all_finite=True, ensure_2d=False, dtype=None + y, + accept_sparse="csr", + force_all_finite=True, + ensure_2d=False, + dtype=None, + input_name="y", + estimator=estimator, ) else: + estimator_name = _check_estimator_name(estimator) y = column_or_1d(y, warn=True) - _assert_all_finite(y) + _assert_all_finite(y, input_name="y", estimator_name=estimator_name) _ensure_no_complex_data(y) if y_numeric and y.dtype.kind == "O": y = y.astype(np.float64) @@ -1563,6 +1660,7 @@ def _check_sample_weight( dtype=dtype, order="C", copy=copy, + input_name="sample_weight", ) if sample_weight.ndim != 1: raise ValueError("Sample weights must be 1D array or scalar")
diff --git a/sklearn/feature_selection/tests/test_sequential.py b/sklearn/feature_selection/tests/test_sequential.py index d4e6af5c667c2..486cc6d90f09c 100644 --- a/sklearn/feature_selection/tests/test_sequential.py +++ b/sklearn/feature_selection/tests/test_sequential.py @@ -123,7 +123,7 @@ def test_nan_support(): sfs.fit(X, y) sfs.transform(X) - with pytest.raises(ValueError, match="Input contains NaN"): + with pytest.raises(ValueError, match="Input X contains NaN"): # LinearRegression does not support nans SequentialFeatureSelector(LinearRegression(), cv=2).fit(X, y) diff --git a/sklearn/impute/tests/test_impute.py b/sklearn/impute/tests/test_impute.py index 9a4da4a9230a0..1d8c81e244060 100644 --- a/sklearn/impute/tests/test_impute.py +++ b/sklearn/impute/tests/test_impute.py @@ -1277,7 +1277,7 @@ def test_missing_indicator_with_imputer(X, missing_values, X_trans_exp): @pytest.mark.parametrize( "imputer_missing_values, missing_value, err_msg", [ - ("NaN", np.nan, "Input contains NaN"), + ("NaN", np.nan, "Input X contains NaN"), ("-1", -1, "types are expected to be both numerical."), ], ) diff --git a/sklearn/impute/tests/test_knn.py b/sklearn/impute/tests/test_knn.py index b153f3a458161..098899bc1a0f1 100644 --- a/sklearn/impute/tests/test_knn.py +++ b/sklearn/impute/tests/test_knn.py @@ -39,7 +39,7 @@ def test_knn_imputer_default_with_invalid_input(na): [6, 6, 2, 5, 7], ] ) - with pytest.raises(ValueError, match="Input contains (infinity|NaN)"): + with pytest.raises(ValueError, match="Input X contains (infinity|NaN)"): KNNImputer(missing_values=na).fit(X) # Test with inf present in matrix passed in transform() @@ -65,7 +65,7 @@ def test_knn_imputer_default_with_invalid_input(na): ] ) imputer = KNNImputer(missing_values=na).fit(X_fit) - with pytest.raises(ValueError, match="Input contains (infinity|NaN)"): + with pytest.raises(ValueError, match="Input X contains (infinity|NaN)"): imputer.transform(X) # negative n_neighbors @@ -82,9 +82,7 @@ def test_knn_imputer_default_with_invalid_input(na): [np.nan, 6, 0, 5, 13], ] ) - msg = ( - r"Input contains NaN, infinity or a value too large for " r"dtype\('float64'\)" - ) + msg = "Input X contains NaN" with pytest.raises(ValueError, match=msg): imputer.fit(X) diff --git a/sklearn/metrics/cluster/tests/test_common.py b/sklearn/metrics/cluster/tests/test_common.py index 49fd0f06c51f7..98c9a0155a6d3 100644 --- a/sklearn/metrics/cluster/tests/test_common.py +++ b/sklearn/metrics/cluster/tests/test_common.py @@ -214,6 +214,6 @@ def test_inf_nan_input(metric_name, metric_func): else: X = np.random.randint(10, size=(2, 10)) invalids = [(X, [np.inf, np.inf]), (X, [np.nan, np.nan]), (X, [np.nan, np.inf])] - with pytest.raises(ValueError, match="contains NaN, infinity"): + with pytest.raises(ValueError, match=r"contains (NaN|infinity)"): for args in invalids: metric_func(*args) diff --git a/sklearn/metrics/tests/test_common.py b/sklearn/metrics/tests/test_common.py index d5a4fa7adfa17..dfd43ef34096f 100644 --- a/sklearn/metrics/tests/test_common.py +++ b/sklearn/metrics/tests/test_common.py @@ -902,7 +902,7 @@ def test_thresholded_invariance_string_vs_numbers_labels(name): ) @pytest.mark.parametrize("y_true, y_score", invalids_nan_inf) def test_regression_thresholded_inf_nan_input(metric, y_true, y_score): - with pytest.raises(ValueError, match="contains NaN, infinity"): + with pytest.raises(ValueError, match=r"contains (NaN|infinity)"): metric(y_true, y_score) @@ -913,12 +913,29 @@ def test_regression_thresholded_inf_nan_input(metric, y_true, y_score): # Add an additional case for classification only # non-regression test for: # https://github.com/scikit-learn/scikit-learn/issues/6809 - [([np.nan, 1, 2], [1, 2, 3])], # type: ignore + [ + ([np.nan, 1, 2], [1, 2, 3]), + ([np.inf, 1, 2], [1, 2, 3]), + ], # type: ignore ) def test_classification_inf_nan_input(metric, y_true, y_score): """check that classification metrics raise a message mentioning the occurrence of non-finite values in the target vectors.""" - err_msg = "Input contains NaN, infinity or a value too large" + if not np.isfinite(y_true).all(): + input_name = "y_true" + if np.isnan(y_true).any(): + unexpected_value = "NaN" + else: + unexpected_value = "infinity or a value too large" + else: + input_name = "y_pred" + if np.isnan(y_score).any(): + unexpected_value = "NaN" + else: + unexpected_value = "infinity or a value too large" + + err_msg = f"Input {input_name} contains {unexpected_value}" + with pytest.raises(ValueError, match=err_msg): metric(y_true, y_score) diff --git a/sklearn/utils/tests/test_estimator_checks.py b/sklearn/utils/tests/test_estimator_checks.py index c4f954790cd26..0c444e2caa5e0 100644 --- a/sklearn/utils/tests/test_estimator_checks.py +++ b/sklearn/utils/tests/test_estimator_checks.py @@ -496,7 +496,7 @@ def test_check_estimator(): except ImportError: pass # check that predict does input validation (doesn't accept dicts in input) - msg = "Estimator doesn't check for NaN and inf in predict" + msg = "Estimator NoCheckinPredict doesn't check for NaN and inf in predict" with raises(AssertionError, match=msg): check_estimator(NoCheckinPredict()) # check that estimator state does not change diff --git a/sklearn/utils/tests/test_validation.py b/sklearn/utils/tests/test_validation.py index 00c6cf85dda4d..18f88373b02f3 100644 --- a/sklearn/utils/tests/test_validation.py +++ b/sklearn/utils/tests/test_validation.py @@ -175,23 +175,75 @@ def test_check_array_force_all_finite_valid(value, force_all_finite, retype): @pytest.mark.parametrize( - "value, force_all_finite, match_msg", + "value, input_name, force_all_finite, match_msg", [ - (np.inf, True, "Input contains NaN, infinity"), - (np.inf, "allow-nan", "Input contains infinity"), - (np.nan, True, "Input contains NaN, infinity"), - (np.nan, "allow-inf", 'force_all_finite should be a bool or "allow-nan"'), - (np.nan, 1, "Input contains NaN, infinity"), + (np.inf, "", True, "Input contains infinity"), + (np.inf, "X", True, "Input X contains infinity"), + (np.inf, "sample_weight", True, "Input sample_weight contains infinity"), + (np.inf, "X", "allow-nan", "Input X contains infinity"), + (np.nan, "", True, "Input contains NaN"), + (np.nan, "X", True, "Input X contains NaN"), + (np.nan, "y", True, "Input y contains NaN"), + ( + np.nan, + "", + "allow-inf", + 'force_all_finite should be a bool or "allow-nan"', + ), + (np.nan, "", 1, "Input contains NaN"), ], ) @pytest.mark.parametrize("retype", [np.asarray, sp.csr_matrix]) def test_check_array_force_all_finiteinvalid( - value, force_all_finite, match_msg, retype + value, input_name, force_all_finite, match_msg, retype ): - X = retype(np.arange(4).reshape(2, 2).astype(float)) + X = retype(np.arange(4).reshape(2, 2).astype(np.float64)) X[0, 0] = value with pytest.raises(ValueError, match=match_msg): - check_array(X, force_all_finite=force_all_finite, accept_sparse=True) + check_array( + X, + input_name=input_name, + force_all_finite=force_all_finite, + accept_sparse=True, + ) + + [email protected]("input_name", ["X", "y", "sample_weight"]) [email protected]("retype", [np.asarray, sp.csr_matrix]) +def test_check_array_links_to_imputer_doc_only_for_X(input_name, retype): + data = retype(np.arange(4).reshape(2, 2).astype(np.float64)) + data[0, 0] = np.nan + estimator = SVR() + extended_msg = ( + f"\n{estimator.__class__.__name__} does not accept missing values" + " encoded as NaN natively. For supervised learning, you might want" + " to consider sklearn.ensemble.HistGradientBoostingClassifier and Regressor" + " which accept missing values encoded as NaNs natively." + " Alternatively, it is possible to preprocess the" + " data, for instance by using an imputer transformer in a pipeline" + " or drop samples with missing values. See" + " https://scikit-learn.org/stable/modules/impute.html" + ) + + with pytest.raises(ValueError, match=f"Input {input_name} contains NaN") as ctx: + check_array( + data, + estimator=estimator, + input_name=input_name, + accept_sparse=True, + ) + + if input_name == "X": + assert extended_msg in ctx.value.args[0] + else: + assert extended_msg not in ctx.value.args[0] + + if input_name == "X": + # Veriy that _validate_data is automatically called with the right argument + # to generate the same exception: + with pytest.raises(ValueError, match=f"Input {input_name} contains NaN") as ctx: + SVR().fit(data, np.ones(data.shape[0])) + assert extended_msg in ctx.value.args[0] def test_check_array_force_all_finite_object(): @@ -212,15 +264,15 @@ def test_check_array_force_all_finite_object(): [ ( np.array([[1, np.nan]]), - "Input contains NaN, infinity or a value too large for.*int", + "Input contains NaN.", ), ( np.array([[1, np.nan]]), - "Input contains NaN, infinity or a value too large for.*int", + "Input contains NaN.", ), ( np.array([[1, np.inf]]), - "Input contains NaN, infinity or a value too large for.*int", + "Input contains infinity or a value too large for.*int", ), (np.array([[1, np.nan]], dtype=object), "cannot convert float NaN to integer"), ], @@ -425,7 +477,7 @@ def test_check_array_pandas_na_support(pd_dtype, dtype, expected_dtype): assert_allclose(X_checked, X_np) assert X_checked.dtype == expected_dtype - msg = "Input contains NaN, infinity" + msg = "Input contains NaN" with pytest.raises(ValueError, match=msg): check_array(X, force_all_finite=True)
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 95367bb35ce10..2cf9d9226dbff 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -38,6 +38,13 @@ Changelog\n :pr:`123456` by :user:`Joe Bloggs <joeongithub>`.\n where 123456 is the *pull request* number, not the issue number.\n \n+- |Enhancement| All scikit-learn models now generate a more informative\n+ error message when some input contains unexpected `NaN` or infinite values.\n+ In particular the message contains the input name (\"X\", \"y\" or\n+ \"sample_weight\") and if an unexpected `NaN` value is found in `X`, the error\n+ message suggests potential solutions.\n+ :pr:`21219` by :user:`Olivier Grisel <ogrisel>`.\n+\n :mod:`sklearn.calibration`\n ..........................\n \n@@ -131,6 +138,12 @@ Changelog\n instead of `__init__`. :pr:`21430` by :user:`Desislava Vasileva <DessyVV>` and\n :user:`Lucy Jimenez <LucyJimenez>`.\n \n+- |Enhancement| `utils.validation.check_array` and `utils.validation.type_of_target`\n+ now accept an `input_name` parameter to make the error message more\n+ informative when passed invalid input data (e.g. with NaN or infinite\n+ values).\n+ :pr:`21219` by :user:`Olivier Grisel <ogrisel>`.\n+\n - |Enhancement| :func:`utils.validation.check_array` returns a float\n ndarray with `np.nan` when passed a `Float32` or `Float64` pandas extension\n array with `pd.NA`. :pr:`21278` by `Thomas Fan`_.\n" } ]
1.01
bd871537415a80b0505daabeaa8bfe4dd5f30e6d
[ "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[log_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric10]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[int64-longlong-integer]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric11]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric18]", "sklearn/metrics/cluster/tests/test_common.py::test_single_sample[adjusted_rand_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_ones[precision_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric13]", "sklearn/metrics/tests/test_common.py::test_averaging_binary_multilabel_all_zeroes", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[d2_tweedie_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric11]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric26]", "sklearn/metrics/cluster/tests/test_common.py::test_symmetry[rand_score-y11-y21]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric36]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[micro_roc_auc]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[matthews_corrcoef]", "sklearn/metrics/cluster/tests/test_common.py::test_inf_nan_input[mutual_info_score-mutual_info_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric35]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric7]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_zeroes[f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[object-f1_score-False]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[dtype0-float32-Int8]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric9]", "sklearn/utils/tests/test_validation.py::test_check_is_fitted_with_is_fitted", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-roc_auc_score]", "sklearn/utils/tests/test_validation.py::test_check_dataframe_fit_attribute", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_raise_exception[coo]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-coverage_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric13]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[r2_score]", "sklearn/impute/tests/test_knn.py::test_knn_imputer_callable_metric", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-max_error]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_ones[f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[samples_f1_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[f0.5_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric14]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[precision_score]", "sklearn/metrics/cluster/tests/test_common.py::test_permute_labels[normalized_mutual_info_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[coverage_error]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_roc_auc]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric18]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multiclass[f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[det_curve]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_recall_score]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_raise_exception[bsr]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[int8-byte-integer]", "sklearn/utils/tests/test_validation.py::test_get_feature_names_invalid_dtypes_warns[multi-index]", "sklearn/impute/tests/test_knn.py::test_knn_imputer_verify[-1]", "sklearn/impute/tests/test_knn.py::test_knn_imputer_drops_all_nan_features[-1]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[macro_recall_score]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[array-bool]", "sklearn/metrics/tests/test_common.py::test_single_sample[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[dcg_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_f0.5_score]", "sklearn/impute/tests/test_knn.py::test_knn_imputer_zero_nan_imputes_the_same[-1]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-coverage_error]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_ovo_roc_auc]", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_valid[True-insignificant_imag]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-log_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric16]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_absolute_error]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[numeric-float64-UInt16]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_ovr_roc_auc]", "sklearn/utils/tests/test_validation.py::test_num_features[sparse_csc]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[True-X3-cannot convert float NaN to integer]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-brier_score_loss]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_normalize_option_binary_classification[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-brier_score_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multiclass[f1_score]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[numeric-float64-Int16]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[hamming_loss]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[dtype0-float32-UInt8]", "sklearn/metrics/cluster/tests/test_common.py::test_inf_nan_input[normalized_mutual_info_score-normalized_mutual_info_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_ovo_roc_auc]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[uint16-ushort-unsignedinteger]", "sklearn/impute/tests/test_knn.py::test_knn_imputer_not_enough_valid_distances[distance-nan]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[macro_f1_score]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_scalars[bool]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[mean_pinball_loss]", "sklearn/metrics/cluster/tests/test_common.py::test_inf_nan_input[rand_score-rand_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric12]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric7]", "sklearn/metrics/tests/test_common.py::test_normalize_option_multilabel_classification[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[micro_precision_score]", "sklearn/utils/tests/test_validation.py::test_check_non_negative[dok_matrix]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_f0.5_score]", "sklearn/impute/tests/test_knn.py::test_knn_imputer_shape[4-distance]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[normalized_confusion_matrix]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_no_exception[csc]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_jaccard_score]", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_valid[True-insignificant neg]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[micro_precision_score]", "sklearn/utils/tests/test_validation.py::test_check_array_numeric_warns[X4]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric22]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[object-metric3-False]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_pinball_loss]", "sklearn/utils/tests/test_validation.py::test_deprecate_positional_args_warns_for_function", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[tuple-float]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[ovo_roc_auc]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[str-precision_recall_curve-True]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_recall_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_poisson_deviance]", "sklearn/utils/tests/test_validation.py::test_deprecate_positional_args_warns_for_function_version", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[macro_jaccard_score]", "sklearn/utils/tests/test_validation.py::test_check_non_negative[dia_matrix]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-top_k_accuracy_score]", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_invalid[significant neg]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[macro_f0.5_score]", "sklearn/utils/tests/test_validation.py::test_np_matrix", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[uintc-uint32-unsignedinteger]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[micro_f1_score]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[dtype0-float32-Float32]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-hinge_loss]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[micro_roc_auc]", "sklearn/utils/tests/test_validation.py::test_check_array_complex_data_error", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_single_sample[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_ones[f0.5_score]", "sklearn/utils/tests/test_validation.py::test_check_array_dtype_numeric_errors[X0]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[explained_variance_score]", "sklearn/metrics/cluster/tests/test_common.py::test_inf_nan_input[homogeneity_score-homogeneity_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[partial_roc_auc]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric14]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric13]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[mean_absolute_error]", "sklearn/utils/tests/test_validation.py::test_check_array_dtype_numeric_errors[X1]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[samples_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_single_sample[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[mean_squared_error]", "sklearn/metrics/cluster/tests/test_common.py::test_normalized_output[normalized_mutual_info_score]", "sklearn/utils/tests/test_validation.py::test_num_features[dataframe]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[brier_score_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-max_error]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric37]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[brier_score_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[weighted_ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric9]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-brier_score_loss]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[weighted_ovo_roc_auc]", "sklearn/metrics/cluster/tests/test_common.py::test_format_invariance[adjusted_rand_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric24]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[samples_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_f1_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[weighted_ovo_roc_auc]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-median_absolute_error]", "sklearn/metrics/cluster/tests/test_common.py::test_permute_labels[v_measure_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric16]", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_equals[csc_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric19]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric18]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-mean_gamma_deviance]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_sparse_type_exception", "sklearn/impute/tests/test_knn.py::test_knn_imputer_distance_weighted_not_enough_neighbors[nan-None]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[samples_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric20]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric30]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[ovo_roc_auc]", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_invalid[significant_imag]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[r2_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[matthews_corrcoef_score]", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_raise[csr_matrix]", "sklearn/metrics/tests/test_common.py::test_single_sample[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-label_ranking_loss]", "sklearn/impute/tests/test_knn.py::test_knn_imputer_distance_weighted_not_enough_neighbors[-1-None]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[samples_jaccard_score]", "sklearn/impute/tests/test_knn.py::test_knn_imputer_one_n_neighbors[-1]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[mean_squared_error]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[numeric-float64-Int8]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[d2_tweedie_score]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[tuple-int]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[log_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[samples_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[average_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric17]", "sklearn/utils/tests/test_validation.py::test_get_feature_names_pandas", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[log_loss]", "sklearn/metrics/cluster/tests/test_common.py::test_permute_labels[homogeneity_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[samples_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[partial_roc_auc]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[weighted_f0.5_score]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[numeric-float64-UInt8]", "sklearn/metrics/tests/test_common.py::test_single_sample[micro_f1_score]", "sklearn/utils/tests/test_validation.py::test_check_is_fitted_with_attributes[tuple]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-average_precision_score]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[longdouble-float16]", "sklearn/metrics/cluster/tests/test_common.py::test_permute_labels[adjusted_rand_score]", "sklearn/metrics/cluster/tests/test_common.py::test_non_symmetry[completeness_score-y11-y21]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[cohen_kappa_score]", "sklearn/metrics/cluster/tests/test_common.py::test_format_invariance[rand_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[precision_score]", "sklearn/impute/tests/test_knn.py::test_knn_imputer_all_samples_are_neighbors[nan]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[hamming_loss]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_valid[csr_matrix-nan-False]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric31]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[samples_recall_score]", "sklearn/utils/tests/test_validation.py::test_get_feature_names_invalid_dtypes_warns[mixed]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric16]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[float64-float64-Float32]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_zeroes[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric34]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[f1_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[unnormalized_confusion_matrix]", "sklearn/utils/tests/test_validation.py::test_check_non_negative[lil_matrix]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric34]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[ovr_roc_auc]", "sklearn/metrics/cluster/tests/test_common.py::test_format_invariance[completeness_score]", "sklearn/impute/tests/test_knn.py::test_knn_tags[nan-True]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[samples_f2_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-coverage_error]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[byte-uint16]", "sklearn/utils/tests/test_validation.py::test_check_array_min_samples_and_features_messages", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_valid[asarray-nan-False]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_roc_auc]", "sklearn/metrics/cluster/tests/test_common.py::test_inf_nan_input[davies_bouldin_score-davies_bouldin_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-roc_auc_score]", "sklearn/utils/tests/test_validation.py::test_check_feature_names_in_pandas", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric23]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_squared_error]", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_valid[True-insignificant neg float32]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric12]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[log_loss]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_raise_exception[csr]", "sklearn/metrics/tests/test_common.py::test_single_sample[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[f2_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric8]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric17]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[intc-int32-integer]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_symmetry_consistency", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-log_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[dcg_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[samples_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-label_ranking_loss]", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_not_equals[csc_matrix]", "sklearn/metrics/cluster/tests/test_common.py::test_permute_labels[davies_bouldin_score]", "sklearn/metrics/cluster/tests/test_common.py::test_symmetry[adjusted_mutual_info_score-y14-y24]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[coverage_error]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[hinge_loss]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric30]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[roc_auc_score]", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_invalid[significant neg float64]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-hinge_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[samples_f0.5_score]", "sklearn/metrics/cluster/tests/test_common.py::test_symmetric_non_symmetric_union", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[object-jaccard_score-False]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[mean_absolute_percentage_error]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[tuple-bool]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[unnormalized_accuracy_score]", "sklearn/utils/tests/test_validation.py::test_check_sample_weight", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[unnormalized_zero_one_loss]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[uint32-uint64]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric3]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[samples_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[recall_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[precision_recall_curve]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[unnormalized_zero_one_loss]", "sklearn/metrics/cluster/tests/test_common.py::test_symmetry[fowlkes_mallows_score-y16-y26]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[balanced_accuracy_score]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[uintp-ulonglong-unsignedinteger]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric9]", "sklearn/impute/tests/test_knn.py::test_knn_imputer_zero_nan_imputes_the_same[nan]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[macro_f0.5_score]", "sklearn/utils/tests/test_validation.py::test_check_sparse_pandas_sp_format[bsr]", "sklearn/metrics/cluster/tests/test_common.py::test_normalized_output[adjusted_rand_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[top_k_accuracy_score]", "sklearn/utils/tests/test_validation.py::test_num_features[list]", "sklearn/utils/tests/test_validation.py::test_check_array_numeric_warns[X2]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric17]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[samples_precision_score]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[str-roc_curve-True]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[label_ranking_loss]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_zeroes[f2_score]", "sklearn/metrics/cluster/tests/test_common.py::test_symmetry[v_measure_score-y12-y22]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-dcg_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric34]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[zero_one_loss]", "sklearn/impute/tests/test_knn.py::test_knn_imputer_shape[2-distance]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[weighted_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-median_absolute_error]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_dtype_object_conversion", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_valid[csr_matrix-nan-allow-nan]", "sklearn/utils/tests/test_validation.py::test_check_consistent_length", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[f1_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_normalize_option_binary_classification[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[samples_precision_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[macro_recall_score]", "sklearn/metrics/cluster/tests/test_common.py::test_permute_labels[calinski_harabasz_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric11]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_normal_deviance]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-mean_squared_error]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[uint-uint64-unsignedinteger]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[micro_f0.5_score]", "sklearn/metrics/cluster/tests/test_common.py::test_format_invariance[adjusted_mutual_info_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-max_error]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_scalars[int]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-ndcg_score]", "sklearn/utils/tests/test_validation.py::test_check_array_memmap[False]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric35]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[adjusted_balanced_accuracy_score]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_raise_exception[csc]", "sklearn/metrics/cluster/tests/test_common.py::test_normalized_output[completeness_score]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[d2_tweedie_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[unnormalized_multilabel_confusion_matrix]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[series-dict]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance_multilabel_and_multioutput", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric3]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-dcg_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[mean_pinball_loss]", "sklearn/impute/tests/test_knn.py::test_knn_imputer_weight_distance[-1]", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_equals[csr_matrix]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_gamma_deviance]", "sklearn/impute/tests/test_knn.py::test_knn_imputer_removes_all_na_features[nan]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_compound_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[str-average_precision_score-True]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric30]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[micro_recall_score]", "sklearn/metrics/cluster/tests/test_common.py::test_single_sample[mutual_info_score]", "sklearn/impute/tests/test_knn.py::test_knn_imputer_shape[1-distance]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[weighted_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[r2_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric9]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[average_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_roc_auc]", "sklearn/metrics/cluster/tests/test_common.py::test_permute_labels[silhouette_manhattan]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-average_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric35]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_valid[asarray-nan-allow-nan]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[samples_f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-coverage_error]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[log_loss]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_single_sample[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric10]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[mean_compound_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric33]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[samples_f2_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[samples_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[samples_f2_score]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[int16-int32]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[matthews_corrcoef_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_ones[f2_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[hinge_loss]", "sklearn/utils/tests/test_validation.py::test_check_fit_params[indices1]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric15]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[weighted_roc_auc]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-dcg_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric3]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[r2_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[d2_tweedie_score]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric30]", "sklearn/impute/tests/test_knn.py::test_knn_imputer_verify[nan]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_single_sample[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_single_sample[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric16]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric8]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-mean_squared_error]", "sklearn/utils/tests/test_validation.py::test_check_non_negative[bsr_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[precision_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_normal_deviance]", "sklearn/metrics/tests/test_common.py::test_single_sample[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric17]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric29]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-dcg_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[coverage_error]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[macro_precision_score]", "sklearn/metrics/cluster/tests/test_common.py::test_format_invariance[silhouette_manhattan]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[matthews_corrcoef_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[balanced_accuracy_score]", "sklearn/metrics/cluster/tests/test_common.py::test_format_invariance[calinski_harabasz_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[zero_one_loss]", "sklearn/utils/tests/test_validation.py::test_check_array_series", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-max_error]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[median_absolute_error]", "sklearn/impute/tests/test_knn.py::test_knn_imputer_one_n_neighbors[nan]", "sklearn/metrics/tests/test_common.py::test_averaging_multiclass[f0.5_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-log_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[f1_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[weighted_jaccard_score]", "sklearn/utils/tests/test_validation.py::test_check_symmetric", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[object-average_precision_score-True]", "sklearn/metrics/tests/test_common.py::test_averaging_multiclass[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[weighted_recall_score]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[float64-float64-Int8]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric39]", "sklearn/impute/tests/test_knn.py::test_knn_imputer_shape[2-uniform]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_no_exception[bsr]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[mean_absolute_percentage_error]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[tuple-str]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_single_sample[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[micro_precision_score]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_no_exception[csr]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[list-bool]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[False-X0-Input contains NaN.]", "sklearn/metrics/cluster/tests/test_common.py::test_normalized_output[adjusted_mutual_info_score]", "sklearn/metrics/tests/test_common.py::test_normalize_option_binary_classification[top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric21]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[precision_score]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[series-int]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[average_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric11]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[samples_f2_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[hinge_loss]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_zeroes[recall_score]", "sklearn/utils/tests/test_validation.py::test_as_float_array_nan[X0]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[samples_roc_auc]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_f0.5_score]", "sklearn/utils/tests/test_validation.py::test_deprecate_positional_args_warns_for_class", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[weighted_f1_score]", "sklearn/impute/tests/test_knn.py::test_knn_imputer_weight_distance[nan]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample[r2_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-max_error]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[explained_variance_score]", "sklearn/impute/tests/test_knn.py::test_knn_imputer_with_simple_example[nan-0]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[recall_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[samples_roc_auc]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[log_loss]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-ndcg_score]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[array-str]", "sklearn/utils/tests/test_validation.py::test_check_non_negative[csc_matrix]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[False-X1-Input contains NaN.]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[float64-float64-Float64]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[f0.5_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-mean_gamma_deviance]", "sklearn/utils/tests/test_validation.py::test_num_features[sparse_csr]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[matthews_corrcoef_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_average_precision_score]", "sklearn/metrics/cluster/tests/test_common.py::test_single_sample[adjusted_mutual_info_score]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[numeric-float64-Float64]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-label_ranking_average_precision_score]", "sklearn/metrics/cluster/tests/test_common.py::test_format_invariance[mutual_info_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[matthews_corrcoef_score]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[str-metric3-False]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[array-float]", "sklearn/impute/tests/test_knn.py::test_knn_imputer_removes_all_na_features[-1]", "sklearn/metrics/tests/test_common.py::test_normalize_option_multiclass_classification[accuracy_score]", "sklearn/metrics/cluster/tests/test_common.py::test_inf_nan_input[adjusted_mutual_info_score-adjusted_mutual_info_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[weighted_precision_score]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[list-float]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric7]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric9]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[matthews_corrcoef_score]", "sklearn/impute/tests/test_knn.py::test_knn_imputer_distance_weighted_not_enough_neighbors[nan-0]", "sklearn/utils/tests/test_validation.py::test_get_feature_names_numpy", "sklearn/metrics/cluster/tests/test_common.py::test_single_sample[fowlkes_mallows_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric18]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric32]", "sklearn/metrics/tests/test_common.py::test_normalize_option_multilabel_classification[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[micro_jaccard_score]", "sklearn/utils/tests/test_validation.py::test_check_array_on_mock_dataframe", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[zero_one_loss]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[float64-float64-Int16]", "sklearn/utils/tests/test_validation.py::test_as_float_array_nan[X1]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric18]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[str-precision_score-False]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[ovo_roc_auc]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[str-f1_score-False]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[label_ranking_loss]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[micro_jaccard_score]", "sklearn/utils/tests/test_validation.py::test_check_sparse_pandas_sp_format[csr]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric31]", "sklearn/metrics/cluster/tests/test_common.py::test_permute_labels[fowlkes_mallows_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric12]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric2]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[f2_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_average_precision_score]", "sklearn/utils/tests/test_validation.py::test_num_features[array]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[mean_absolute_percentage_error]", "sklearn/utils/tests/test_validation.py::test_check_array_dtype_warning", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_roc_auc]", "sklearn/utils/tests/test_validation.py::test_as_float_array", "sklearn/metrics/tests/test_common.py::test_normalize_option_multiclass_classification[top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample[micro_jaccard_score]", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_not_equals[csr_matrix]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[log_loss]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[log_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[samples_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric41]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_precision_score]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_sparse_no_exception", "sklearn/metrics/cluster/tests/test_common.py::test_normalized_output[fowlkes_mallows_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[weighted_f1_score]", "sklearn/metrics/cluster/tests/test_common.py::test_non_symmetry[homogeneity_score-y10-y20]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric31]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[hamming_loss]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[float16-float32]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[micro_f2_score]", "sklearn/metrics/cluster/tests/test_common.py::test_single_sample[rand_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric27]", "sklearn/utils/tests/test_validation.py::test_num_features[tuple]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_normal_deviance]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric10]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric16]", "sklearn/metrics/cluster/tests/test_common.py::test_format_invariance[v_measure_score]", "sklearn/utils/tests/test_validation.py::test_check_array_memmap[True]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[precision_recall_curve]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[samples_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric35]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[det_curve]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_absolute_percentage_error]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[dtype0-float32-Int16]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[roc_auc_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-average_precision_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_ones[recall_score]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[object-brier_score_loss-True]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[unnormalized_multilabel_confusion_matrix]", "sklearn/impute/tests/test_knn.py::test_knn_imputer_weight_uniform[nan]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[partial_roc_auc]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_valid[csr_matrix-inf-False]", "sklearn/metrics/cluster/tests/test_common.py::test_permute_labels[rand_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[object-precision_recall_curve-True]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multiclass[precision_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[f0.5_score]", "sklearn/utils/tests/test_validation.py::test_check_scalar_invalid[1-test_name1-float-2-4-neither-err_msg0]", "sklearn/utils/tests/test_validation.py::test_check_scalar_invalid[1-test_name2-int-2-4-neither-err_msg1]", "sklearn/metrics/cluster/tests/test_common.py::test_format_invariance[homogeneity_score]", "sklearn/metrics/cluster/tests/test_common.py::test_inf_nan_input[completeness_score-completeness_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[samples_roc_auc]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-label_ranking_loss]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric3]", "sklearn/metrics/tests/test_common.py::test_single_sample[cohen_kappa_score]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[float64-float64-UInt8]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric34]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[macro_f0.5_score]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[short-int16-integer]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[roc_auc_score]", "sklearn/impute/tests/test_knn.py::test_knn_imputer_not_enough_valid_distances[uniform-nan]", "sklearn/metrics/cluster/tests/test_common.py::test_format_invariance[silhouette_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[samples_recall_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[max_error]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[list-str]", "sklearn/utils/tests/test_validation.py::test_check_feature_names_in", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[samples_precision_score]", "sklearn/impute/tests/test_knn.py::test_knn_imputer_shape[5-uniform]", "sklearn/utils/tests/test_validation.py::test_check_array_dtype_stability", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[hinge_loss]", "sklearn/utils/tests/test_validation.py::test_check_is_fitted_attributes", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric13]", "sklearn/utils/tests/test_validation.py::test_suppress_validation", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[partial_roc_auc]", "sklearn/metrics/cluster/tests/test_common.py::test_inf_nan_input[calinski_harabasz_score-calinski_harabasz_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[matthews_corrcoef_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_f1_score]", "sklearn/metrics/cluster/tests/test_common.py::test_format_invariance[normalized_mutual_info_score]", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_valid[True-insignificant pos]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric7]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric10]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-label_ranking_loss]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric3]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[partial_roc_auc]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_f2_score]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[float64-float64-UInt16]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[int_-intp-integer]", "sklearn/utils/tests/test_validation.py::test_check_fit_params[None]", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_invalid[all negative]", "sklearn/utils/tests/test_validation.py::test_check_non_negative[asarray]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[explained_variance_score]", "sklearn/metrics/cluster/tests/test_common.py::test_format_invariance[davies_bouldin_score]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[numeric-float64-Float32]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric31]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric14]", "sklearn/impute/tests/test_knn.py::test_knn_tags[-1-False]", "sklearn/utils/tests/test_validation.py::test_check_dataframe_mixed_float_dtypes", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[macro_f1_score]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_scalars[str]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-ndcg_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric14]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[recall_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[mean_normal_deviance]", "sklearn/utils/tests/test_validation.py::test_check_array_dtype_numeric_errors[X2]", "sklearn/utils/tests/test_validation.py::test_check_array_numeric_warns[X3]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[cohen_kappa_score]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[ubyte-uint8-unsignedinteger]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-label_ranking_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric3]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-ndcg_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric7]", "sklearn/utils/tests/test_validation.py::test_check_array", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[str-recall_score-False]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[recall_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[samples_recall_score]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[object-roc_curve-True]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-label_ranking_average_precision_score]", "sklearn/metrics/cluster/tests/test_common.py::test_inf_nan_input[adjusted_rand_score-adjusted_rand_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric16]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[average_precision_score]", "sklearn/utils/tests/test_validation.py::test_check_scalar_invalid[5-test_name3-int-2-4-neither-err_msg2]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-label_ranking_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-hinge_loss]", "sklearn/metrics/cluster/tests/test_common.py::test_permute_labels[adjusted_mutual_info_score]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[series-float]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric31]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[f0.5_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric13]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric25]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[ndcg_score]", "sklearn/impute/tests/test_knn.py::test_knn_imputer_shape[3-uniform]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-mean_absolute_percentage_error]", "sklearn/utils/tests/test_validation.py::test_check_scalar_invalid[4-test_name6-int-2-4-bad parameter value-err_msg5]", "sklearn/metrics/tests/test_common.py::test_normalize_option_multiclass_classification[zero_one_loss]", "sklearn/impute/tests/test_knn.py::test_knn_imputer_drops_all_nan_features[nan]", "sklearn/utils/tests/test_validation.py::test_check_scalar_invalid[4-test_name5-int-2-4-left-err_msg4]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[macro_f1_score]", "sklearn/impute/tests/test_knn.py::test_knn_imputer_weight_uniform[-1]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-dcg_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric14]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[f2_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-ndcg_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-hinge_loss]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_dtype_casting", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric8]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_zeroes[precision_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[median_absolute_error]", "sklearn/utils/tests/test_validation.py::test_ordering", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[micro_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[samples_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[r2_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_no_averaging_labels", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric8]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric40]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-log_loss]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_roc_auc]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[micro_recall_score]", "sklearn/impute/tests/test_knn.py::test_knn_imputer_distance_weighted_not_enough_neighbors[-1-0]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric38]", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_valid[True-insignificant neg float64]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[r2_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric35]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric34]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[f1_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[roc_auc_score]", "sklearn/metrics/cluster/tests/test_common.py::test_single_sample[homogeneity_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[max_error]", "sklearn/impute/tests/test_knn.py::test_knn_imputer_all_samples_are_neighbors[-1]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric30]", "sklearn/utils/tests/test_validation.py::test_check_scalar_invalid[2-test_name4-int-2-4-right-err_msg3]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-roc_auc_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[weighted_recall_score]", "sklearn/utils/tests/test_validation.py::test_check_array_deprecated_matrix", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[f2_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[max_error]", "sklearn/utils/tests/test_validation.py::test_check_array_numeric_warns[X1]", "sklearn/metrics/cluster/tests/test_common.py::test_inf_nan_input[v_measure_score-v_measure_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[samples_recall_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[mean_absolute_percentage_error]", "sklearn/metrics/cluster/tests/test_common.py::test_permute_labels[mutual_info_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric12]", "sklearn/metrics/cluster/tests/test_common.py::test_inf_nan_input[silhouette_manhattan-metric_func10]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric31]", "sklearn/metrics/tests/test_common.py::test_single_sample[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[macro_jaccard_score]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[int-long-integer]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-roc_auc_score]", "sklearn/utils/tests/test_validation.py::test_check_is_fitted", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric10]", "sklearn/metrics/cluster/tests/test_common.py::test_normalized_output[v_measure_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[samples_precision_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[macro_precision_score]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[array-int]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[label_ranking_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_normal_deviance]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[str-jaccard_score-False]", "sklearn/impute/tests/test_knn.py::test_knn_imputer_shape[5-distance]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[str-brier_score_loss-True]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-coverage_error]", "sklearn/metrics/cluster/tests/test_common.py::test_single_sample[completeness_score]", "sklearn/utils/tests/test_validation.py::test_check_is_fitted_with_attributes[list]", "sklearn/impute/tests/test_knn.py::test_knn_imputer_with_simple_example[nan-None]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_compound_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[mean_absolute_percentage_error]", "sklearn/metrics/cluster/tests/test_common.py::test_symmetry[adjusted_rand_score-y10-y20]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric11]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-log_loss]", "sklearn/metrics/cluster/tests/test_common.py::test_permute_labels[completeness_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric7]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric34]", "sklearn/utils/tests/test_validation.py::test_check_non_negative[csr_matrix]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[micro_jaccard_score]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[array-dict]", "sklearn/metrics/cluster/tests/test_common.py::test_single_sample[normalized_mutual_info_score]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[single-float32-floating]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[label_ranking_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-hinge_loss]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_f2_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric12]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[log_loss]", "sklearn/utils/tests/test_validation.py::test_retrieve_samples_from_non_standard_shape", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[r2_score]", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_equals[array]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_scalars[float]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_ovr_roc_auc]", "sklearn/utils/tests/test_validation.py::test_memmap", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[list-int]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_precision_score]", "sklearn/impute/tests/test_knn.py::test_knn_imputer_not_enough_valid_distances[uniform--1]", "sklearn/metrics/cluster/tests/test_common.py::test_inf_nan_input[silhouette_score-silhouette_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[ndcg_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[unnormalized_zero_one_loss]", "sklearn/metrics/cluster/tests/test_common.py::test_symmetry[mutual_info_score-y13-y23]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric18]", "sklearn/impute/tests/test_knn.py::test_knn_imputer_shape[3-distance]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_no_exception[coo]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[matthews_corrcoef_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[r2_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[micro_precision_score]", "sklearn/metrics/cluster/tests/test_common.py::test_inf_nan_input[fowlkes_mallows_score-fowlkes_mallows_score]", "sklearn/utils/tests/test_validation.py::test_check_array_dtype_numeric_errors[X3]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[unnormalized_multilabel_confusion_matrix]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[float32-double]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[uint8-int8]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_compound_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[mean_absolute_error]", "sklearn/impute/tests/test_knn.py::test_knn_imputer_shape[4-uniform]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[roc_curve]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[dcg_score]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[double-float64-floating]", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[mean_squared_error]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_valid[asarray-inf-False]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric17]", "sklearn/utils/tests/test_validation.py::test_check_array_numeric_warns[X0]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[hinge_loss]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[float16-half-floating]", "sklearn/metrics/cluster/tests/test_common.py::test_normalized_output[rand_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[f1_score]", "sklearn/utils/tests/test_validation.py::test_check_is_fitted_with_attributes[single]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[mean_pinball_loss]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[int0-long-integer]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[micro_f2_score]", "sklearn/metrics/cluster/tests/test_common.py::test_format_invariance[fowlkes_mallows_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_zeroes[f0.5_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[roc_auc_score]", "sklearn/utils/tests/test_validation.py::test_check_non_negative[coo_matrix]", "sklearn/metrics/cluster/tests/test_common.py::test_single_sample[v_measure_score]", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[explained_variance_score]", "sklearn/impute/tests/test_knn.py::test_knn_imputer_with_simple_example[-1-0]", "sklearn/utils/tests/test_validation.py::test_check_X_y_informative_error", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-average_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[macro_f1_score]", "sklearn/utils/tests/test_validation.py::test_check_sparse_pandas_sp_format[csc]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[micro_average_precision_score]", "sklearn/metrics/cluster/tests/test_common.py::test_symmetry[normalized_mutual_info_score-y15-y25]", "sklearn/impute/tests/test_knn.py::test_knn_imputer_not_enough_valid_distances[distance--1]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[tuple-dict]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[samples_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[unnormalized_zero_one_loss]", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_raise[csc_matrix]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[ndcg_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[average_precision_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[hinge_loss]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[object-precision_score-False]", "sklearn/utils/tests/test_validation.py::test_check_sparse_pandas_sp_format[coo]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[True-X1-Input contains NaN.]", "sklearn/metrics/cluster/tests/test_common.py::test_permute_labels[silhouette_score]", "sklearn/impute/tests/test_knn.py::test_knn_imputer_shape[1-uniform]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[dtype0-float32-Float64]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_f0.5_score]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[series-str]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[label_ranking_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[adjusted_balanced_accuracy_score]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[ushort-uint32]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-brier_score_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-label_ranking_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[macro_f0.5_score]", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_invalid[significant neg float32]", "sklearn/metrics/tests/test_common.py::test_single_sample[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-brier_score_loss]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[list-dict]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[accuracy_score]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[longfloat-longdouble-floating]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[ovo_roc_auc]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[explained_variance_score]", "sklearn/utils/tests/test_validation.py::test_check_sparse_pandas_sp_format[True]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric35]", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[explained_variance_score]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[int32-long]", "sklearn/metrics/tests/test_common.py::test_multilabel_representation_invariance", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric28]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[weighted_f1_score]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[True-X0-Input contains NaN.]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[unnormalized_log_loss]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[False-X3-cannot convert float NaN to integer]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_ones[jaccard_score]", "sklearn/utils/tests/test_validation.py::test_has_fit_parameter", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[roc_curve]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[weighted_ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[<lambda>]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[unnormalized_multilabel_confusion_matrix_sample]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[hinge_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric10]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_compound_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric30]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[label_ranking_loss]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[r2_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[weighted_roc_auc]", "sklearn/impute/tests/test_knn.py::test_knn_imputer_with_simple_example[-1-None]", "sklearn/metrics/tests/test_common.py::test_averaging_multiclass[recall_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[d2_tweedie_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-average_precision_score]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[object-recall_score-False]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[series-bool]", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_not_equals[array]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-roc_auc_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[top_k_accuracy_score]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[dtype0-float32-UInt16]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[max_error]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric8]", "sklearn/metrics/cluster/tests/test_common.py::test_normalized_output[homogeneity_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-label_ranking_loss]" ]
[ "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric16]", "sklearn/impute/tests/test_impute.py::test_most_frequent[1-array7-int-10-2]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric36]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-jaccard_score]", "sklearn/impute/tests/test_impute.py::test_imputation_most_frequent", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric39]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[all-3-features_indices1--1-int32-array]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric35]", "sklearn/impute/tests/test_impute.py::test_imputation_constant_object[nan]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric39]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric21]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric37]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric15]", "sklearn/impute/tests/test_impute.py::test_imputation_pipeline_grid_search", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-hamming_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric18]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric23]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[0-array-auto]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric32]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_dont_set_random_state[1-1]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[asarray-inf-X-allow-nan-Input X contains infinity]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric34]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_skip_non_missing[False]", "sklearn/impute/tests/test_impute.py::test_imputation_error_invalid_strategy[const]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric20]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-zero_one_loss]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[0-array-False]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric33]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric41]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric18]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_rank_one", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_skip_non_missing[True]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric39]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric28]", "sklearn/impute/tests/test_impute.py::test_imputation_mean_median_error_invalid_type[None-median]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric20]", "sklearn/impute/tests/test_impute.py::test_imputer_without_indicator[SimpleImputer]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric21]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_imputation_order[roman]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[csr_matrix-nan--True-Input contains NaN]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric2]", "sklearn/impute/tests/test_impute.py::test_most_frequent[extra_value-array0-object-extra_value-2]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-precision_score]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_error[X_fit0-X_trans0-params0-have missing values in transform but have no missing values in fit]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric28]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric7]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-<lambda>]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-multilabel_confusion_matrix]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[False-X2-Input contains infinity or a value too large for.*int]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[missing-only-3-features_indices0-nan-float64-csc_matrix]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[nan-coo_matrix-True]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric35]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric32]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[missing-only-3-features_indices0-nan-float64-lil_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric31]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric41]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-recall_score]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_dont_set_random_state[None-None]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_catch_min_max_error[inf--inf-min_value >= max_value.]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric26]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric39]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric39]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric3]", "sklearn/impute/tests/test_impute.py::test_imputation_mean_median", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_transform_stochasticity", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric20]", "sklearn/utils/tests/test_validation.py::test_check_array_links_to_imputer_doc_only_for_X[csr_matrix-X]", "sklearn/impute/tests/test_impute.py::test_simple_imputation_add_indicator_sparse_matrix[coo_matrix]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_estimators[estimator3]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric30]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric33]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric3]", "sklearn/impute/tests/test_impute.py::test_most_frequent[a-array2-object-a-2]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric35]", "sklearn/impute/tests/test_impute.py::test_most_frequent[10-array6-int-10-2]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric15]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric37]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[csr_matrix-inf-sample_weight-True-Input sample_weight contains infinity]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[missing-only-3-features_indices0-nan-float64-csr_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric22]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric7]", "sklearn/impute/tests/test_impute.py::test_imputation_mean_median_error_invalid_type_list_pandas[list-mean]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_error_param[1--0.001-ValueError-should be a non-negative float]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric38]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric31]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric3]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_min_max_array_like[inf]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_imputation_order[descending]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-confusion_matrix]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_estimators[None]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric34]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric24]", "sklearn/impute/tests/test_impute.py::test_imputation_most_frequent_pandas[category]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric18]", "sklearn/impute/tests/test_impute.py::test_imputation_median_special_cases", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric2]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric22]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric29]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_dont_set_random_state[rs_estimator2-None]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_missing_at_transform[median]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric22]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric40]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric36]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[asarray-inf-sample_weight-True-Input sample_weight contains infinity]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric10]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric15]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_no_missing", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric34]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[0-array-True]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric16]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_min_max_array_like[scalars]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-cohen_kappa_score]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_min_max_array_like[lists]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_estimators[estimator1]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-multilabel_confusion_matrix]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[missing-only-3-features_indices0--1-int32-csr_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric25]", "sklearn/impute/tests/test_impute.py::test_imputation_constant_pandas[category]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric31]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric35]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-hamming_loss]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_feature_names_out", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_verbose", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric41]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_no_missing", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric27]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-hamming_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric19]", "sklearn/impute/tests/test_impute.py::test_simple_imputation_inverse_transform_exceptions[-1]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric29]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric32]", "sklearn/impute/tests/test_knn.py::test_knn_imputer_default_with_invalid_input[nan]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-jaccard_score]", "sklearn/impute/tests/test_impute.py::test_imputation_error_sparse_0[median]", "sklearn/impute/tests/test_impute.py::test_imputation_error_invalid_strategy[None]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[nan-array-False]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[csr_matrix-nan--allow-inf-force_all_finite should be a bool or \"allow-nan\"]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-matthews_corrcoef]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric7]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric36]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-hamming_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric35]", "sklearn/impute/tests/test_impute.py::test_imputation_shape[median]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_clip_truncnorm", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric21]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric10]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric19]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_transform_recovery[5]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[asarray-inf-X-True-Input X contains infinity]", "sklearn/utils/tests/test_validation.py::test_check_array_links_to_imputer_doc_only_for_X[asarray-X]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_string", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-f1_score]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_one_feature[X0]", "sklearn/impute/tests/test_impute.py::test_simple_imputation_add_indicator_sparse_matrix[lil_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric2]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-cohen_kappa_score]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[all-3-features_indices1--1-int32-bsr_matrix]", "sklearn/impute/tests/test_impute.py::test_imputation_most_frequent_objects[NAN]", "sklearn/impute/tests/test_impute.py::test_imputation_const_mostf_error_invalid_types[dtype2-most_frequent]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[all-3-features_indices1-0-int32-array]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric38]", "sklearn/impute/tests/test_impute.py::test_imputation_const_mostf_error_invalid_types[dtype1-most_frequent]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric28]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric16]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric15]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[nan-csc_matrix-True]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-precision_score]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_dont_set_random_state[1-None]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric10]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[missing-only-3-features_indices0-nan-float64-coo_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric29]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric16]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric19]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_dont_set_random_state[1-rs_imputer2]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric26]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[nan-csc_matrix-auto]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric29]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_missing_at_transform[most_frequent]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric23]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-<lambda>]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_raise_on_sparse_with_missing_0[lil_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric38]", "sklearn/impute/tests/test_impute.py::test_most_frequent[1-array5-int-10-1]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[nan-lil_matrix-auto]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric31]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[nan-array-True]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric27]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric7]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[missing-only-3-features_indices0-0-int32-array]", "sklearn/impute/tests/test_impute.py::test_inconsistent_dtype_X_missing_values[-1--1-types are expected to be both numerical.-IterativeImputer]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric26]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric24]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric19]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric18]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric3]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric30]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric26]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-matthews_corrcoef]", "sklearn/impute/tests/test_impute.py::test_imputation_constant_object[0]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric29]", "sklearn/impute/tests/test_impute.py::test_imputation_most_frequent_pandas[object]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_clip", "sklearn/impute/tests/test_impute.py::test_imputation_constant_error_invalid_type[1.0-nan]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric23]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric34]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_error_param[-1-0.001-ValueError-should be a positive integer]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric21]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_with_imputer[X1-nan-X_trans_exp1]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric15]", "sklearn/utils/tests/test_validation.py::test_check_array_links_to_imputer_doc_only_for_X[csr_matrix-sample_weight]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_imputation_order[random]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric25]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric18]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-jaccard_score]", "sklearn/impute/tests/test_impute.py::test_simple_imputation_inverse_transform[-1]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric34]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric33]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_dont_set_random_state[None-1]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[missing-only-3-features_indices0--1-int32-bsr_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric28]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric35]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-<lambda>]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric30]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric20]", "sklearn/impute/tests/test_impute.py::test_imputation_constant_object[]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric28]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric27]", "sklearn/impute/tests/test_impute.py::test_imputation_mean_median_error_invalid_type[str-median]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric36]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_error[X_fit3-X_trans3-params3-MissingIndicator does not support data with dtype]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric21]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-matthews_corrcoef]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric22]", "sklearn/impute/tests/test_impute.py::test_imputation_mean_median_error_invalid_type[object-median]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric38]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_all_missing", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric40]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric23]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-multilabel_confusion_matrix]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[asarray-nan--allow-inf-force_all_finite should be a bool or \"allow-nan\"]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric20]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[asarray-nan-X-True-Input X contains NaN]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric29]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[True-X2-Input contains infinity or a value too large for.*int]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric25]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_catch_min_max_error[min_value2-max_value2-_value' should be of shape]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric21]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric33]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[all-3-features_indices1-nan-float64-bsr_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric7]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[nan-lil_matrix-False]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric36]", "sklearn/impute/tests/test_impute.py::test_inconsistent_dtype_X_missing_values[NaN-nan-Input X contains NaN-IterativeImputer]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric24]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric25]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric41]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[csr_matrix-nan--1-Input contains NaN]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric40]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric24]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric28]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric39]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric38]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric38]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric20]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric19]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_min_max_array_like[None-default]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_no_explicit_zeros", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric31]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric27]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric40]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric36]", "sklearn/impute/tests/test_impute.py::test_simple_imputation_add_indicator_sparse_matrix[bsr_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-matthews_corrcoef]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[all-3-features_indices1--1-int32-csc_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-recall_score]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[nan-csr_matrix-auto]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric37]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric24]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_estimators[estimator4]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_raise_on_sparse_with_missing_0[coo_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-multilabel_confusion_matrix]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[nan-array-auto]", "sklearn/impute/tests/test_impute.py::test_simple_imputation_string_list[constant-missing_value]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[nan-csr_matrix-False]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-matthews_corrcoef]", "sklearn/impute/tests/test_impute.py::test_imputation_order[ascending-idx_order0]", "sklearn/impute/tests/test_impute.py::test_imputation_mean_median_error_invalid_type_list_pandas[list-median]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric18]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric35]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric18]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[nan-csc_matrix-False]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_imputation_order[ascending]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[asarray-nan-y-True-Input y contains NaN]", "sklearn/impute/tests/test_impute.py::test_imputation_const_mostf_error_invalid_types[dtype2-constant]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[missing-only-3-features_indices0--1-int32-array]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric27]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric26]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric40]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric23]", "sklearn/impute/tests/test_impute.py::test_imputation_error_sparse_0[constant]", "sklearn/impute/tests/test_impute.py::test_simple_imputation_string_list[most_frequent-b]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric32]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric31]", "sklearn/impute/tests/test_impute.py::test_imputation_most_frequent_objects[None]", "sklearn/impute/tests/test_impute.py::test_imputation_most_frequent_objects[0]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_catch_min_max_error[100-0-min_value >= max_value.]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric22]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric16]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-hamming_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric10]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_min_max_array_like_imputation[None-vs-inf]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_with_imputer[X3-None-X_trans_exp3]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric7]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-recall_score]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[missing-only-3-features_indices0-nan-float64-array]", "sklearn/impute/tests/test_impute.py::test_imputation_const_mostf_error_invalid_types[str-most_frequent]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-matthews_corrcoef]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric16]", "sklearn/impute/tests/test_impute.py::test_imputation_most_frequent_objects[nan]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-jaccard_score]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_transform_recovery[3]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_zero_iters", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric37]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric33]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric30]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric10]", "sklearn/impute/tests/test_impute.py::test_imputation_shape[mean]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric38]", "sklearn/impute/tests/test_impute.py::test_simple_imputation_inverse_transform[nan]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_missing_at_transform[mean]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric19]", "sklearn/impute/tests/test_impute.py::test_imputation_mean_median_error_invalid_type[None-mean]", "sklearn/impute/tests/test_impute.py::test_imputation_order[descending-idx_order1]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-cohen_kappa_score]", "sklearn/impute/tests/test_impute.py::test_imputation_most_frequent_objects[]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric25]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric20]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric25]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric22]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric29]", "sklearn/impute/tests/test_impute.py::test_imputation_error_sparse_0[most_frequent]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-precision_score]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[csr_matrix-inf-X-allow-nan-Input X contains infinity]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[csr_matrix-nan-y-True-Input y contains NaN]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric25]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_dont_set_random_state[rs_estimator2-rs_imputer2]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric27]", "sklearn/impute/tests/test_impute.py::test_imputation_error_invalid_strategy[101]", "sklearn/utils/tests/test_validation.py::test_check_array_links_to_imputer_doc_only_for_X[asarray-sample_weight]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric39]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[csr_matrix-inf-X-True-Input X contains infinity]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-f1_score]", "sklearn/impute/tests/test_impute.py::test_imputer_without_indicator[IterativeImputer]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[missing-only-3-features_indices0--1-int32-coo_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric28]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_error[X_fit2-X_trans2-params2-'sparse' has to be a boolean or 'auto']", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric2]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric16]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[all-3-features_indices1-nan-float64-csc_matrix]", "sklearn/impute/tests/test_impute.py::test_inconsistent_dtype_X_missing_values[-1--1-types are expected to be both numerical.-SimpleImputer]", "sklearn/utils/tests/test_validation.py::test_check_array_links_to_imputer_doc_only_for_X[csr_matrix-y]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric15]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric31]", "sklearn/impute/tests/test_impute.py::test_imputation_mean_median_error_invalid_type[str-mean]", "sklearn/impute/tests/test_impute.py::test_most_frequent[10-array4-int-10-2]", "sklearn/impute/tests/test_impute.py::test_imputation_deletion_warning[most_frequent]", "sklearn/impute/tests/test_impute.py::test_imputation_deletion_warning[mean]", "sklearn/impute/tests/test_impute.py::test_imputation_shape[constant]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric19]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[nan-coo_matrix-auto]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric26]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_one_feature[X1]", "sklearn/impute/tests/test_knn.py::test_knn_imputer_default_with_invalid_input[-1]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[asarray-nan--True-Input contains NaN]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-accuracy_score]", "sklearn/impute/tests/test_impute.py::test_most_frequent[min_value-array3-object-z-2]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_raise_on_sparse_with_missing_0[csc_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric40]", "sklearn/impute/tests/test_impute.py::test_imputation_const_mostf_error_invalid_types[dtype1-constant]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[all-3-features_indices1--1-int32-lil_matrix]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_min_max_array_like_imputation[Scalar-vs-vector]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric23]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[all-3-features_indices1-nan-float64-csr_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric22]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric30]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric2]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric21]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric2]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-matthews_corrcoef]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_raise_on_sparse_with_missing_0[csr_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric34]", "sklearn/impute/tests/test_impute.py::test_imputation_const_mostf_error_invalid_types[str-constant]", "sklearn/impute/tests/test_impute.py::test_most_frequent[most_frequent_value-array1-object-extra_value-1]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric33]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric36]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[nan-coo_matrix-False]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric33]", "sklearn/impute/tests/test_impute.py::test_imputation_constant_float[asarray]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-confusion_matrix]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_raise_on_sparse_with_missing_0[bsr_matrix]", "sklearn/impute/tests/test_impute.py::test_imputation_deletion_warning[median]", "sklearn/impute/tests/test_impute.py::test_imputation_constant_object[NAN]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[nan-lil_matrix-True]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric30]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-f1_score]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_imputation_order[arabic]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric23]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric27]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric41]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric26]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric37]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[missing-only-3-features_indices0-nan-float64-bsr_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric2]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric30]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric40]", "sklearn/utils/tests/test_validation.py::test_check_array_links_to_imputer_doc_only_for_X[asarray-y]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_additive_matrix", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric10]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-accuracy_score]", "sklearn/impute/tests/test_impute.py::test_imputation_constant_object[None]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric32]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_truncated_normal_posterior", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric3]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric3]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-<lambda>]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_with_imputer[X0-a-X_trans_exp0]", "sklearn/impute/tests/test_impute.py::test_imputation_copy", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[missing-only-3-features_indices0--1-int32-lil_matrix]", "sklearn/impute/tests/test_impute.py::test_inconsistent_dtype_X_missing_values[NaN-nan-Input X contains NaN-SimpleImputer]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric41]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[all-3-features_indices1--1-int32-csr_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-<lambda>]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric32]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-recall_score]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_estimators[estimator2]", "sklearn/impute/tests/test_impute.py::test_simple_imputation_add_indicator_sparse_matrix[csc_matrix]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[nan-csr_matrix-True]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_with_imputer[X2-nan-X_trans_exp2]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric34]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_dont_set_random_state[None-rs_imputer2]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_error[X_fit1-X_trans1-params1-'features' has to be either 'missing-only' or 'all']", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[csr_matrix-inf--True-Input contains infinity]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[all-3-features_indices1-nan-float64-coo_matrix]", "sklearn/impute/tests/test_impute.py::test_simple_imputation_inverse_transform_exceptions[nan]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-<lambda>]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric3]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric41]", "sklearn/impute/tests/test_impute.py::test_imputation_constant_float[csr_matrix]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[asarray-nan--1-Input contains NaN]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[asarray-inf--True-Input contains infinity]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_min_max_array_like[lists-with-inf]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric24]", "sklearn/impute/tests/test_impute.py::test_imputation_mean_median_error_invalid_type_list_pandas[dataframe-mean]", "sklearn/impute/tests/test_impute.py::test_imputation_error_sparse_0[mean]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-accuracy_score]", "sklearn/impute/tests/test_impute.py::test_imputation_mean_median_error_invalid_type_list_pandas[dataframe-median]", "sklearn/impute/tests/test_impute.py::test_imputation_constant_error_invalid_type[1-0]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric15]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[csr_matrix-nan-X-True-Input X contains NaN]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[all-3-features_indices1-nan-float64-lil_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-balanced_accuracy_score]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[missing-only-3-features_indices0--1-int32-csc_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric37]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-<lambda>]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-hamming_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-zero_one_loss]", "sklearn/impute/tests/test_impute.py::test_imputation_shape[most_frequent]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric37]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric32]", "sklearn/impute/tests/test_impute.py::test_imputation_constant_integer", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_dont_set_random_state[rs_estimator2-1]", "sklearn/impute/tests/test_impute.py::test_imputation_constant_pandas[object]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric10]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-confusion_matrix]", "sklearn/impute/tests/test_impute.py::test_simple_imputation_add_indicator_sparse_matrix[csr_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric7]", "sklearn/impute/tests/test_impute.py::test_imputation_mean_median_error_invalid_type[object-mean]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-zero_one_loss]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[all-3-features_indices1-nan-float64-array]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_early_stopping", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-hamming_loss]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[all-3-features_indices1--1-int32-coo_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric24]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 95367bb35ce10..2cf9d9226dbff 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -38,6 +38,13 @@ Changelog\n :pr:`<PRID>` by :user:`<NAME>`.\n where <PRID> is the *pull request* number, not the issue number.\n \n+- |Enhancement| All scikit-learn models now generate a more informative\n+ error message when some input contains unexpected `NaN` or infinite values.\n+ In particular the message contains the input name (\"X\", \"y\" or\n+ \"sample_weight\") and if an unexpected `NaN` value is found in `X`, the error\n+ message suggests potential solutions.\n+ :pr:`<PRID>` by :user:`<NAME>`.\n+\n :mod:`sklearn.calibration`\n ..........................\n \n@@ -131,6 +138,12 @@ Changelog\n instead of `__init__`. :pr:`<PRID>` by :user:`<NAME>` and\n :user:`<NAME>`.\n \n+- |Enhancement| `utils.validation.check_array` and `utils.validation.type_of_target`\n+ now accept an `input_name` parameter to make the error message more\n+ informative when passed invalid input data (e.g. with NaN or infinite\n+ values).\n+ :pr:`<PRID>` by :user:`<NAME>`.\n+\n - |Enhancement| :func:`utils.validation.check_array` returns a float\n ndarray with `np.nan` when passed a `Float32` or `Float64` pandas extension\n array with `pd.NA`. :pr:`<PRID>` by `<NAME>`_.\n" } ]
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 95367bb35ce10..2cf9d9226dbff 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -38,6 +38,13 @@ Changelog :pr:`<PRID>` by :user:`<NAME>`. where <PRID> is the *pull request* number, not the issue number. +- |Enhancement| All scikit-learn models now generate a more informative + error message when some input contains unexpected `NaN` or infinite values. + In particular the message contains the input name ("X", "y" or + "sample_weight") and if an unexpected `NaN` value is found in `X`, the error + message suggests potential solutions. + :pr:`<PRID>` by :user:`<NAME>`. + :mod:`sklearn.calibration` .......................... @@ -131,6 +138,12 @@ Changelog instead of `__init__`. :pr:`<PRID>` by :user:`<NAME>` and :user:`<NAME>`. +- |Enhancement| `utils.validation.check_array` and `utils.validation.type_of_target` + now accept an `input_name` parameter to make the error message more + informative when passed invalid input data (e.g. with NaN or infinite + values). + :pr:`<PRID>` by :user:`<NAME>`. + - |Enhancement| :func:`utils.validation.check_array` returns a float ndarray with `np.nan` when passed a `Float32` or `Float64` pandas extension array with `pd.NA`. :pr:`<PRID>` by `<NAME>`_.
scikit-learn/scikit-learn
scikit-learn__scikit-learn-22249
https://github.com/scikit-learn/scikit-learn/pull/22249
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index c0f705a8ceef7..aa1a71466fce0 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -314,6 +314,12 @@ Changelog `max_iter` and `tol`. :pr:`21341` by :user:`Arturo Amor <ArturoAmorQ>`. +:mod:`sklearn.isotonic` +....................... + +- |Enhancement| Adds :term:`get_feature_names_out` to `IsotonicRegression`. + :pr:`22249` by `Thomas Fan`_. + :mod:`sklearn.linear_model` ........................... diff --git a/sklearn/isotonic.py b/sklearn/isotonic.py index 4b1687dea9605..ef8fb3f332e71 100644 --- a/sklearn/isotonic.py +++ b/sklearn/isotonic.py @@ -416,6 +416,26 @@ def predict(self, T): """ return self.transform(T) + # We implement get_feature_names_out here instead of using + # `_ClassNamePrefixFeaturesOutMixin`` because `input_features` are ignored. + # `input_features` are ignored because `IsotonicRegression` accepts 1d + # arrays and the semantics of `feature_names_in_` are not clear for 1d arrays. + def get_feature_names_out(self, input_features=None): + """Get output feature names for transformation. + + Parameters + ---------- + input_features : array-like of str or None, default=None + Ignored. + + Returns + ------- + feature_names_out : ndarray of str objects + An ndarray with one string i.e. ["isotonicregression0"]. + """ + class_name = self.__class__.__name__.lower() + return np.asarray([f"{class_name}0"], dtype=object) + def __getstate__(self): """Pickle-protocol - return state of the estimator.""" state = super().__getstate__()
diff --git a/sklearn/tests/test_common.py b/sklearn/tests/test_common.py index a8178a4219485..49ee681316554 100644 --- a/sklearn/tests/test_common.py +++ b/sklearn/tests/test_common.py @@ -382,7 +382,6 @@ def test_pandas_column_name_consistency(estimator): GET_FEATURES_OUT_MODULES_TO_IGNORE = [ "cluster", "ensemble", - "isotonic", "kernel_approximation", "preprocessing", "manifold", diff --git a/sklearn/tests/test_isotonic.py b/sklearn/tests/test_isotonic.py index 4c8ea220e75c0..25f9e26d70d34 100644 --- a/sklearn/tests/test_isotonic.py +++ b/sklearn/tests/test_isotonic.py @@ -695,3 +695,18 @@ def test_isotonic_regression_sample_weight_not_overwritten(): IsotonicRegression().fit(X, y, sample_weight=sample_weight_fit) assert_allclose(sample_weight_fit, sample_weight_original) + + [email protected]("shape", ["1d", "2d"]) +def test_get_feature_names_out(shape): + """Check `get_feature_names_out` for `IsotonicRegression`.""" + X = np.arange(10) + if shape == "2d": + X = X.reshape(-1, 1) + y = np.arange(10) + + iso = IsotonicRegression().fit(X, y) + names = iso.get_feature_names_out() + assert isinstance(names, np.ndarray) + assert names.dtype == object + assert_array_equal(["isotonicregression0"], names)
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex c0f705a8ceef7..aa1a71466fce0 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -314,6 +314,12 @@ Changelog\n `max_iter` and `tol`.\n :pr:`21341` by :user:`Arturo Amor <ArturoAmorQ>`.\n \n+:mod:`sklearn.isotonic`\n+.......................\n+\n+- |Enhancement| Adds :term:`get_feature_names_out` to `IsotonicRegression`.\n+ :pr:`22249` by `Thomas Fan`_.\n+\n :mod:`sklearn.linear_model`\n ...........................\n \n" } ]
1.01
49043fc769d0affc92e3641d2d5f8f8de2421611
[ "sklearn/tests/test_isotonic.py::test_isotonic_regression_oob_bad", "sklearn/tests/test_isotonic.py::test_make_unique_tolerance[float32]", "sklearn/tests/test_isotonic.py::test_isotonic_thresholds[True]", "sklearn/tests/test_isotonic.py::test_isotonic_sample_weight_parameter_default_value", "sklearn/tests/test_isotonic.py::test_isotonic_sample_weight", "sklearn/tests/test_isotonic.py::test_isotonic_regression_oob_raise", "sklearn/tests/test_isotonic.py::test_isotonic_regression_oob_nan", "sklearn/tests/test_isotonic.py::test_input_shape_validation", "sklearn/tests/test_isotonic.py::test_isotonic_regression_oob_clip", "sklearn/tests/test_isotonic.py::test_isotonic_regression_pickle", "sklearn/tests/test_isotonic.py::test_isotonic_regression_sample_weight_not_overwritten", "sklearn/tests/test_isotonic.py::test_isotonic_ymin_ymax", "sklearn/tests/test_isotonic.py::test_make_unique_dtype", "sklearn/tests/test_isotonic.py::test_isotonic_regression_auto_decreasing", "sklearn/tests/test_isotonic.py::test_isotonic_mismatched_dtype[float64]", "sklearn/tests/test_isotonic.py::test_isotonic_zero_weight_loop", "sklearn/tests/test_isotonic.py::test_isotonic_mismatched_dtype[int32]", "sklearn/tests/test_isotonic.py::test_isotonic_mismatched_dtype[float32]", "sklearn/tests/test_isotonic.py::test_isotonic_duplicate_min_entry", "sklearn/tests/test_isotonic.py::test_isotonic_min_max_boundaries", "sklearn/tests/test_isotonic.py::test_assert_raises_exceptions", "sklearn/tests/test_isotonic.py::test_isotonic_2darray_more_than_1_feature", "sklearn/tests/test_isotonic.py::test_check_ci_warn", "sklearn/tests/test_isotonic.py::test_isotonic_copy_before_fit", "sklearn/tests/test_isotonic.py::test_make_unique_tolerance[float64]", "sklearn/tests/test_isotonic.py::test_isotonic_mismatched_dtype[int64]", "sklearn/tests/test_isotonic.py::test_isotonic_regression", "sklearn/tests/test_isotonic.py::test_isotonic_regression_ties_secondary_", "sklearn/tests/test_isotonic.py::test_isotonic_regression_with_ties_in_differently_sized_groups", "sklearn/tests/test_isotonic.py::test_fast_predict", "sklearn/tests/test_isotonic.py::test_isotonic_thresholds[False]", "sklearn/tests/test_isotonic.py::test_isotonic_regression_ties_max", "sklearn/tests/test_isotonic.py::test_permutation_invariance", "sklearn/tests/test_isotonic.py::test_isotonic_dtype", "sklearn/tests/test_isotonic.py::test_isotonic_regression_reversed", "sklearn/tests/test_isotonic.py::test_isotonic_regression_ties_min", "sklearn/tests/test_isotonic.py::test_isotonic_make_unique_tolerance", "sklearn/tests/test_isotonic.py::test_isotonic_non_regression_inf_slope", "sklearn/tests/test_isotonic.py::test_isotonic_regression_oob_bad_after", "sklearn/tests/test_isotonic.py::test_isotonic_regression_auto_increasing" ]
[ "sklearn/tests/test_isotonic.py::test_get_feature_names_out[1d]", "sklearn/tests/test_isotonic.py::test_get_feature_names_out[2d]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex c0f705a8ceef7..aa1a71466fce0 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -314,6 +314,12 @@ Changelog\n `max_iter` and `tol`.\n :pr:`<PRID>` by :user:`<NAME>`.\n \n+:mod:`sklearn.isotonic`\n+.......................\n+\n+- |Enhancement| Adds :term:`get_feature_names_out` to `IsotonicRegression`.\n+ :pr:`<PRID>` by `<NAME>`_.\n+\n :mod:`sklearn.linear_model`\n ...........................\n \n" } ]
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index c0f705a8ceef7..aa1a71466fce0 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -314,6 +314,12 @@ Changelog `max_iter` and `tol`. :pr:`<PRID>` by :user:`<NAME>`. +:mod:`sklearn.isotonic` +....................... + +- |Enhancement| Adds :term:`get_feature_names_out` to `IsotonicRegression`. + :pr:`<PRID>` by `<NAME>`_. + :mod:`sklearn.linear_model` ...........................
scikit-learn/scikit-learn
scikit-learn__scikit-learn-19794
https://github.com/scikit-learn/scikit-learn/pull/19794
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 7ecffa9e18279..a18f14ee95b20 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -542,6 +542,26 @@ Changelog :class:`linear_model.ARDRegression` now preserve float32 dtype. :pr:`9087` by :user:`Arthur Imbert <Henley13>` and :pr:`22525` by :user:`Meekail Zain <micky774>`. +:mod:`sklearn.manifold` +....................... + +- |Feature| :class:`sklearn.manifold.Isomap` now supports radius-based + neighbors via the `radius` argument. + :pr:`19794` by :user:`Zhehao Liu <MaxwellLZH>`. + +- |Enhancement| :func:`manifold.spectral_embedding` and + :class:`manifold.SpectralEmbedding` supports `np.float32` dtype and will + preserve this dtype. + :pr:`21534` by :user:`Andrew Knyazev <lobpcg>`. + +- |Enhancement| Adds `get_feature_names_out` to :class:`manifold.Isomap` + and :class:`manifold.LocallyLinearEmbedding`. :pr:`22254` by `Thomas Fan`_. + +- |Fix| :func:`manifold.spectral_embedding` now uses Gaussian instead of + the previous uniform on [0, 1] random initial approximations to eigenvectors + in eigen_solvers `lobpcg` and `amg` to improve their numerical stability. + :pr:`21565` by :user:`Andrew Knyazev <lobpcg>`. + :mod:`sklearn.metrics` ...................... @@ -575,22 +595,6 @@ Changelog in the multiclass case when ``multiclass='ovr'`` which will return the score per class. :pr:`19158` by :user:`Nicki Skafte <SkafteNicki>`. -:mod:`sklearn.manifold` -....................... - -- |Enhancement| :func:`manifold.spectral_embedding` and - :class:`manifold.SpectralEmbedding` supports `np.float32` dtype and will - preserve this dtype. - :pr:`21534` by :user:`Andrew Knyazev <lobpcg>`. - -- |Enhancement| Adds `get_feature_names_out` to :class:`manifold.Isomap` - and :class:`manifold.LocallyLinearEmbedding`. :pr:`22254` by `Thomas Fan`_. - -- |Fix| :func:`manifold.spectral_embedding` now uses Gaussian instead of - the previous uniform on [0, 1] random initial approximations to eigenvectors - in eigen_solvers `lobpcg` and `amg` to improve their numerical stability. - :pr:`21565` by :user:`Andrew Knyazev <lobpcg>`. - :mod:`sklearn.model_selection` .............................. diff --git a/sklearn/manifold/_isomap.py b/sklearn/manifold/_isomap.py index c0300edb8c8bb..6e23da19ac694 100644 --- a/sklearn/manifold/_isomap.py +++ b/sklearn/manifold/_isomap.py @@ -5,6 +5,7 @@ import warnings import numpy as np + import scipy from scipy.sparse import issparse from scipy.sparse.csgraph import shortest_path @@ -12,6 +13,7 @@ from ..base import BaseEstimator, TransformerMixin, _ClassNamePrefixFeaturesOutMixin from ..neighbors import NearestNeighbors, kneighbors_graph +from ..neighbors import radius_neighbors_graph from ..utils.validation import check_is_fitted from ..decomposition import KernelPCA from ..preprocessing import KernelCenterer @@ -28,8 +30,15 @@ class Isomap(_ClassNamePrefixFeaturesOutMixin, TransformerMixin, BaseEstimator): Parameters ---------- - n_neighbors : int, default=5 - Number of neighbors to consider for each point. + n_neighbors : int or None, default=5 + Number of neighbors to consider for each point. If `n_neighbors` is an int, + then `radius` must be `None`. + + radius : float or None, default=None + Limiting distance of neighbors to return. If `radius` is a float, + then `n_neighbors` must be set to `None`. + + .. versionadded:: 1.1 n_components : int, default=2 Number of coordinates for the manifold. @@ -156,6 +165,7 @@ def __init__( self, *, n_neighbors=5, + radius=None, n_components=2, eigen_solver="auto", tol=0, @@ -168,6 +178,7 @@ def __init__( metric_params=None, ): self.n_neighbors = n_neighbors + self.radius = radius self.n_components = n_components self.eigen_solver = eigen_solver self.tol = tol @@ -180,8 +191,16 @@ def __init__( self.metric_params = metric_params def _fit_transform(self, X): + if self.n_neighbors is not None and self.radius is not None: + raise ValueError( + "Both n_neighbors and radius are provided. Use" + f" Isomap(radius={self.radius}, n_neighbors=None) if intended to use" + " radius-based neighbors" + ) + self.nbrs_ = NearestNeighbors( n_neighbors=self.n_neighbors, + radius=self.radius, algorithm=self.neighbors_algorithm, metric=self.metric, p=self.p, @@ -202,21 +221,32 @@ def _fit_transform(self, X): n_jobs=self.n_jobs, ) - kng = kneighbors_graph( - self.nbrs_, - self.n_neighbors, - metric=self.metric, - p=self.p, - metric_params=self.metric_params, - mode="distance", - n_jobs=self.n_jobs, - ) + if self.n_neighbors is not None: + nbg = kneighbors_graph( + self.nbrs_, + self.n_neighbors, + metric=self.metric, + p=self.p, + metric_params=self.metric_params, + mode="distance", + n_jobs=self.n_jobs, + ) + else: + nbg = radius_neighbors_graph( + self.nbrs_, + radius=self.radius, + metric=self.metric, + p=self.p, + metric_params=self.metric_params, + mode="distance", + n_jobs=self.n_jobs, + ) # Compute the number of connected components, and connect the different # components to be able to compute a shortest path between all pairs # of samples in the graph. # Similar fix to cluster._agglomerative._fix_connectivity. - n_connected_components, labels = connected_components(kng) + n_connected_components, labels = connected_components(nbg) if n_connected_components > 1: if self.metric == "precomputed" and issparse(X): raise RuntimeError( @@ -236,9 +266,9 @@ def _fit_transform(self, X): ) # use array validated by NearestNeighbors - kng = _fix_connected_components( + nbg = _fix_connected_components( X=self.nbrs_._fit_X, - graph=kng, + graph=nbg, n_connected_components=n_connected_components, component_labels=labels, mode="distance", @@ -249,9 +279,9 @@ def _fit_transform(self, X): if parse_version(scipy.__version__) < parse_version("1.3.2"): # make identical samples have a nonzero distance, to account for # issues in old scipy Floyd-Warshall implementation. - kng.data += 1e-15 + nbg.data += 1e-15 - self.dist_matrix_ = shortest_path(kng, method=self.path_method, directed=False) + self.dist_matrix_ = shortest_path(nbg, method=self.path_method, directed=False) G = self.dist_matrix_**2 G *= -0.5 @@ -349,7 +379,10 @@ def transform(self, X): X transformed in the new space. """ check_is_fitted(self) - distances, indices = self.nbrs_.kneighbors(X, return_distance=True) + if self.n_neighbors is not None: + distances, indices = self.nbrs_.kneighbors(X, return_distance=True) + else: + distances, indices = self.nbrs_.radius_neighbors(X, return_distance=True) # Create the graph of shortest distances from X to # training data via the nearest neighbors of X.
diff --git a/sklearn/manifold/tests/test_isomap.py b/sklearn/manifold/tests/test_isomap.py index 515bc4e46c9d7..73365b08a5cfb 100644 --- a/sklearn/manifold/tests/test_isomap.py +++ b/sklearn/manifold/tests/test_isomap.py @@ -1,5 +1,6 @@ from itertools import product import numpy as np +import math from numpy.testing import ( assert_almost_equal, assert_array_almost_equal, @@ -14,6 +15,7 @@ from sklearn import preprocessing from sklearn.datasets import make_blobs from sklearn.metrics.pairwise import pairwise_distances +from sklearn.utils._testing import assert_allclose, assert_allclose_dense_sparse from scipy.sparse import rand as sparse_rand @@ -21,51 +23,63 @@ path_methods = ["auto", "FW", "D"] -def test_isomap_simple_grid(): - # Isomap should preserve distances when all neighbors are used - N_per_side = 5 - Npts = N_per_side**2 - n_neighbors = Npts - 1 - +def create_sample_data(n_pts=25, add_noise=False): # grid of equidistant points in 2D, n_components = n_dim - X = np.array(list(product(range(N_per_side), repeat=2))) + n_per_side = int(math.sqrt(n_pts)) + X = np.array(list(product(range(n_per_side), repeat=2))) + if add_noise: + # add noise in a third dimension + rng = np.random.RandomState(0) + noise = 0.1 * rng.randn(n_pts, 1) + X = np.concatenate((X, noise), 1) + return X + + [email protected]("n_neighbors, radius", [(24, None), (None, np.inf)]) +def test_isomap_simple_grid(n_neighbors, radius): + # Isomap should preserve distances when all neighbors are used + n_pts = 25 + X = create_sample_data(n_pts=n_pts, add_noise=False) # distances from each point to all others - G = neighbors.kneighbors_graph(X, n_neighbors, mode="distance").toarray() + if n_neighbors is not None: + G = neighbors.kneighbors_graph(X, n_neighbors, mode="distance") + else: + G = neighbors.radius_neighbors_graph(X, radius, mode="distance") for eigen_solver in eigen_solvers: for path_method in path_methods: clf = manifold.Isomap( n_neighbors=n_neighbors, + radius=radius, n_components=2, eigen_solver=eigen_solver, path_method=path_method, ) clf.fit(X) - G_iso = neighbors.kneighbors_graph( - clf.embedding_, n_neighbors, mode="distance" - ).toarray() - assert_array_almost_equal(G, G_iso) + if n_neighbors is not None: + G_iso = neighbors.kneighbors_graph( + clf.embedding_, n_neighbors, mode="distance" + ) + else: + G_iso = neighbors.radius_neighbors_graph( + clf.embedding_, radius, mode="distance" + ) + assert_allclose_dense_sparse(G, G_iso) -def test_isomap_reconstruction_error(): [email protected]("n_neighbors, radius", [(24, None), (None, np.inf)]) +def test_isomap_reconstruction_error(n_neighbors, radius): # Same setup as in test_isomap_simple_grid, with an added dimension - N_per_side = 5 - Npts = N_per_side**2 - n_neighbors = Npts - 1 - - # grid of equidistant points in 2D, n_components = n_dim - X = np.array(list(product(range(N_per_side), repeat=2))) - - # add noise in a third dimension - rng = np.random.RandomState(0) - noise = 0.1 * rng.randn(Npts, 1) - X = np.concatenate((X, noise), 1) + n_pts = 25 + X = create_sample_data(n_pts=n_pts, add_noise=True) # compute input kernel - G = neighbors.kneighbors_graph(X, n_neighbors, mode="distance").toarray() - + if n_neighbors is not None: + G = neighbors.kneighbors_graph(X, n_neighbors, mode="distance").toarray() + else: + G = neighbors.radius_neighbors_graph(X, radius, mode="distance").toarray() centerer = preprocessing.KernelCenterer() K = centerer.fit_transform(-0.5 * G**2) @@ -73,6 +87,7 @@ def test_isomap_reconstruction_error(): for path_method in path_methods: clf = manifold.Isomap( n_neighbors=n_neighbors, + radius=radius, n_components=2, eigen_solver=eigen_solver, path_method=path_method, @@ -80,18 +95,24 @@ def test_isomap_reconstruction_error(): clf.fit(X) # compute output kernel - G_iso = neighbors.kneighbors_graph( - clf.embedding_, n_neighbors, mode="distance" - ).toarray() - + if n_neighbors is not None: + G_iso = neighbors.kneighbors_graph( + clf.embedding_, n_neighbors, mode="distance" + ) + else: + G_iso = neighbors.radius_neighbors_graph( + clf.embedding_, radius, mode="distance" + ) + G_iso = G_iso.toarray() K_iso = centerer.fit_transform(-0.5 * G_iso**2) # make sure error agrees - reconstruction_error = np.linalg.norm(K - K_iso) / Npts + reconstruction_error = np.linalg.norm(K - K_iso) / n_pts assert_almost_equal(reconstruction_error, clf.reconstruction_error()) -def test_transform(): [email protected]("n_neighbors, radius", [(2, None), (None, 0.5)]) +def test_transform(n_neighbors, radius): n_samples = 200 n_components = 10 noise_scale = 0.01 @@ -100,7 +121,9 @@ def test_transform(): X, y = datasets.make_s_curve(n_samples, random_state=0) # Compute isomap embedding - iso = manifold.Isomap(n_components=n_components) + iso = manifold.Isomap( + n_components=n_components, n_neighbors=n_neighbors, radius=radius + ) X_iso = iso.fit_transform(X) # Re-embed a noisy version of the points @@ -112,13 +135,17 @@ def test_transform(): assert np.sqrt(np.mean((X_iso - X_iso2) ** 2)) < 2 * noise_scale -def test_pipeline(): [email protected]("n_neighbors, radius", [(2, None), (None, 10.0)]) +def test_pipeline(n_neighbors, radius): # check that Isomap works fine as a transformer in a Pipeline # only checks that no error is raised. # TODO check that it actually does something useful X, y = datasets.make_blobs(random_state=0) clf = pipeline.Pipeline( - [("isomap", manifold.Isomap()), ("clf", neighbors.KNeighborsClassifier())] + [ + ("isomap", manifold.Isomap(n_neighbors=n_neighbors, radius=radius)), + ("clf", neighbors.KNeighborsClassifier()), + ] ) clf.fit(X, y) assert 0.9 < clf.score(X, y) @@ -204,6 +231,34 @@ def test_sparse_input(): clf.fit(X) +def test_isomap_fit_precomputed_radius_graph(): + # Isomap.fit_transform must yield similar result when using + # a precomputed distance matrix. + + X, y = datasets.make_s_curve(200, random_state=0) + radius = 10 + + g = neighbors.radius_neighbors_graph(X, radius=radius, mode="distance") + isomap = manifold.Isomap(n_neighbors=None, radius=radius, metric="precomputed") + isomap.fit(g) + precomputed_result = isomap.embedding_ + + isomap = manifold.Isomap(n_neighbors=None, radius=radius, metric="minkowski") + result = isomap.fit_transform(X) + assert_allclose(precomputed_result, result) + + +def test_isomap_raise_error_when_neighbor_and_radius_both_set(): + # Isomap.fit_transform must raise a ValueError if + # radius and n_neighbors are provided. + + X, _ = datasets.load_digits(return_X_y=True) + isomap = manifold.Isomap(n_neighbors=3, radius=5.5) + msg = "Both n_neighbors and radius are provided" + with pytest.raises(ValueError, match=msg): + isomap.fit_transform(X) + + def test_multiple_connected_components(): # Test that a warning is raised when the graph has multiple components X = np.array([0, 1, 2, 5, 6, 7])[:, None]
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 7ecffa9e18279..a18f14ee95b20 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -542,6 +542,26 @@ Changelog\n :class:`linear_model.ARDRegression` now preserve float32 dtype. :pr:`9087` by\n :user:`Arthur Imbert <Henley13>` and :pr:`22525` by :user:`Meekail Zain <micky774>`.\n \n+:mod:`sklearn.manifold`\n+.......................\n+\n+- |Feature| :class:`sklearn.manifold.Isomap` now supports radius-based\n+ neighbors via the `radius` argument.\n+ :pr:`19794` by :user:`Zhehao Liu <MaxwellLZH>`.\n+\n+- |Enhancement| :func:`manifold.spectral_embedding` and\n+ :class:`manifold.SpectralEmbedding` supports `np.float32` dtype and will\n+ preserve this dtype.\n+ :pr:`21534` by :user:`Andrew Knyazev <lobpcg>`.\n+\n+- |Enhancement| Adds `get_feature_names_out` to :class:`manifold.Isomap`\n+ and :class:`manifold.LocallyLinearEmbedding`. :pr:`22254` by `Thomas Fan`_.\n+\n+- |Fix| :func:`manifold.spectral_embedding` now uses Gaussian instead of\n+ the previous uniform on [0, 1] random initial approximations to eigenvectors\n+ in eigen_solvers `lobpcg` and `amg` to improve their numerical stability.\n+ :pr:`21565` by :user:`Andrew Knyazev <lobpcg>`.\n+\n :mod:`sklearn.metrics`\n ......................\n \n@@ -575,22 +595,6 @@ Changelog\n in the multiclass case when ``multiclass='ovr'`` which will return the score\n per class. :pr:`19158` by :user:`Nicki Skafte <SkafteNicki>`.\n \n-:mod:`sklearn.manifold`\n-.......................\n-\n-- |Enhancement| :func:`manifold.spectral_embedding` and\n- :class:`manifold.SpectralEmbedding` supports `np.float32` dtype and will\n- preserve this dtype.\n- :pr:`21534` by :user:`Andrew Knyazev <lobpcg>`.\n-\n-- |Enhancement| Adds `get_feature_names_out` to :class:`manifold.Isomap`\n- and :class:`manifold.LocallyLinearEmbedding`. :pr:`22254` by `Thomas Fan`_.\n-\n-- |Fix| :func:`manifold.spectral_embedding` now uses Gaussian instead of\n- the previous uniform on [0, 1] random initial approximations to eigenvectors\n- in eigen_solvers `lobpcg` and `amg` to improve their numerical stability.\n- :pr:`21565` by :user:`Andrew Knyazev <lobpcg>`.\n-\n :mod:`sklearn.model_selection`\n ..............................\n \n" } ]
1.01
1c94c0b0be3b9146aae41376f3f4ef3853e0ca97
[ "sklearn/manifold/tests/test_isomap.py::test_sparse_input", "sklearn/manifold/tests/test_isomap.py::test_isomap_clone_bug", "sklearn/manifold/tests/test_isomap.py::test_different_metric", "sklearn/manifold/tests/test_isomap.py::test_multiple_connected_components", "sklearn/manifold/tests/test_isomap.py::test_multiple_connected_components_metric_precomputed", "sklearn/manifold/tests/test_isomap.py::test_pipeline_with_nearest_neighbors_transformer", "sklearn/manifold/tests/test_isomap.py::test_get_feature_names_out" ]
[ "sklearn/manifold/tests/test_isomap.py::test_transform[None-0.5]", "sklearn/manifold/tests/test_isomap.py::test_isomap_reconstruction_error[None-inf]", "sklearn/manifold/tests/test_isomap.py::test_pipeline[None-10.0]", "sklearn/manifold/tests/test_isomap.py::test_isomap_simple_grid[None-inf]", "sklearn/manifold/tests/test_isomap.py::test_isomap_fit_precomputed_radius_graph", "sklearn/manifold/tests/test_isomap.py::test_isomap_raise_error_when_neighbor_and_radius_both_set", "sklearn/manifold/tests/test_isomap.py::test_transform[2-None]", "sklearn/manifold/tests/test_isomap.py::test_isomap_reconstruction_error[24-None]", "sklearn/manifold/tests/test_isomap.py::test_pipeline[2-None]", "sklearn/manifold/tests/test_isomap.py::test_isomap_simple_grid[24-None]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 7ecffa9e18279..a18f14ee95b20 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -542,6 +542,26 @@ Changelog\n :class:`linear_model.ARDRegression` now preserve float32 dtype. :pr:`<PRID>` by\n :user:`<NAME>` and :pr:`<PRID>` by :user:`<NAME>`.\n \n+:mod:`sklearn.manifold`\n+.......................\n+\n+- |Feature| :class:`sklearn.manifold.Isomap` now supports radius-based\n+ neighbors via the `radius` argument.\n+ :pr:`<PRID>` by :user:`<NAME>`.\n+\n+- |Enhancement| :func:`manifold.spectral_embedding` and\n+ :class:`manifold.SpectralEmbedding` supports `np.float32` dtype and will\n+ preserve this dtype.\n+ :pr:`<PRID>` by :user:`<NAME>`.\n+\n+- |Enhancement| Adds `get_feature_names_out` to :class:`manifold.Isomap`\n+ and :class:`manifold.LocallyLinearEmbedding`. :pr:`<PRID>` by `<NAME>`_.\n+\n+- |Fix| :func:`manifold.spectral_embedding` now uses Gaussian instead of\n+ the previous uniform on [0, 1] random initial approximations to eigenvectors\n+ in eigen_solvers `lobpcg` and `amg` to improve their numerical stability.\n+ :pr:`<PRID>` by :user:`<NAME>`.\n+\n :mod:`sklearn.metrics`\n ......................\n \n@@ -575,22 +595,6 @@ Changelog\n in the multiclass case when ``multiclass='ovr'`` which will return the score\n per class. :pr:`<PRID>` by :user:`<NAME>`.\n \n-:mod:`sklearn.manifold`\n-.......................\n-\n-- |Enhancement| :func:`manifold.spectral_embedding` and\n- :class:`manifold.SpectralEmbedding` supports `np.float32` dtype and will\n- preserve this dtype.\n- :pr:`<PRID>` by :user:`<NAME>`.\n-\n-- |Enhancement| Adds `get_feature_names_out` to :class:`manifold.Isomap`\n- and :class:`manifold.LocallyLinearEmbedding`. :pr:`<PRID>` by `<NAME>`_.\n-\n-- |Fix| :func:`manifold.spectral_embedding` now uses Gaussian instead of\n- the previous uniform on [0, 1] random initial approximations to eigenvectors\n- in eigen_solvers `lobpcg` and `amg` to improve their numerical stability.\n- :pr:`<PRID>` by :user:`<NAME>`.\n-\n :mod:`sklearn.model_selection`\n ..............................\n \n" } ]
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 7ecffa9e18279..a18f14ee95b20 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -542,6 +542,26 @@ Changelog :class:`linear_model.ARDRegression` now preserve float32 dtype. :pr:`<PRID>` by :user:`<NAME>` and :pr:`<PRID>` by :user:`<NAME>`. +:mod:`sklearn.manifold` +....................... + +- |Feature| :class:`sklearn.manifold.Isomap` now supports radius-based + neighbors via the `radius` argument. + :pr:`<PRID>` by :user:`<NAME>`. + +- |Enhancement| :func:`manifold.spectral_embedding` and + :class:`manifold.SpectralEmbedding` supports `np.float32` dtype and will + preserve this dtype. + :pr:`<PRID>` by :user:`<NAME>`. + +- |Enhancement| Adds `get_feature_names_out` to :class:`manifold.Isomap` + and :class:`manifold.LocallyLinearEmbedding`. :pr:`<PRID>` by `<NAME>`_. + +- |Fix| :func:`manifold.spectral_embedding` now uses Gaussian instead of + the previous uniform on [0, 1] random initial approximations to eigenvectors + in eigen_solvers `lobpcg` and `amg` to improve their numerical stability. + :pr:`<PRID>` by :user:`<NAME>`. + :mod:`sklearn.metrics` ...................... @@ -575,22 +595,6 @@ Changelog in the multiclass case when ``multiclass='ovr'`` which will return the score per class. :pr:`<PRID>` by :user:`<NAME>`. -:mod:`sklearn.manifold` -....................... - -- |Enhancement| :func:`manifold.spectral_embedding` and - :class:`manifold.SpectralEmbedding` supports `np.float32` dtype and will - preserve this dtype. - :pr:`<PRID>` by :user:`<NAME>`. - -- |Enhancement| Adds `get_feature_names_out` to :class:`manifold.Isomap` - and :class:`manifold.LocallyLinearEmbedding`. :pr:`<PRID>` by `<NAME>`_. - -- |Fix| :func:`manifold.spectral_embedding` now uses Gaussian instead of - the previous uniform on [0, 1] random initial approximations to eigenvectors - in eigen_solvers `lobpcg` and `amg` to improve their numerical stability. - :pr:`<PRID>` by :user:`<NAME>`. - :mod:`sklearn.model_selection` ..............................
scikit-learn/scikit-learn
scikit-learn__scikit-learn-21606
https://github.com/scikit-learn/scikit-learn/pull/21606
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index b9651a1e1b6f8..329f87813a389 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -187,6 +187,11 @@ Changelog multilabel classification. :pr:`19689` by :user:`Guillaume Lemaitre <glemaitre>`. +- |Enhancement| :class:`linear_model.RidgeCV` and + :class:`linear_model.RidgeClassifierCV` now raise consistent error message + when passed invalid values for `alphas`. + :pr:`21606` by :user:`Arturo Amor <ArturoAmorQ>`. + - |Enhancement| :class:`linear_model.Ridge` and :class:`linear_model.RidgeClassifier` now raise consistent error message when passed invalid values for `alpha`, `max_iter` and `tol`. diff --git a/sklearn/linear_model/_ridge.py b/sklearn/linear_model/_ridge.py index 09ef46ffc7ebe..1426201a893aa 100644 --- a/sklearn/linear_model/_ridge.py +++ b/sklearn/linear_model/_ridge.py @@ -10,6 +10,7 @@ from abc import ABCMeta, abstractmethod +from functools import partial import warnings import numpy as np @@ -1864,12 +1865,6 @@ def fit(self, X, y, sample_weight=None): self.alphas = np.asarray(self.alphas) - if np.any(self.alphas <= 0): - raise ValueError( - "alphas must be strictly positive. Got {} containing some " - "negative or null value instead.".format(self.alphas) - ) - X, y, X_offset, y_offset, X_scale = LinearModel._preprocess_data( X, y, @@ -2038,9 +2033,30 @@ def fit(self, X, y, sample_weight=None): the validation score. """ cv = self.cv + + check_scalar_alpha = partial( + check_scalar, + target_type=numbers.Real, + min_val=0.0, + include_boundaries="neither", + ) + + if isinstance(self.alphas, (np.ndarray, list, tuple)): + n_alphas = 1 if np.ndim(self.alphas) == 0 else len(self.alphas) + if n_alphas != 1: + for index, alpha in enumerate(self.alphas): + alpha = check_scalar_alpha(alpha, f"alphas[{index}]") + else: + self.alphas[0] = check_scalar_alpha(self.alphas[0], "alphas") + else: + # check for single non-iterable item + self.alphas = check_scalar_alpha(self.alphas, "alphas") + + alphas = np.asarray(self.alphas) + if cv is None: estimator = _RidgeGCV( - self.alphas, + alphas, fit_intercept=self.fit_intercept, normalize=self.normalize, scoring=self.scoring, @@ -2059,7 +2075,8 @@ def fit(self, X, y, sample_weight=None): raise ValueError("cv!=None and store_cv_values=True are incompatible") if self.alpha_per_target: raise ValueError("cv!=None and alpha_per_target=True are incompatible") - parameters = {"alpha": self.alphas} + + parameters = {"alpha": alphas} solver = "sparse_cg" if sparse.issparse(X) else "auto" model = RidgeClassifier if is_classifier(self) else Ridge gs = GridSearchCV(
diff --git a/sklearn/linear_model/tests/test_ridge.py b/sklearn/linear_model/tests/test_ridge.py index 1160e2db57fc6..975d16df06f12 100644 --- a/sklearn/linear_model/tests/test_ridge.py +++ b/sklearn/linear_model/tests/test_ridge.py @@ -1270,19 +1270,51 @@ def test_ridgecv_int_alphas(): ridge.fit(X, y) -def test_ridgecv_negative_alphas(): - X = np.array([[-1.0, -1.0], [-1.0, 0], [-0.8, -1.0], [1.0, 1.0], [1.0, 0.0]]) - y = [1, 1, 1, -1, -1] [email protected]("Estimator", [RidgeCV, RidgeClassifierCV]) [email protected]( + "params, err_type, err_msg", + [ + ({"alphas": (1, -1, -100)}, ValueError, r"alphas\[1\] == -1, must be > 0.0"), + ( + {"alphas": (-0.1, -1.0, -10.0)}, + ValueError, + r"alphas\[0\] == -0.1, must be > 0.0", + ), + ( + {"alphas": (1, 1.0, "1")}, + TypeError, + r"alphas\[2\] must be an instance of <class 'numbers.Real'>, not <class" + r" 'str'>", + ), + ], +) +def test_ridgecv_alphas_validation(Estimator, params, err_type, err_msg): + """Check the `alphas` validation in RidgeCV and RidgeClassifierCV.""" - # Negative integers - ridge = RidgeCV(alphas=(-1, -10, -100)) - with pytest.raises(ValueError, match="alphas must be strictly positive"): - ridge.fit(X, y) + n_samples, n_features = 5, 5 + X = rng.randn(n_samples, n_features) + y = rng.randint(0, 2, n_samples) - # Negative floats - ridge = RidgeCV(alphas=(-0.1, -1.0, -10.0)) - with pytest.raises(ValueError, match="alphas must be strictly positive"): - ridge.fit(X, y) + with pytest.raises(err_type, match=err_msg): + Estimator(**params).fit(X, y) + + [email protected]("Estimator", [RidgeCV, RidgeClassifierCV]) +def test_ridgecv_alphas_scalar(Estimator): + """Check the case when `alphas` is a scalar. + This case was supported in the past when `alphas` where converted + into array in `__init__`. + We add this test to ensure backward compatibility. + """ + + n_samples, n_features = 5, 5 + X = rng.randn(n_samples, n_features) + if Estimator is RidgeCV: + y = rng.randn(n_samples) + else: + y = rng.randint(0, 2, n_samples) + + Estimator(alphas=1).fit(X, y) def test_raises_value_error_if_solver_not_supported():
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex b9651a1e1b6f8..329f87813a389 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -187,6 +187,11 @@ Changelog\n multilabel classification.\n :pr:`19689` by :user:`Guillaume Lemaitre <glemaitre>`.\n \n+- |Enhancement| :class:`linear_model.RidgeCV` and\n+ :class:`linear_model.RidgeClassifierCV` now raise consistent error message\n+ when passed invalid values for `alphas`.\n+ :pr:`21606` by :user:`Arturo Amor <ArturoAmorQ>`.\n+\n - |Enhancement| :class:`linear_model.Ridge` and :class:`linear_model.RidgeClassifier`\n now raise consistent error message when passed invalid values for `alpha`,\n `max_iter` and `tol`.\n" } ]
1.01
cacc034bba73859390a005445d634b1aa3ca7fe1
[ "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[True-shape4]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[0.001-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[svd-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_alphas_conversion[RidgeClassifierCV]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.001-True-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_int_alphas", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape0-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weights", "sklearn/linear_model/tests/test_ridge.py::test_ridge_params_validation[params1-TypeError-alpha must be an instance of <class 'numbers.Real'>, not <class 'str'>]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[auto-svd-eigen-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge[sag]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[SPARSE_FILTER-None-None]", "sklearn/linear_model/tests/test_ridge.py::test_X_CenterStackOp[n_col1]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-csr_matrix-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_best_score[None-ridge1-make_classification]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sag_with_X_fortran", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.01-False-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-csr_matrix-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-csr_matrix-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape1-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-array-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_error[True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_class_weight_vs_sample_weight[RidgeClassifier]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.1-False-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[auto-svd-eigen-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape0-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[svd-svd-svd-True]", "sklearn/linear_model/tests/test_ridge.py::test_X_CenterStackOp[n_col2]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[False-shape1]", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_ridge_classifiers]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[False-shape4]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[SPARSE_FILTER-None-_accuracy_callable]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_error[1]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-8-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_store_cv_values[_mean_squared_error_callable]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape1-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-20-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-csr_matrix-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-csr_matrix-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_custom_scoring[SPARSE_FILTER-cv1]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[True-shape0]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_error[5]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-csr_matrix-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-array-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape1-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-csr_matrix-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-8-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-20-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape1-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_params_validation[params0-ValueError-alpha == -1, must be >= 0.0]", "sklearn/linear_model/tests/test_ridge.py::test_lbfgs_solver_consistency[0.01]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[lsqr-True]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[lsqr]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[lbfgs-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-8-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_alphas_scalar[RidgeClassifierCV]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.01-True-auto]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape0-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-8-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape1-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-csr_matrix-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_cv_values_not_stored[ridge1-make_classification]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[0.01-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-array-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[False-shape1]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape1-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_primal_dual_relationship", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_cv_store_cv_values[None]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[None-svd-eigen-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-20-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_custom_scoring[DENSE_FILTER-None]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_custom_scoring[SPARSE_FILTER-None]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-array-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape0-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape0-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[DENSE_FILTER-cv1-None]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-csr_matrix-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-8-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape0-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.1-True-auto]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[cholesky-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-csr_matrix-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[True-shape1]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_error_test[sparse_cg]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-8-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_ridge_loo]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[False-shape0]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_error[bad]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.1-False-auto]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_fit_intercept_sparse_error[saga]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[False-shape2]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-csr_matrix-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_X_CenterStackOp[n_col0]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_params_validation[params5-TypeError-tol must be an instance of <class 'numbers.Real'>, not <class 'str'>]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_ridge_cv_normalize]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape0-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[True-shape3]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[False-shape2]", "sklearn/linear_model/tests/test_ridge.py::test_ridge[sparse_cg]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-csr_matrix-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-csr_matrix-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-csr_matrix-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_shapes", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-array-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[DENSE_FILTER-None-accuracy]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_vs_lstsq", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape0-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[False-shape0]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-8-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.1-True-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_store_cv_values[neg_mean_squared_error]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[1.0-True-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-8-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[1.0-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_raises_value_error_if_solver_not_supported", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-array-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-csr_matrix-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape1-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-array-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-array-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape1-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-array-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_best_score[3-ridge0-make_regression]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape0-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_sample_weight", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[True-shape4]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[DENSE_FILTER-None-_accuracy_callable]", "sklearn/linear_model/tests/test_ridge.py::test_sparse_design_with_sample_weights", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-array-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-20-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape1-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[SPARSE_FILTER-cv1-_accuracy_callable]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_alphas_conversion[RidgeCV]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-array-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.001-False-auto]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[sparse_cg]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_class_weight_vs_sample_weight[RidgeClassifierCV]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[DENSE_FILTER-cv1-accuracy]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.001-False-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[True-shape2]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[0.1-True]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[eigen-eigen-eigen-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match_cholesky", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-array-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[1.0-False-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.01-True-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[DENSE_FILTER-None-None]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape1-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[False-shape4]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-20-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-array-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape1-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape1-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-csr_matrix-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape1-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_ridge_cv]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.001-True-auto]", "sklearn/linear_model/tests/test_ridge.py::test_positive_ridge_loss[0.1]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-array-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-20-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_best_score[3-ridge1-make_classification]", "sklearn/linear_model/tests/test_ridge.py::test_ridge[cholesky]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape0-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape0-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape0-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-8-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_individual_penalties", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape0-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_lbfgs_solver_consistency[0.1]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-20-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_error_test[sag]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_sample_weights", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_sparse_cg_max_iter", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-array-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-cholesky]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_fit_intercept_sparse_error[svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_cv_values_not_stored[ridge0-make_regression]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sparse_svd", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-20-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_params_validation[params2-ValueError-max_iter == 0, must be >= 1.]", "sklearn/linear_model/tests/test_ridge.py::test_positive_ridge_loss[0.001]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[False-shape3]", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_ridge_diabetes]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_params_validation[params3-TypeError-max_iter must be an instance of <class 'numbers.Integral'>, not <class 'str'>]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[SPARSE_FILTER-None-accuracy]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-8-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_lbfgs_solver_error", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-array-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-20-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-csr_matrix-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-array-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-8-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-20-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridgeclassifier_multilabel[RidgeClassifierCV-params1]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[True-shape0]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[True-shape3]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-array-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[DENSE_FILTER-cv1-_accuracy_callable]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-20-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-array-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_fit_intercept_sparse_error[lsqr]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-8-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_tolerance]", "sklearn/linear_model/tests/test_ridge.py::test_class_weights", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape1-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-array-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-array-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_error_test[cholesky]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape1-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridgeclassifier_multilabel[RidgeClassifier-params0]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_alphas_scalar[RidgeCV]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_error_test[saga]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_loo_cv_asym_scoring", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[saga]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-csr_matrix-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-20-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_singular", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape1-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-20-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-csr_matrix-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_positive_ridge_loss[0.01]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-array-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape0-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_store_cv_values[None]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape0-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape0-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape0-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_intercept", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape1-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[1.0-True-auto]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[SPARSE_FILTER-cv1-accuracy]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[cholesky]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[0.001-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_fit_intercept_sparse_error[cholesky]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_error_test[lsqr]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape0-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[1.0-False-auto]", "sklearn/linear_model/tests/test_ridge.py::test_positive_ridge_loss[1.0]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-8-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_cv_store_cv_values[accuracy]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[svd-svd-svd-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape0-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[svd-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-8-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-array-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape1-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-sag]", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_multi_ridge_diabetes]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-array-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape1-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-csr_matrix-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape1-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-csr_matrix-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridgeclassifier_multilabel[RidgeClassifierCV-params2]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[True-shape2]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_error[gcv]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-20-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[eigen-eigen-eigen-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-array-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[lbfgs-False]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[True-shape1]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape0-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[sag]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-csr_matrix-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-csr_matrix-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[None-svd-eigen-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[0.1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_cv_individual_penalties", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-csr_matrix-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-saga]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-array-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape1-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge[svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape1-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape1-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-csr_matrix-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-lsqr]", "sklearn/linear_model/tests/test_ridge.py::test_lbfgs_solver_consistency[1.0]", "sklearn/linear_model/tests/test_ridge.py::test_n_iter", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[SPARSE_FILTER-cv1-None]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape0-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-csr_matrix-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_error_test[svd]", "sklearn/linear_model/tests/test_ridge.py::test_raises_value_error_if_sample_weights_greater_than_1d", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-csr_matrix-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-20-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-8-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-8-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape0-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_convergence_fail", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-array-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-20-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_toy_ridge_object", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[1.0-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape0-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape1-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_lbfgs_solver_consistency[0.001]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[0.01-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_params_validation[params4-ValueError-tol == -1.0, must be >= 0.]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.01-False-auto]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-array-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape0-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_custom_scoring[DENSE_FILTER-cv1]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[False-shape3]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_class_weights_cv", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-sparse_cg]", "sklearn/linear_model/tests/test_ridge.py::test_ridge[lsqr]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_best_score[None-ridge0-make_regression]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-csr_matrix-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_cv_store_cv_values[_accuracy_callable]" ]
[ "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_alphas_validation[params2-TypeError-alphas\\\\[2\\\\] must be an instance of <class 'numbers.Real'>, not <class 'str'>-RidgeCV]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_alphas_validation[params0-ValueError-alphas\\\\[1\\\\] == -1, must be > 0.0-RidgeClassifierCV]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_alphas_validation[params2-TypeError-alphas\\\\[2\\\\] must be an instance of <class 'numbers.Real'>, not <class 'str'>-RidgeClassifierCV]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_alphas_validation[params0-ValueError-alphas\\\\[1\\\\] == -1, must be > 0.0-RidgeCV]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_alphas_validation[params1-ValueError-alphas\\\\[0\\\\] == -0.1, must be > 0.0-RidgeCV]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_alphas_validation[params1-ValueError-alphas\\\\[0\\\\] == -0.1, must be > 0.0-RidgeClassifierCV]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex b9651a1e1b6f8..329f87813a389 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -187,6 +187,11 @@ Changelog\n multilabel classification.\n :pr:`<PRID>` by :user:`<NAME>`.\n \n+- |Enhancement| :class:`linear_model.RidgeCV` and\n+ :class:`linear_model.RidgeClassifierCV` now raise consistent error message\n+ when passed invalid values for `alphas`.\n+ :pr:`<PRID>` by :user:`<NAME>`.\n+\n - |Enhancement| :class:`linear_model.Ridge` and :class:`linear_model.RidgeClassifier`\n now raise consistent error message when passed invalid values for `alpha`,\n `max_iter` and `tol`.\n" } ]
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index b9651a1e1b6f8..329f87813a389 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -187,6 +187,11 @@ Changelog multilabel classification. :pr:`<PRID>` by :user:`<NAME>`. +- |Enhancement| :class:`linear_model.RidgeCV` and + :class:`linear_model.RidgeClassifierCV` now raise consistent error message + when passed invalid values for `alphas`. + :pr:`<PRID>` by :user:`<NAME>`. + - |Enhancement| :class:`linear_model.Ridge` and :class:`linear_model.RidgeClassifier` now raise consistent error message when passed invalid values for `alpha`, `max_iter` and `tol`.
scikit-learn/scikit-learn
scikit-learn__scikit-learn-21341
https://github.com/scikit-learn/scikit-learn/pull/21341
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index e2ff5bc76fce2..b9651a1e1b6f8 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -187,6 +187,11 @@ Changelog multilabel classification. :pr:`19689` by :user:`Guillaume Lemaitre <glemaitre>`. +- |Enhancement| :class:`linear_model.Ridge` and :class:`linear_model.RidgeClassifier` + now raise consistent error message when passed invalid values for `alpha`, + `max_iter` and `tol`. + :pr:`21341` by :user:`Arturo Amor <ArturoAmorQ>`. + :mod:`sklearn.linear_model` ........................... diff --git a/sklearn/linear_model/_ridge.py b/sklearn/linear_model/_ridge.py index 1a501e8404f62..09ef46ffc7ebe 100644 --- a/sklearn/linear_model/_ridge.py +++ b/sklearn/linear_model/_ridge.py @@ -13,6 +13,7 @@ import warnings import numpy as np +import numbers from scipy import linalg from scipy import sparse from scipy import optimize @@ -26,6 +27,7 @@ from ..utils.extmath import row_norms from ..utils import check_array from ..utils import check_consistent_length +from ..utils import check_scalar from ..utils import compute_sample_weight from ..utils import column_or_1d from ..utils.validation import check_is_fitted @@ -557,6 +559,17 @@ def _ridge_regression( # we implement sample_weight via a simple rescaling. X, y = _rescale_data(X, y, sample_weight) + # Some callers of this method might pass alpha as single + # element array which already has been validated. + if alpha is not None and not isinstance(alpha, (np.ndarray, tuple)): + alpha = check_scalar( + alpha, + "alpha", + target_type=numbers.Real, + min_val=0.0, + include_boundaries="left", + ) + # There should be either 1 or n_targets penalties alpha = np.asarray(alpha, dtype=X.dtype).ravel() if alpha.size not in [1, n_targets]: @@ -742,6 +755,13 @@ def fit(self, X, y, sample_weight=None): if sample_weight is not None: sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype) + if self.max_iter is not None: + self.max_iter = check_scalar( + self.max_iter, "max_iter", target_type=numbers.Integral, min_val=1 + ) + + self.tol = check_scalar(self.tol, "tol", target_type=numbers.Real, min_val=0.0) + # when X is sparse we only remove offset from y X, y, X_offset, y_offset, X_scale = self._preprocess_data( X,
diff --git a/sklearn/linear_model/tests/test_ridge.py b/sklearn/linear_model/tests/test_ridge.py index 58d2804d89aca..1160e2db57fc6 100644 --- a/sklearn/linear_model/tests/test_ridge.py +++ b/sklearn/linear_model/tests/test_ridge.py @@ -335,6 +335,42 @@ def test_ridge_individual_penalties(): ridge.fit(X, y) [email protected]( + "params, err_type, err_msg", + [ + ({"alpha": -1}, ValueError, "alpha == -1, must be >= 0.0"), + ( + {"alpha": "1"}, + TypeError, + "alpha must be an instance of <class 'numbers.Real'>, not <class 'str'>", + ), + ({"max_iter": 0}, ValueError, "max_iter == 0, must be >= 1."), + ( + {"max_iter": "1"}, + TypeError, + "max_iter must be an instance of <class 'numbers.Integral'>, not <class" + " 'str'>", + ), + ({"tol": -1.0}, ValueError, "tol == -1.0, must be >= 0."), + ( + {"tol": "1"}, + TypeError, + "tol must be an instance of <class 'numbers.Real'>, not <class 'str'>", + ), + ], +) +def test_ridge_params_validation(params, err_type, err_msg): + """Check the parameters validation in Ridge.""" + + rng = np.random.RandomState(42) + n_samples, n_features, n_targets = 20, 10, 5 + X = rng.randn(n_samples, n_features) + y = rng.randn(n_samples, n_targets) + + with pytest.raises(err_type, match=err_msg): + Ridge(**params).fit(X, y) + + @pytest.mark.parametrize("n_col", [(), (1,), (3,)]) def test_X_CenterStackOp(n_col): rng = np.random.RandomState(0)
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex e2ff5bc76fce2..b9651a1e1b6f8 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -187,6 +187,11 @@ Changelog\n multilabel classification.\n :pr:`19689` by :user:`Guillaume Lemaitre <glemaitre>`.\n \n+- |Enhancement| :class:`linear_model.Ridge` and :class:`linear_model.RidgeClassifier`\n+ now raise consistent error message when passed invalid values for `alpha`,\n+ `max_iter` and `tol`.\n+ :pr:`21341` by :user:`Arturo Amor <ArturoAmorQ>`.\n+\n :mod:`sklearn.linear_model`\n ...........................\n \n" } ]
1.01
80ebe21ec280892df98a02d8fdd61cbf3988ccd6
[ "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-array-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.01-False-auto]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape0-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_lbfgs_solver_consistency[1.0]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_best_score[3-ridge0-make_regression]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.001-True-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-8-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_class_weights", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[1.0-False-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_X_CenterStackOp[n_col1]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape1-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[0.001-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape1-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[cholesky]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[SPARSE_FILTER-None-accuracy]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-array-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[False-shape4]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[0.1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[None-svd-eigen-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_convergence_fail", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_class_weight_vs_sample_weight[RidgeClassifier]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[svd-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_vs_lstsq", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-array-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape0-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-csr_matrix-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_cv_values_not_stored[ridge1-make_classification]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-array-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-csr_matrix-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-array-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_individual_penalties", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_alphas_conversion[RidgeCV]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-csr_matrix-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-8-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-20-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape0-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-array-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[True-shape0]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-20-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-array-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_shapes", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-array-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape1-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_intercept", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[1.0-False-auto]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[DENSE_FILTER-None-_accuracy_callable]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-array-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape0-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-8-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-array-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape1-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-array-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-csr_matrix-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-array-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-8-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape1-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[1.0-True-auto]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[1.0-False]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[lsqr]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-csr_matrix-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[sag]", "sklearn/linear_model/tests/test_ridge.py::test_sparse_design_with_sample_weights", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-array-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_fit_intercept_sparse_error[lsqr]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_positive_ridge_loss[1.0]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-array-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_primal_dual_relationship", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-array-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[True-shape3]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-20-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_ridge_loo]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_ridge_classifiers]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_error[True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape1-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-20-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-20-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-array-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape1-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[False-shape0]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[False-shape2]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_best_score[None-ridge1-make_classification]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_error_test[svd]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[True-shape3]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-20-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-array-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_cv_values_not_stored[ridge0-make_regression]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[eigen-eigen-eigen-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[0.01-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape0-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_X_CenterStackOp[n_col0]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[True-shape2]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[1.0-True-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[eigen-eigen-eigen-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-8-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_positive_ridge_loss[0.001]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape0-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[True-shape4]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_fit_intercept_sparse_error[saga]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-csr_matrix-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape1-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-csr_matrix-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-20-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-lsqr]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[False-shape2]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_ridge_cv]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_custom_scoring[SPARSE_FILTER-cv1]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_cv_store_cv_values[accuracy]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-csr_matrix-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_cv_store_cv_values[_accuracy_callable]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-csr_matrix-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-20-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-csr_matrix-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-csr_matrix-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge[sag]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-20-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_int_alphas", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-array-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape0-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape1-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[svd-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-csr_matrix-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-csr_matrix-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape1-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_lbfgs_solver_consistency[0.1]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_alphas_conversion[RidgeClassifierCV]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-csr_matrix-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridgeclassifier_multilabel[RidgeClassifierCV-params2]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_custom_scoring[DENSE_FILTER-None]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape1-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_loo_cv_asym_scoring", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape0-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-csr_matrix-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-csr_matrix-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_n_iter", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-8-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.001-True-auto]", "sklearn/linear_model/tests/test_ridge.py::test_positive_ridge_loss[0.01]", "sklearn/linear_model/tests/test_ridge.py::test_lbfgs_solver_consistency[0.001]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridgeclassifier_multilabel[RidgeClassifierCV-params1]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-20-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[svd-svd-svd-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[0.001-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_sample_weight", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-8-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape0-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_lbfgs_solver_error", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[True-shape2]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-8-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-sparse_cg]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_ridge_diabetes]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_cv_store_cv_values[None]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[0.1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-csr_matrix-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[DENSE_FILTER-None-None]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[auto-svd-eigen-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.01-False-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.1-True-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_lbfgs_solver_consistency[0.01]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape1-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[1.0-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_raises_value_error_if_sample_weights_greater_than_1d", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[False-shape3]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape0-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_class_weights_cv", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.1-True-auto]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_store_cv_values[_mean_squared_error_callable]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_store_cv_values[neg_mean_squared_error]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-20-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-array-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.01-True-auto]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_error_test[saga]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape0-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_error[1]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[auto-svd-eigen-True]", "sklearn/linear_model/tests/test_ridge.py::test_sparse_cg_max_iter", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape1-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-csr_matrix-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[cholesky-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_error_test[sparse_cg]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[True-shape1]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape0-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[lbfgs-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape0-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_ridge_cv_normalize]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sparse_svd", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-csr_matrix-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-8-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[DENSE_FILTER-cv1-accuracy]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-20-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-csr_matrix-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.001-False-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[DENSE_FILTER-None-accuracy]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape1-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge[lsqr]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-array-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[SPARSE_FILTER-cv1-None]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-array-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-8-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-cholesky]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-csr_matrix-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[0.01-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape1-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_positive_ridge_loss[0.1]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-8-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[False-shape3]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_error_test[sag]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-array-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[SPARSE_FILTER-None-None]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-array-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[sparse_cg]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape1-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_toy_ridge_object", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape1-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape0-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-csr_matrix-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-8-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_negative_alphas", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_error[bad]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-20-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-20-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape0-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[SPARSE_FILTER-None-_accuracy_callable]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-csr_matrix-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_best_score[None-ridge0-make_regression]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[None-svd-eigen-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-8-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge[sparse_cg]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-saga]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-8-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape0-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-array-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[SPARSE_FILTER-cv1-_accuracy_callable]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[DENSE_FILTER-cv1-_accuracy_callable]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[False-shape1]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-20-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[False-shape0]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-array-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[True-shape1]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_sample_weights", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match_cholesky", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape1-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape0-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_error_test[lsqr]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[True-shape0]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape1-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[SPARSE_FILTER-cv1-accuracy]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sag_with_X_fortran", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.01-True-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[lbfgs-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-csr_matrix-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[lsqr-True]", "sklearn/linear_model/tests/test_ridge.py::test_X_CenterStackOp[n_col2]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_class_weight_vs_sample_weight[RidgeClassifierCV]", "sklearn/linear_model/tests/test_ridge.py::test_ridge[cholesky]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_fit_intercept_sparse_error[cholesky]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape0-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-8-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_error[5]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-sag]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_best_score[3-ridge1-make_classification]", "sklearn/linear_model/tests/test_ridge.py::test_ridgeclassifier_multilabel[RidgeClassifier-params0]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape1-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_custom_scoring[SPARSE_FILTER-None]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weights", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[saga]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge[svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_singular", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.001-False-auto]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape1-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-8-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-array-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_raises_value_error_if_solver_not_supported", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape1-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape0-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape0-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[False-shape4]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape0-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape0-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-20-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[False-shape1]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-csr_matrix-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[svd-svd-svd-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape0-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_cv_individual_penalties", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-csr_matrix-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_store_cv_values[None]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_error_test[cholesky]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_custom_scoring[DENSE_FILTER-cv1]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-csr_matrix-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape1-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_multi_ridge_diabetes]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-array-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.1-False-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape0-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[DENSE_FILTER-cv1-None]", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_tolerance]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.1-False-auto]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape1-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_error[gcv]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-csr_matrix-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-array-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[True-shape4]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_fit_intercept_sparse_error[svd]" ]
[ "sklearn/linear_model/tests/test_ridge.py::test_ridge_params_validation[params5-TypeError-tol must be an instance of <class 'numbers.Real'>, not <class 'str'>]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_params_validation[params0-ValueError-alpha == -1, must be >= 0.0]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_params_validation[params1-TypeError-alpha must be an instance of <class 'numbers.Real'>, not <class 'str'>]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_params_validation[params4-ValueError-tol == -1.0, must be >= 0.]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_params_validation[params2-ValueError-max_iter == 0, must be >= 1.]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_params_validation[params3-TypeError-max_iter must be an instance of <class 'numbers.Integral'>, not <class 'str'>]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex e2ff5bc76fce2..b9651a1e1b6f8 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -187,6 +187,11 @@ Changelog\n multilabel classification.\n :pr:`<PRID>` by :user:`<NAME>`.\n \n+- |Enhancement| :class:`linear_model.Ridge` and :class:`linear_model.RidgeClassifier`\n+ now raise consistent error message when passed invalid values for `alpha`,\n+ `max_iter` and `tol`.\n+ :pr:`<PRID>` by :user:`<NAME>`.\n+\n :mod:`sklearn.linear_model`\n ...........................\n \n" } ]
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index e2ff5bc76fce2..b9651a1e1b6f8 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -187,6 +187,11 @@ Changelog multilabel classification. :pr:`<PRID>` by :user:`<NAME>`. +- |Enhancement| :class:`linear_model.Ridge` and :class:`linear_model.RidgeClassifier` + now raise consistent error message when passed invalid values for `alpha`, + `max_iter` and `tol`. + :pr:`<PRID>` by :user:`<NAME>`. + :mod:`sklearn.linear_model` ...........................
scikit-learn/scikit-learn
scikit-learn__scikit-learn-21334
https://github.com/scikit-learn/scikit-learn/pull/21334
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 7141080afbc06..261b6f8eac6bf 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -58,6 +58,22 @@ Changelog - |Fix| :class:`decomposition.FastICA` now validates input parameters in `fit` instead of `__init__`. :pr:`21432` by :user:`Hannah Bohle <hhnnhh>` and :user:`Maren Westermann <marenwestermann>`. +- |API| Adds :term:`get_feature_names_out` to all transformers in the + :mod:`~sklearn.decomposition` module: + :class:`~sklearn.decomposition.DictionaryLearning`, + :class:`~sklearn.decomposition.FactorAnalysis`, + :class:`~sklearn.decomposition.FastICA`, + :class:`~sklearn.decomposition.IncrementalPCA`, + :class:`~sklearn.decomposition.KernelPCA`, + :class:`~sklearn.decomposition.LatentDirichletAllocation`, + :class:`~sklearn.decomposition.MiniBatchDictionaryLearning`, + :class:`~sklearn.decomposition.MiniBatchSparsePCA`, + :class:`~sklearn.decomposition.NMF`, + :class:`~sklearn.decomposition.PCA`, + :class:`~sklearn.decomposition.SparsePCA`, + and :class:`~sklearn.decomposition.TruncatedSVD`. :pr:`21334` by + `Thomas Fan`_. + :mod:`sklearn.impute` ..................... diff --git a/sklearn/base.py b/sklearn/base.py index 241dac26dd3ca..557b2c25b2691 100644 --- a/sklearn/base.py +++ b/sklearn/base.py @@ -24,6 +24,8 @@ from .utils.validation import _check_y from .utils.validation import _num_features from .utils.validation import _check_feature_names_in +from .utils.validation import _generate_get_feature_names_out +from .utils.validation import check_is_fitted from .utils._estimator_html_repr import estimator_html_repr from .utils.validation import _get_feature_names @@ -879,6 +881,31 @@ def get_feature_names_out(self, input_features=None): return _check_feature_names_in(self, input_features) +class _ClassNamePrefixFeaturesOutMixin: + """Mixin class for transformers that generate their own names by prefixing. + + Assumes that `_n_features_out` is defined for the estimator. + """ + + def get_feature_names_out(self, input_features=None): + """Get output feature names for transformation. + + Parameters + ---------- + input_features : array-like of str or None, default=None + Only used to validate feature names with the names seen in :meth:`fit`. + + Returns + ------- + feature_names_out : ndarray of str objects + Transformed feature names. + """ + check_is_fitted(self, "_n_features_out") + return _generate_get_feature_names_out( + self, self._n_features_out, input_features=input_features + ) + + class DensityMixin: """Mixin class for all density estimators in scikit-learn.""" diff --git a/sklearn/decomposition/_base.py b/sklearn/decomposition/_base.py index e503a52ee1f92..7904ce17f7212 100644 --- a/sklearn/decomposition/_base.py +++ b/sklearn/decomposition/_base.py @@ -11,12 +11,14 @@ import numpy as np from scipy import linalg -from ..base import BaseEstimator, TransformerMixin +from ..base import BaseEstimator, TransformerMixin, _ClassNamePrefixFeaturesOutMixin from ..utils.validation import check_is_fitted from abc import ABCMeta, abstractmethod -class _BasePCA(TransformerMixin, BaseEstimator, metaclass=ABCMeta): +class _BasePCA( + _ClassNamePrefixFeaturesOutMixin, TransformerMixin, BaseEstimator, metaclass=ABCMeta +): """Base class for PCA methods. Warning: This class should not be used directly. @@ -154,3 +156,8 @@ def inverse_transform(self, X): ) else: return np.dot(X, self.components_) + self.mean_ + + @property + def _n_features_out(self): + """Number of transformed output features.""" + return self.components_.shape[0] diff --git a/sklearn/decomposition/_dict_learning.py b/sklearn/decomposition/_dict_learning.py index 3ade7727a8b7e..e4edaf31c9c32 100644 --- a/sklearn/decomposition/_dict_learning.py +++ b/sklearn/decomposition/_dict_learning.py @@ -14,7 +14,7 @@ from scipy import linalg from joblib import Parallel, effective_n_jobs -from ..base import BaseEstimator, TransformerMixin +from ..base import BaseEstimator, TransformerMixin, _ClassNamePrefixFeaturesOutMixin from ..utils import deprecated from ..utils import check_array, check_random_state, gen_even_slices, gen_batches from ..utils.extmath import randomized_svd, row_norms, svd_flip @@ -1014,7 +1014,7 @@ def dict_learning_online( return dictionary -class _BaseSparseCoding(TransformerMixin): +class _BaseSparseCoding(_ClassNamePrefixFeaturesOutMixin, TransformerMixin): """Base class from SparseCoder and DictionaryLearning algorithms.""" def __init__( @@ -1315,6 +1315,11 @@ def n_features_in_(self): """Number of features seen during `fit`.""" return self.dictionary.shape[1] + @property + def _n_features_out(self): + """Number of transformed output features.""" + return self.n_components_ + class DictionaryLearning(_BaseSparseCoding, BaseEstimator): """Dictionary learning. @@ -1587,6 +1592,11 @@ def fit(self, X, y=None): self.error_ = E return self + @property + def _n_features_out(self): + """Number of transformed output features.""" + return self.components_.shape[0] + class MiniBatchDictionaryLearning(_BaseSparseCoding, BaseEstimator): """Mini-batch dictionary learning. @@ -1926,3 +1936,8 @@ def partial_fit(self, X, y=None, iter_offset=None): self.inner_stats_ = (A, B) self.iter_offset_ = iter_offset + 1 return self + + @property + def _n_features_out(self): + """Number of transformed output features.""" + return self.components_.shape[0] diff --git a/sklearn/decomposition/_factor_analysis.py b/sklearn/decomposition/_factor_analysis.py index fcf96cb0eb532..8ff5b54d4e839 100644 --- a/sklearn/decomposition/_factor_analysis.py +++ b/sklearn/decomposition/_factor_analysis.py @@ -25,14 +25,14 @@ from scipy import linalg -from ..base import BaseEstimator, TransformerMixin +from ..base import BaseEstimator, TransformerMixin, _ClassNamePrefixFeaturesOutMixin from ..utils import check_random_state from ..utils.extmath import fast_logdet, randomized_svd, squared_norm from ..utils.validation import check_is_fitted from ..exceptions import ConvergenceWarning -class FactorAnalysis(TransformerMixin, BaseEstimator): +class FactorAnalysis(_ClassNamePrefixFeaturesOutMixin, TransformerMixin, BaseEstimator): """Factor Analysis (FA). A simple linear generative model with Gaussian latent variables. @@ -426,6 +426,11 @@ def _rotate(self, components, n_components=None, tol=1e-6): else: raise ValueError("'method' must be in %s, not %s" % (implemented, method)) + @property + def _n_features_out(self): + """Number of transformed output features.""" + return self.components_.shape[0] + def _ortho_rotation(components, method="varimax", tol=1e-6, max_iter=100): """Return rotated components.""" diff --git a/sklearn/decomposition/_fastica.py b/sklearn/decomposition/_fastica.py index 9d4bcc9026926..6eb10ce59505b 100644 --- a/sklearn/decomposition/_fastica.py +++ b/sklearn/decomposition/_fastica.py @@ -14,7 +14,7 @@ import numpy as np from scipy import linalg -from ..base import BaseEstimator, TransformerMixin +from ..base import BaseEstimator, TransformerMixin, _ClassNamePrefixFeaturesOutMixin from ..exceptions import ConvergenceWarning from ..utils import check_array, as_float_array, check_random_state @@ -319,7 +319,7 @@ def my_g(x): return None, est._unmixing, sources -class FastICA(TransformerMixin, BaseEstimator): +class FastICA(_ClassNamePrefixFeaturesOutMixin, TransformerMixin, BaseEstimator): """FastICA: a fast algorithm for Independent Component Analysis. The implementation is based on [1]_. @@ -689,3 +689,8 @@ def inverse_transform(self, X, copy=True): X += self.mean_ return X + + @property + def _n_features_out(self): + """Number of transformed output features.""" + return self.components_.shape[0] diff --git a/sklearn/decomposition/_kernel_pca.py b/sklearn/decomposition/_kernel_pca.py index aee9b46899cd6..ff0fd223512c1 100644 --- a/sklearn/decomposition/_kernel_pca.py +++ b/sklearn/decomposition/_kernel_pca.py @@ -10,15 +10,18 @@ from ..utils._arpack import _init_arpack_v0 from ..utils.extmath import svd_flip, _randomized_eigsh -from ..utils.validation import check_is_fitted, _check_psd_eigenvalues +from ..utils.validation import ( + check_is_fitted, + _check_psd_eigenvalues, +) from ..utils.deprecation import deprecated from ..exceptions import NotFittedError -from ..base import BaseEstimator, TransformerMixin +from ..base import BaseEstimator, TransformerMixin, _ClassNamePrefixFeaturesOutMixin from ..preprocessing import KernelCenterer from ..metrics.pairwise import pairwise_kernels -class KernelPCA(TransformerMixin, BaseEstimator): +class KernelPCA(_ClassNamePrefixFeaturesOutMixin, TransformerMixin, BaseEstimator): """Kernel Principal component analysis (KPCA). Non-linear dimensionality reduction through the use of kernels (see @@ -546,3 +549,8 @@ def _more_tags(self): "preserves_dtype": [np.float64, np.float32], "pairwise": self.kernel == "precomputed", } + + @property + def _n_features_out(self): + """Number of transformed output features.""" + return self.eigenvalues_.shape[0] diff --git a/sklearn/decomposition/_lda.py b/sklearn/decomposition/_lda.py index a723e3451e24f..6db9d900566eb 100644 --- a/sklearn/decomposition/_lda.py +++ b/sklearn/decomposition/_lda.py @@ -16,7 +16,7 @@ from scipy.special import gammaln, logsumexp from joblib import Parallel, effective_n_jobs -from ..base import BaseEstimator, TransformerMixin +from ..base import BaseEstimator, TransformerMixin, _ClassNamePrefixFeaturesOutMixin from ..utils import check_random_state, gen_batches, gen_even_slices from ..utils.validation import check_non_negative from ..utils.validation import check_is_fitted @@ -138,7 +138,9 @@ def _update_doc_distribution( return (doc_topic_distr, suff_stats) -class LatentDirichletAllocation(TransformerMixin, BaseEstimator): +class LatentDirichletAllocation( + _ClassNamePrefixFeaturesOutMixin, TransformerMixin, BaseEstimator +): """Latent Dirichlet Allocation with online variational Bayes algorithm. The implementation is based on [1]_ and [2]_. @@ -887,3 +889,8 @@ def perplexity(self, X, sub_sampling=False): X, reset_n_features=True, whom="LatentDirichletAllocation.perplexity" ) return self._perplexity_precomp_distr(X, sub_sampling=sub_sampling) + + @property + def _n_features_out(self): + """Number of transformed output features.""" + return self.components_.shape[0] diff --git a/sklearn/decomposition/_nmf.py b/sklearn/decomposition/_nmf.py index d914bd5b6126d..e388fdd45c201 100644 --- a/sklearn/decomposition/_nmf.py +++ b/sklearn/decomposition/_nmf.py @@ -15,11 +15,14 @@ from ._cdnmf_fast import _update_cdnmf_fast from .._config import config_context -from ..base import BaseEstimator, TransformerMixin +from ..base import BaseEstimator, TransformerMixin, _ClassNamePrefixFeaturesOutMixin from ..exceptions import ConvergenceWarning from ..utils import check_random_state, check_array from ..utils.extmath import randomized_svd, safe_sparse_dot, squared_norm -from ..utils.validation import check_is_fitted, check_non_negative +from ..utils.validation import ( + check_is_fitted, + check_non_negative, +) EPSILON = np.finfo(np.float32).eps @@ -1109,7 +1112,7 @@ def non_negative_factorization( return W, H, n_iter -class NMF(TransformerMixin, BaseEstimator): +class NMF(_ClassNamePrefixFeaturesOutMixin, TransformerMixin, BaseEstimator): """Non-Negative Matrix Factorization (NMF). Find two non-negative matrices (W, H) whose product approximates the non- @@ -1708,3 +1711,8 @@ def inverse_transform(self, W): """ check_is_fitted(self) return np.dot(W, self.components_) + + @property + def _n_features_out(self): + """Number of transformed output features.""" + return self.components_.shape[0] diff --git a/sklearn/decomposition/_sparse_pca.py b/sklearn/decomposition/_sparse_pca.py index 1d7b4d6dfc063..31c8d2168a3e6 100644 --- a/sklearn/decomposition/_sparse_pca.py +++ b/sklearn/decomposition/_sparse_pca.py @@ -7,11 +7,11 @@ from ..utils import check_random_state from ..utils.validation import check_is_fitted from ..linear_model import ridge_regression -from ..base import BaseEstimator, TransformerMixin +from ..base import BaseEstimator, TransformerMixin, _ClassNamePrefixFeaturesOutMixin from ._dict_learning import dict_learning, dict_learning_online -class SparsePCA(TransformerMixin, BaseEstimator): +class SparsePCA(_ClassNamePrefixFeaturesOutMixin, TransformerMixin, BaseEstimator): """Sparse Principal Components Analysis (SparsePCA). Finds the set of sparse components that can optimally reconstruct @@ -236,6 +236,11 @@ def transform(self, X): return U + @property + def _n_features_out(self): + """Number of transformed output features.""" + return self.components_.shape[0] + class MiniBatchSparsePCA(SparsePCA): """Mini-batch Sparse Principal Components Analysis. diff --git a/sklearn/decomposition/_truncated_svd.py b/sklearn/decomposition/_truncated_svd.py index 21ed87eca5fd1..01d79f742302f 100644 --- a/sklearn/decomposition/_truncated_svd.py +++ b/sklearn/decomposition/_truncated_svd.py @@ -10,7 +10,7 @@ import scipy.sparse as sp from scipy.sparse.linalg import svds -from ..base import BaseEstimator, TransformerMixin +from ..base import BaseEstimator, TransformerMixin, _ClassNamePrefixFeaturesOutMixin from ..utils import check_array, check_random_state from ..utils._arpack import _init_arpack_v0 from ..utils.extmath import randomized_svd, safe_sparse_dot, svd_flip @@ -21,7 +21,7 @@ __all__ = ["TruncatedSVD"] -class TruncatedSVD(TransformerMixin, BaseEstimator): +class TruncatedSVD(_ClassNamePrefixFeaturesOutMixin, TransformerMixin, BaseEstimator): """Dimensionality reduction using truncated SVD (aka LSA). This transformer performs linear dimensionality reduction by means of @@ -273,3 +273,8 @@ def inverse_transform(self, X): def _more_tags(self): return {"preserves_dtype": [np.float64, np.float32]} + + @property + def _n_features_out(self): + """Number of transformed output features.""" + return self.components_.shape[0] diff --git a/sklearn/utils/validation.py b/sklearn/utils/validation.py index 0380af76f5140..7662f03f85ce5 100644 --- a/sklearn/utils/validation.py +++ b/sklearn/utils/validation.py @@ -1702,7 +1702,7 @@ def _get_feature_names(X): return feature_names -def _check_feature_names_in(estimator, input_features=None): +def _check_feature_names_in(estimator, input_features=None, *, generate_names=True): """Get output feature names for transformation. Parameters @@ -1716,9 +1716,13 @@ def _check_feature_names_in(estimator, input_features=None): - If `input_features` is an array-like, then `input_features` must match `feature_names_in_` if `feature_names_in_` is defined. + generate_names : bool, default=True + Wether to generate names when `input_features` is `None` and + `estimator.feature_names_in_` is not defined. + Returns ------- - feature_names_in : ndarray of str + feature_names_in : ndarray of str or `None` Feature names in. """ @@ -1742,8 +1746,40 @@ def _check_feature_names_in(estimator, input_features=None): if feature_names_in_ is not None: return feature_names_in_ + if not generate_names: + return + # Generates feature names if `n_features_in_` is defined if n_features_in_ is None: raise ValueError("Unable to generate feature names without n_features_in_") return np.asarray([f"x{i}" for i in range(n_features_in_)], dtype=object) + + +def _generate_get_feature_names_out(estimator, n_features_out, input_features=None): + """Generate feature names out for estimator using the estimator name as the prefix. + + The input_feature names are validated but not used. This function is useful + for estimators that generate their own names based on `n_features_out`, i.e. PCA. + + Parameters + ---------- + estimator : estimator instance + Estimator producing output feature names. + + n_feature_out : int + Number of feature names out. + + input_features : array-like of str or None, default=None + Only used to validate feature names with `estimator.feature_names_in_`. + + Returns + ------- + feature_names_in : ndarray of str or `None` + Feature names in. + """ + _check_feature_names_in(estimator, input_features, generate_names=False) + estimator_name = estimator.__class__.__name__.lower() + return np.asarray( + [f"{estimator_name}{i}" for i in range(n_features_out)], dtype=object + )
diff --git a/sklearn/decomposition/tests/test_dict_learning.py b/sklearn/decomposition/tests/test_dict_learning.py index 1270287ec844a..9ce477fffcd9d 100644 --- a/sklearn/decomposition/tests/test_dict_learning.py +++ b/sklearn/decomposition/tests/test_dict_learning.py @@ -664,3 +664,21 @@ def test_warning_default_transform_alpha(Estimator): dl = Estimator(alpha=0.1) with pytest.warns(FutureWarning, match="default transform_alpha"): dl.fit_transform(X) + + [email protected]( + "estimator", + [SparseCoder(X.T), DictionaryLearning(), MiniBatchDictionaryLearning()], + ids=lambda x: x.__class__.__name__, +) +def test_get_feature_names_out(estimator): + """Check feature names for dict learning estimators.""" + estimator.fit(X) + n_components = X.shape[1] + + feature_names_out = estimator.get_feature_names_out() + estimator_name = estimator.__class__.__name__.lower() + assert_array_equal( + feature_names_out, + [f"{estimator_name}{i}" for i in range(n_components)], + ) diff --git a/sklearn/decomposition/tests/test_incremental_pca.py b/sklearn/decomposition/tests/test_incremental_pca.py index 756300d970072..2ae2187452eee 100644 --- a/sklearn/decomposition/tests/test_incremental_pca.py +++ b/sklearn/decomposition/tests/test_incremental_pca.py @@ -5,6 +5,7 @@ from sklearn.utils._testing import assert_almost_equal from sklearn.utils._testing import assert_array_almost_equal from sklearn.utils._testing import assert_allclose_dense_sparse +from numpy.testing import assert_array_equal from sklearn import datasets from sklearn.decomposition import PCA, IncrementalPCA @@ -427,3 +428,11 @@ def test_incremental_pca_fit_overflow_error(): pca.fit(A) np.testing.assert_allclose(ipca.singular_values_, pca.singular_values_) + + +def test_incremental_pca_feature_names_out(): + """Check feature names out for IncrementalPCA.""" + ipca = IncrementalPCA(n_components=2).fit(iris.data) + + names = ipca.get_feature_names_out() + assert_array_equal([f"incrementalpca{i}" for i in range(2)], names) diff --git a/sklearn/decomposition/tests/test_kernel_pca.py b/sklearn/decomposition/tests/test_kernel_pca.py index e7ae53fd5188b..72b40ec83e308 100644 --- a/sklearn/decomposition/tests/test_kernel_pca.py +++ b/sklearn/decomposition/tests/test_kernel_pca.py @@ -559,3 +559,12 @@ def test_kernel_pca_alphas_deprecated(): msg = r"Attribute `alphas_` was deprecated in version 1\.0" with pytest.warns(FutureWarning, match=msg): kp.alphas_ + + +def test_kernel_pca_feature_names_out(): + """Check feature names out for KernelPCA.""" + X, *_ = make_blobs(n_samples=100, n_features=4, random_state=0) + kpca = KernelPCA(n_components=2).fit(X) + + names = kpca.get_feature_names_out() + assert_array_equal([f"kernelpca{i}" for i in range(2)], names) diff --git a/sklearn/decomposition/tests/test_nmf.py b/sklearn/decomposition/tests/test_nmf.py index 3b056bf9ee0b1..19eecdbba99e0 100644 --- a/sklearn/decomposition/tests/test_nmf.py +++ b/sklearn/decomposition/tests/test_nmf.py @@ -741,3 +741,13 @@ def test_init_default_deprecation(): NMF().fit(A) with pytest.warns(FutureWarning, match=msg): non_negative_factorization(A) + + +def test_feature_names_out(): + """Check feature names out for NMF.""" + random_state = np.random.RandomState(0) + X = np.abs(random_state.randn(10, 4)) + nmf = NMF(n_components=3, init="nndsvda").fit(X) + + names = nmf.get_feature_names_out() + assert_array_equal([f"nmf{i}" for i in range(3)], names) diff --git a/sklearn/decomposition/tests/test_online_lda.py b/sklearn/decomposition/tests/test_online_lda.py index 811f3186ce503..e3ce951f7b6da 100644 --- a/sklearn/decomposition/tests/test_online_lda.py +++ b/sklearn/decomposition/tests/test_online_lda.py @@ -4,6 +4,7 @@ from scipy.linalg import block_diag from scipy.sparse import csr_matrix from scipy.special import psi +from numpy.testing import assert_array_equal import pytest @@ -427,3 +428,14 @@ def check_verbosity(verbose, evaluate_every, expected_lines, expected_perplexiti ) def test_verbosity(verbose, evaluate_every, expected_lines, expected_perplexities): check_verbosity(verbose, evaluate_every, expected_lines, expected_perplexities) + + +def test_lda_feature_names_out(): + """Check feature names out for LatentDirichletAllocation.""" + n_components, X = _build_sparse_mtx() + lda = LatentDirichletAllocation(n_components=n_components).fit(X) + + names = lda.get_feature_names_out() + assert_array_equal( + [f"latentdirichletallocation{i}" for i in range(n_components)], names + ) diff --git a/sklearn/decomposition/tests/test_pca.py b/sklearn/decomposition/tests/test_pca.py index e7973fd8aa3af..95b790616c02e 100644 --- a/sklearn/decomposition/tests/test_pca.py +++ b/sklearn/decomposition/tests/test_pca.py @@ -1,5 +1,6 @@ import numpy as np import scipy as sp +from numpy.testing import assert_array_equal import pytest @@ -656,3 +657,11 @@ def test_assess_dimesion_rank_one(): assert np.isfinite(_assess_dimension(s, rank=1, n_samples=n_samples)) for rank in range(2, n_features): assert _assess_dimension(s, rank, n_samples) == -np.inf + + +def test_feature_names_out(): + """Check feature names out for PCA.""" + pca = PCA(n_components=2).fit(iris.data) + + names = pca.get_feature_names_out() + assert_array_equal([f"pca{i}" for i in range(2)], names) diff --git a/sklearn/decomposition/tests/test_sparse_pca.py b/sklearn/decomposition/tests/test_sparse_pca.py index 79ad3d0e6006f..c77aabf9c182c 100644 --- a/sklearn/decomposition/tests/test_sparse_pca.py +++ b/sklearn/decomposition/tests/test_sparse_pca.py @@ -5,6 +5,7 @@ import pytest import numpy as np +from numpy.testing import assert_array_equal from sklearn.utils._testing import assert_array_almost_equal from sklearn.utils._testing import assert_allclose @@ -203,3 +204,17 @@ def test_spca_n_components_(SPCA, n_components): assert model.n_components_ == n_components else: assert model.n_components_ == n_features + + [email protected]("SPCA", [SparsePCA, MiniBatchSparsePCA]) +def test_spca_feature_names_out(SPCA): + """Check feature names out for *SparsePCA.""" + rng = np.random.RandomState(0) + n_samples, n_features = 12, 10 + X = rng.randn(n_samples, n_features) + + model = SPCA(n_components=4).fit(X) + names = model.get_feature_names_out() + + estimator_name = SPCA.__name__.lower() + assert_array_equal([f"{estimator_name}{i}" for i in range(4)], names) diff --git a/sklearn/tests/test_common.py b/sklearn/tests/test_common.py index e06a060546713..01fc98deeea91 100644 --- a/sklearn/tests/test_common.py +++ b/sklearn/tests/test_common.py @@ -363,7 +363,6 @@ def test_pandas_column_name_consistency(estimator): GET_FEATURES_OUT_MODULES_TO_IGNORE = [ "cluster", "cross_decomposition", - "decomposition", "discriminant_analysis", "ensemble", "isotonic",
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 7141080afbc06..261b6f8eac6bf 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -58,6 +58,22 @@ Changelog\n - |Fix| :class:`decomposition.FastICA` now validates input parameters in `fit` instead of `__init__`.\n :pr:`21432` by :user:`Hannah Bohle <hhnnhh>` and :user:`Maren Westermann <marenwestermann>`.\n \n+- |API| Adds :term:`get_feature_names_out` to all transformers in the\n+ :mod:`~sklearn.decomposition` module:\n+ :class:`~sklearn.decomposition.DictionaryLearning`,\n+ :class:`~sklearn.decomposition.FactorAnalysis`,\n+ :class:`~sklearn.decomposition.FastICA`,\n+ :class:`~sklearn.decomposition.IncrementalPCA`,\n+ :class:`~sklearn.decomposition.KernelPCA`,\n+ :class:`~sklearn.decomposition.LatentDirichletAllocation`,\n+ :class:`~sklearn.decomposition.MiniBatchDictionaryLearning`,\n+ :class:`~sklearn.decomposition.MiniBatchSparsePCA`,\n+ :class:`~sklearn.decomposition.NMF`,\n+ :class:`~sklearn.decomposition.PCA`,\n+ :class:`~sklearn.decomposition.SparsePCA`,\n+ and :class:`~sklearn.decomposition.TruncatedSVD`. :pr:`21334` by\n+ `Thomas Fan`_.\n+\n :mod:`sklearn.impute`\n .....................\n \n" } ]
1.01
8955057049c5c8cc5a7d8380e236f6a5efcf1c05
[ "sklearn/decomposition/tests/test_incremental_pca.py::test_incremental_pca_partial_fit", "sklearn/decomposition/tests/test_pca.py::test_pca_inverse[True-full]", "sklearn/decomposition/tests/test_pca.py::test_pca[3-arpack]", "sklearn/decomposition/tests/test_incremental_pca.py::test_incremental_pca_sparse[lil_matrix]", "sklearn/decomposition/tests/test_online_lda.py::test_lda_score[online]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[same-0.0-random-mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[same-0.0-nndsvd-mu]", "sklearn/decomposition/tests/test_pca.py::test_pca_inverse[False-randomized]", "sklearn/decomposition/tests/test_pca.py::test_pca_validation[randomized-0-must be between 1 and min\\\\(n_samples, n_features\\\\)-data0]", "sklearn/decomposition/tests/test_incremental_pca.py::test_incremental_pca_num_features_change", "sklearn/decomposition/tests/test_dict_learning.py::test_warning_default_transform_alpha[MiniBatchDictionaryLearning]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[1.0-1.0-nndsvda-mu]", "sklearn/decomposition/tests/test_dict_learning.py::test_dict_learning_overcomplete", "sklearn/decomposition/tests/test_dict_learning.py::test_dict_learning_online_positivity[False-False]", "sklearn/decomposition/tests/test_pca.py::test_infer_dim_by_explained_variance[X2-0.5-2]", "sklearn/decomposition/tests/test_pca.py::test_pca_dtype_preservation[arpack]", "sklearn/decomposition/tests/test_pca.py::test_pca[3-auto]", "sklearn/decomposition/tests/test_online_lda.py::test_lda_score_perplexity", "sklearn/decomposition/tests/test_online_lda.py::test_lda_negative_input", "sklearn/decomposition/tests/test_nmf.py::test_non_negative_factorization_consistency[0.0-1.0-cd-nndsvd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[same-0.0-cd-int32-float64]", "sklearn/decomposition/tests/test_sparse_pca.py::test_fit_transform", "sklearn/decomposition/tests/test_nmf.py::test_non_negative_factorization_consistency[1.0-0.0-cd-random]", "sklearn/decomposition/tests/test_pca.py::test_n_components_none[data0-arpack-3]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[1.0-0.0-mu-int64-float64]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[0.0-0.0-mu-int32-float64]", "sklearn/decomposition/tests/test_nmf.py::test_initialize_nn_output", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[same-1.0-random-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[1.0-0.0-cd-int64-float64]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[0.0-1.0-random-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[1.0-0.0-cd-float64-float64]", "sklearn/decomposition/tests/test_pca.py::test_infer_dim_by_explained_variance[X0-0.95-2]", "sklearn/decomposition/tests/test_dict_learning.py::test_sparse_encode_unavailable_positivity[omp]", "sklearn/decomposition/tests/test_incremental_pca.py::test_incremental_pca_batch_signs", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[same-1.0-nndsvdar-cd]", "sklearn/decomposition/tests/test_nmf.py::test_initialize_close", "sklearn/decomposition/tests/test_nmf.py::test_parameter_checking", "sklearn/decomposition/tests/test_pca.py::test_fit_mle_too_few_samples", "sklearn/decomposition/tests/test_dict_learning.py::test_dict_learning_online_positivity[True-False]", "sklearn/decomposition/tests/test_pca.py::test_pca_inverse[False-full]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[1.0-0.0-None-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[1.0-1.0-mu-float64-float64]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[same-0.0-mu-int32-float64]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[0.0-0.0-None-mu]", "sklearn/decomposition/tests/test_pca.py::test_pca_zero_noise_variance_edge_cases[randomized]", "sklearn/decomposition/tests/test_nmf.py::test_non_negative_factorization_consistency[0.0-0.0-cd-nndsvd]", "sklearn/decomposition/tests/test_nmf.py::test_init_default_deprecation", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[1.0-1.0-nndsvdar-cd]", "sklearn/decomposition/tests/test_dict_learning.py::test_minibatch_dictionary_learning_positivity[True-False-lasso_cd]", "sklearn/decomposition/tests/test_pca.py::test_pca_explained_variance_empirical[randomized-correlated-data]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[1.0-1.0-nndsvda-cd]", "sklearn/decomposition/tests/test_incremental_pca.py::test_incremental_pca_sparse[csr_matrix]", "sklearn/decomposition/tests/test_pca.py::test_pca_singular_values[full]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[same-0.0-nndsvda-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_regularization[cd]", "sklearn/decomposition/tests/test_pca.py::test_pca_check_projection_list[full]", "sklearn/decomposition/tests/test_pca.py::test_pca_check_projection[randomized]", "sklearn/decomposition/tests/test_pca.py::test_pca_explained_variance_empirical[randomized-random-data]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[same-0.0-mu-float32-float32]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[0.0-0.0-nndsvd-cd]", "sklearn/decomposition/tests/test_dict_learning.py::test_dict_learning_lars_positive_parameter", "sklearn/decomposition/tests/test_pca.py::test_pca[2-randomized]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_negative_beta_loss", "sklearn/decomposition/tests/test_nmf.py::test_convergence_warning[mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_sparse_input[same-0.0-mu]", "sklearn/decomposition/tests/test_dict_learning.py::test_dict_learning_positivity[False-True-threshold]", "sklearn/decomposition/tests/test_online_lda.py::test_dirichlet_expectation", "sklearn/decomposition/tests/test_pca.py::test_pca_singular_values_consistency[arpack]", "sklearn/decomposition/tests/test_pca.py::test_pca_explained_variance_empirical[arpack-random-data]", "sklearn/decomposition/tests/test_pca.py::test_pca_validation[arpack-2-must be strictly less than min-data1]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[same-0.0-None-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[0.0-0.0-mu-float32-float32]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[same-1.0-mu-float32-float32]", "sklearn/decomposition/tests/test_dict_learning.py::test_dict_learning_online_overcomplete", "sklearn/decomposition/tests/test_nmf.py::test_nmf_sparse_input[1.0-1.0-cd]", "sklearn/decomposition/tests/test_pca.py::test_whitening[full-True]", "sklearn/decomposition/tests/test_online_lda.py::test_lda_multi_jobs[online]", "sklearn/decomposition/tests/test_pca.py::test_pca_deterministic_output[randomized]", "sklearn/decomposition/tests/test_online_lda.py::test_lda_partial_fit_multi_jobs", "sklearn/decomposition/tests/test_dict_learning.py::test_dict_learning_nonzero_coefs", "sklearn/decomposition/tests/test_pca.py::test_pca_validation[auto-3-n_components={}L? must be between {}L? and min\\\\(n_samples, n_features\\\\)={}L? with svd_solver=\\\\'{}\\\\'-data1]", "sklearn/decomposition/tests/test_dict_learning.py::test_dict_learning_online_lars_positive_parameter", "sklearn/decomposition/tests/test_pca.py::test_pca_validation[auto-3-n_components={}L? must be between {}L? and min\\\\(n_samples, n_features\\\\)={}L? with svd_solver=\\\\'{}\\\\'-data0]", "sklearn/decomposition/tests/test_dict_learning.py::test_minibatch_dictionary_learning_lars[False]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[1.0-1.0-mu-int32-float64]", "sklearn/decomposition/tests/test_online_lda.py::test_lda_score[batch]", "sklearn/decomposition/tests/test_sparse_pca.py::test_pca_vs_spca", "sklearn/decomposition/tests/test_dict_learning.py::test_dict_learning_lassocd_readonly_data", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[0.0-1.0-mu-float64-float64]", "sklearn/decomposition/tests/test_nmf.py::test_n_components_greater_n_features", "sklearn/decomposition/tests/test_pca.py::test_pca_deterministic_output[full]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[same-0.0-nndsvdar-mu]", "sklearn/decomposition/tests/test_pca.py::test_pca_score[auto]", "sklearn/decomposition/tests/test_sparse_pca.py::test_initialization", "sklearn/decomposition/tests/test_dict_learning.py::test_sparse_encode_positivity[True-lasso_cd]", "sklearn/decomposition/tests/test_nmf.py::test_beta_divergence", "sklearn/decomposition/tests/test_dict_learning.py::test_sparse_coder_n_features_in", "sklearn/decomposition/tests/test_nmf.py::test_nmf_underflow", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[1.0-0.0-nndsvd-cd]", "sklearn/decomposition/tests/test_dict_learning.py::test_sparse_coder_estimator_clone", "sklearn/decomposition/tests/test_dict_learning.py::test_sparse_coder_parallel_mmap", "sklearn/decomposition/tests/test_dict_learning.py::test_dict_learning_online_verbosity", "sklearn/decomposition/tests/test_dict_learning.py::test_dict_learning_positivity[False-True-lasso_cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[0.0-1.0-nndsvdar-mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[0.0-0.0-nndsvda-mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[same-1.0-nndsvd-cd]", "sklearn/decomposition/tests/test_pca.py::test_pca_check_projection[auto]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[1.0-1.0-None-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[1.0-0.0-cd-float32-float32]", "sklearn/decomposition/tests/test_dict_learning.py::test_dict_learning_lars_dict_positivity[False]", "sklearn/decomposition/tests/test_dict_learning.py::test_sparse_encode_shapes_omp", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[same-0.0-None-mu]", "sklearn/decomposition/tests/test_dict_learning.py::test_dict_learning_unknown_fit_algorithm", "sklearn/decomposition/tests/test_online_lda.py::test_verbosity[False-0-0-0]", "sklearn/decomposition/tests/test_pca.py::test_pca[1-auto]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[same-1.0-cd-int32-float64]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[1.0-1.0-nndsvd-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[0.0-0.0-nndsvdar-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[same-1.0-cd-float64-float64]", "sklearn/decomposition/tests/test_dict_learning.py::test_dict_learning_positivity[True-False-threshold]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[1.0-1.0-random-mu]", "sklearn/decomposition/tests/test_pca.py::test_pca_bad_solver", "sklearn/decomposition/tests/test_pca.py::test_pca[2-auto]", "sklearn/decomposition/tests/test_dict_learning.py::test_dict_learning_iter_offset", "sklearn/decomposition/tests/test_nmf.py::test_non_negative_factorization_consistency[1.0-0.0-cd-nndsvd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[1.0-0.0-nndsvdar-cd]", "sklearn/decomposition/tests/test_pca.py::test_pca_singular_values[arpack]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[1.0-1.0-cd-int32-float64]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[same-0.0-cd-float64-float64]", "sklearn/decomposition/tests/test_pca.py::test_small_eigenvalues_mle", "sklearn/decomposition/tests/test_nmf.py::test_non_negative_factorization_consistency[same-0.0-mu-nndsvd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[same-1.0-cd-int64-float64]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[same-0.0-cd-float32-float32]", "sklearn/decomposition/tests/test_dict_learning.py::test_dict_learning_positivity[True-True-lasso_cd]", "sklearn/decomposition/tests/test_incremental_pca.py::test_incremental_pca_partial_fit_float_division", "sklearn/decomposition/tests/test_pca.py::test_pca_score_consistency_solvers[arpack]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[0.0-1.0-cd-float32-float32]", "sklearn/decomposition/tests/test_nmf.py::test_non_negative_factorization_consistency[same-1.0-cd-random]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[0.0-1.0-nndsvda-mu]", "sklearn/decomposition/tests/test_dict_learning.py::test_sparse_encode_error", "sklearn/decomposition/tests/test_nmf.py::test_non_negative_factorization_consistency[same-1.0-mu-nndsvd]", "sklearn/decomposition/tests/test_dict_learning.py::test_dict_learning_split", "sklearn/decomposition/tests/test_dict_learning.py::test_sparse_encode_positivity[False-threshold]", "sklearn/decomposition/tests/test_pca.py::test_pca_inverse[True-arpack]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[1.0-1.0-cd-float64-float64]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[same-0.0-cd-int64-float64]", "sklearn/decomposition/tests/test_pca.py::test_pca_zero_noise_variance_edge_cases[full]", "sklearn/decomposition/tests/test_nmf.py::test_non_negative_factorization_consistency[1.0-1.0-cd-nndsvd]", "sklearn/decomposition/tests/test_online_lda.py::test_invalid_params", "sklearn/decomposition/tests/test_online_lda.py::test_verbosity[True-0-3-0]", "sklearn/decomposition/tests/test_pca.py::test_pca_check_projection[full]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[0.0-1.0-cd-float64-float64]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[1.0-1.0-cd-float32-float32]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[1.0-0.0-random-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[same-0.0-nndsvd-cd]", "sklearn/decomposition/tests/test_pca.py::test_n_components_none[data1-arpack-3]", "sklearn/decomposition/tests/test_pca.py::test_n_components_mle_error[randomized]", "sklearn/decomposition/tests/test_dict_learning.py::test_dict_learning_positivity[True-True-lasso_lars]", "sklearn/decomposition/tests/test_dict_learning.py::test_minibatch_dictionary_learning_positivity[True-True-lasso_lars]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_sparse_input[1.0-1.0-mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[0.0-1.0-nndsvda-cd]", "sklearn/decomposition/tests/test_pca.py::test_pca_sparse_input[arpack]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[0.0-0.0-mu-float64-float64]", "sklearn/decomposition/tests/test_pca.py::test_pca_singular_values_consistency[randomized]", "sklearn/decomposition/tests/test_pca.py::test_pca_validation[auto--1-n_components={}L? must be between {}L? and min\\\\(n_samples, n_features\\\\)={}L? with svd_solver=\\\\'{}\\\\'-data1]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_close[cd]", "sklearn/decomposition/tests/test_pca.py::test_pca_svd_solver_auto[data1-5-full]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[1.0-1.0-cd-int64-float64]", "sklearn/decomposition/tests/test_pca.py::test_whitening[arpack-True]", "sklearn/decomposition/tests/test_incremental_pca.py::test_incremental_pca_set_params", "sklearn/decomposition/tests/test_pca.py::test_infer_dim_by_explained_variance[X1-0.01-1]", "sklearn/decomposition/tests/test_incremental_pca.py::test_incremental_pca_check_projection", "sklearn/decomposition/tests/test_incremental_pca.py::test_incremental_pca_batch_rank", "sklearn/decomposition/tests/test_online_lda.py::test_lda_multi_jobs[batch]", "sklearn/decomposition/tests/test_pca.py::test_pca[1-arpack]", "sklearn/decomposition/tests/test_pca.py::test_whitening[auto-False]", "sklearn/decomposition/tests/test_pca.py::test_pca_explained_variance_empirical[auto-correlated-data]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_float32_float64_consistency[mu]", "sklearn/decomposition/tests/test_pca.py::test_pca_score[arpack]", "sklearn/decomposition/tests/test_dict_learning.py::test_sparse_encode_shapes", "sklearn/decomposition/tests/test_pca.py::test_n_components_none[data0-randomized-4]", "sklearn/decomposition/tests/test_pca.py::test_pca_explained_variance_empirical[full-random-data]", "sklearn/decomposition/tests/test_pca.py::test_pca_score[randomized]", "sklearn/decomposition/tests/test_dict_learning.py::test_dict_learning_lars_dict_positivity[True]", "sklearn/decomposition/tests/test_nmf.py::test_non_negative_factorization_consistency[same-0.0-cd-random]", "sklearn/decomposition/tests/test_nmf.py::test_non_negative_factorization_consistency[1.0-0.0-mu-nndsvd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[1.0-0.0-mu-float32-float32]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[same-1.0-nndsvda-mu]", "sklearn/decomposition/tests/test_pca.py::test_pca_sanity_noise_variance[full]", "sklearn/decomposition/tests/test_incremental_pca.py::test_incremental_pca_against_pca_random_data", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[1.0-0.0-cd-int32-float64]", "sklearn/decomposition/tests/test_pca.py::test_pca[3-full]", "sklearn/decomposition/tests/test_dict_learning.py::test_dict_learning_online_positivity[False-True]", "sklearn/decomposition/tests/test_pca.py::test_n_components_mle[full]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[0.0-0.0-nndsvd-mu]", "sklearn/decomposition/tests/test_online_lda.py::test_perplexity_input_format", "sklearn/decomposition/tests/test_pca.py::test_pca_sparse_input[auto]", "sklearn/decomposition/tests/test_dict_learning.py::test_sparse_coder_common_transformer", "sklearn/decomposition/tests/test_nmf.py::test_non_negative_factorization_consistency[0.0-1.0-mu-nndsvd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[1.0-1.0-random-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[same-1.0-mu-float64-float64]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_transform[mu]", "sklearn/decomposition/tests/test_nmf.py::test_non_negative_factorization_consistency[1.0-0.0-mu-random]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_float32_float64_consistency[cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[same-0.0-random-cd]", "sklearn/decomposition/tests/test_sparse_pca.py::test_mini_batch_correct_shapes", "sklearn/decomposition/tests/test_nmf.py::test_nmf_transform_custom_init", "sklearn/decomposition/tests/test_incremental_pca.py::test_incremental_pca_fit_overflow_error", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[0.0-0.0-None-cd]", "sklearn/decomposition/tests/test_pca.py::test_pca_explained_variance_equivalence_solver[arpack]", "sklearn/decomposition/tests/test_sparse_pca.py::test_transform_nan", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[1.0-1.0-mu-float32-float32]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_regularization[mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_sparse_input[same-0.0-cd]", "sklearn/decomposition/tests/test_dict_learning.py::test_sparse_encode_positivity[False-lasso_cd]", "sklearn/decomposition/tests/test_pca.py::test_whitening[randomized-False]", "sklearn/decomposition/tests/test_dict_learning.py::test_minibatch_dictionary_learning_positivity[True-True-lasso_cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[1.0-0.0-nndsvda-mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[same-1.0-mu-int32-float64]", "sklearn/decomposition/tests/test_pca.py::test_pca_check_projection_list[arpack]", "sklearn/decomposition/tests/test_online_lda.py::test_lda_fit_perplexity", "sklearn/decomposition/tests/test_dict_learning.py::test_dict_learning_positivity[False-False-lasso_cd]", "sklearn/decomposition/tests/test_pca.py::test_pca_sanity_noise_variance[auto]", "sklearn/decomposition/tests/test_online_lda.py::test_verbosity[False-1-0-0]", "sklearn/decomposition/tests/test_dict_learning.py::test_sparse_coder_deprecation", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[1.0-0.0-nndsvdar-mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[0.0-1.0-None-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[0.0-0.0-random-cd]", "sklearn/decomposition/tests/test_online_lda.py::test_lda_preplexity_mismatch", "sklearn/decomposition/tests/test_nmf.py::test_non_negative_factorization_consistency[same-1.0-cd-nndsvd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_custom_init_dtype_error", "sklearn/decomposition/tests/test_pca.py::test_pca_singular_values[randomized]", "sklearn/decomposition/tests/test_nmf.py::test_non_negative_factorization_consistency[1.0-1.0-cd-random]", "sklearn/decomposition/tests/test_sparse_pca.py::test_spca_n_components_[None-SparsePCA]", "sklearn/decomposition/tests/test_pca.py::test_whitening[full-False]", "sklearn/decomposition/tests/test_sparse_pca.py::test_scaling_fit_transform", "sklearn/decomposition/tests/test_pca.py::test_pca_dtype_preservation[auto]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[same-0.0-nndsvda-mu]", "sklearn/decomposition/tests/test_dict_learning.py::test_sparse_encode_error_default_sparsity", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[0.0-1.0-None-mu]", "sklearn/decomposition/tests/test_pca.py::test_pca_dtype_preservation[randomized]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_sparse_input[0.0-0.0-cd]", "sklearn/decomposition/tests/test_pca.py::test_pca_explained_variance_equivalence_solver[randomized]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_sparse_input[0.0-1.0-mu]", "sklearn/decomposition/tests/test_dict_learning.py::test_minibatch_dictionary_learning_positivity[True-True-threshold]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[0.0-1.0-mu-float32-float32]", "sklearn/decomposition/tests/test_pca.py::test_pca_sanity_noise_variance[randomized]", "sklearn/decomposition/tests/test_incremental_pca.py::test_incremental_pca_batch_values", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[0.0-0.0-nndsvdar-mu]", "sklearn/decomposition/tests/test_nmf.py::test_non_negative_factorization_consistency[same-1.0-mu-random]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_sparse_input[1.0-0.0-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_sparse_input[same-1.0-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[0.0-1.0-mu-int32-float64]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[1.0-0.0-random-mu]", "sklearn/decomposition/tests/test_pca.py::test_pca_deterministic_output[auto]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[1.0-0.0-None-mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_inverse_transform[mu]", "sklearn/decomposition/tests/test_pca.py::test_pca_inverse[True-randomized]", "sklearn/decomposition/tests/test_pca.py::test_pca[1-full]", "sklearn/decomposition/tests/test_pca.py::test_pca_validation[auto-1.0-must be of type int-data1]", "sklearn/decomposition/tests/test_incremental_pca.py::test_whitening", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[0.0-0.0-cd-float64-float64]", "sklearn/decomposition/tests/test_pca.py::test_pca_score_consistency_solvers[randomized]", "sklearn/decomposition/tests/test_pca.py::test_pca_sparse_input[randomized]", "sklearn/decomposition/tests/test_dict_learning.py::test_dict_learning_positivity[False-False-lasso_lars]", "sklearn/decomposition/tests/test_dict_learning.py::test_sparse_encode_positivity[True-threshold]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[same-1.0-cd-float32-float32]", "sklearn/decomposition/tests/test_dict_learning.py::test_sparse_coder_estimator", "sklearn/decomposition/tests/test_online_lda.py::test_lda_perplexity[online]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_decreasing[mu]", "sklearn/decomposition/tests/test_online_lda.py::test_lda_default_prior_params", "sklearn/decomposition/tests/test_pca.py::test_whitening[arpack-False]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[0.0-0.0-mu-int64-float64]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[0.0-0.0-cd-float32-float32]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[same-1.0-nndsvdar-mu]", "sklearn/decomposition/tests/test_pca.py::test_n_components_mle_error[arpack]", "sklearn/decomposition/tests/test_nmf.py::test_initialize_variants", "sklearn/decomposition/tests/test_nmf.py::test_non_negative_factorization_consistency[0.0-1.0-cd-random]", "sklearn/decomposition/tests/test_incremental_pca.py::test_singular_values", "sklearn/decomposition/tests/test_pca.py::test_whitening[randomized-True]", "sklearn/decomposition/tests/test_nmf.py::test_non_negative_factorization_consistency[1.0-1.0-mu-nndsvd]", "sklearn/decomposition/tests/test_pca.py::test_pca[3-randomized]", "sklearn/decomposition/tests/test_nmf.py::test_non_negative_factorization_checking", "sklearn/decomposition/tests/test_dict_learning.py::test_dict_learning_online_initialization", "sklearn/decomposition/tests/test_nmf.py::test_non_negative_factorization_consistency[0.0-0.0-cd-random]", "sklearn/decomposition/tests/test_pca.py::test_pca_dim", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[0.0-0.0-random-mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[1.0-0.0-mu-float64-float64]", "sklearn/decomposition/tests/test_dict_learning.py::test_dict_learning_shapes", "sklearn/decomposition/tests/test_pca.py::test_pca_deterministic_output[arpack]", "sklearn/decomposition/tests/test_dict_learning.py::test_minibatch_dictionary_learning_positivity[False-True-lasso_cd]", "sklearn/decomposition/tests/test_online_lda.py::test_lda_dense_input", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[1.0-1.0-nndsvdar-mu]", "sklearn/decomposition/tests/test_online_lda.py::test_lda_fit_online", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[same-0.0-nndsvdar-cd]", "sklearn/decomposition/tests/test_sparse_pca.py::test_fit_transform_tall", "sklearn/decomposition/tests/test_pca.py::test_n_components_none[data0-full-4]", "sklearn/decomposition/tests/test_dict_learning.py::test_dict_learning_online_positivity[True-True]", "sklearn/decomposition/tests/test_nmf.py::test_convergence_warning[cd]", "sklearn/decomposition/tests/test_dict_learning.py::test_sparse_encode_positivity[True-lasso_lars]", "sklearn/decomposition/tests/test_dict_learning.py::test_dict_learning_positivity[False-False-threshold]", "sklearn/decomposition/tests/test_online_lda.py::test_lda_fit_batch", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[same-1.0-None-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[1.0-1.0-nndsvd-mu]", "sklearn/decomposition/tests/test_nmf.py::test_non_negative_factorization_consistency[0.0-0.0-mu-nndsvd]", "sklearn/decomposition/tests/test_dict_learning.py::test_dict_learning_online_shapes", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[0.0-0.0-cd-int64-float64]", "sklearn/decomposition/tests/test_pca.py::test_infer_dim_2", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[1.0-0.0-mu-int32-float64]", "sklearn/decomposition/tests/test_incremental_pca.py::test_incremental_pca_against_pca_iris", "sklearn/decomposition/tests/test_pca.py::test_pca_sparse_input[full]", "sklearn/decomposition/tests/test_online_lda.py::test_lda_no_component_error", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[0.0-1.0-nndsvd-mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_decreasing[cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[0.0-1.0-cd-int64-float64]", "sklearn/decomposition/tests/test_dict_learning.py::test_warning_default_transform_alpha[DictionaryLearning]", "sklearn/decomposition/tests/test_pca.py::test_assess_dimesion_rank_one", "sklearn/decomposition/tests/test_pca.py::test_n_components_none[data1-full-4]", "sklearn/decomposition/tests/test_pca.py::test_pca_check_projection_list[auto]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[0.0-1.0-cd-int32-float64]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_sparse_input[1.0-0.0-mu]", "sklearn/decomposition/tests/test_dict_learning.py::test_sparse_encode_input", "sklearn/decomposition/tests/test_dict_learning.py::test_minibatch_dictionary_learning_positivity[False-True-threshold]", "sklearn/decomposition/tests/test_pca.py::test_pca_svd_solver_auto[data2-50-full]", "sklearn/decomposition/tests/test_dict_learning.py::test_dict_learning_positivity[False-True-lasso_lars]", "sklearn/decomposition/tests/test_incremental_pca.py::test_incremental_pca_sparse[csc_matrix]", "sklearn/decomposition/tests/test_pca.py::test_n_components_none[data1-randomized-4]", "sklearn/decomposition/tests/test_dict_learning.py::test_dict_learning_positivity[True-False-lasso_lars]", "sklearn/decomposition/tests/test_dict_learning.py::test_dict_learning_positivity[True-False-lasso_cd]", "sklearn/decomposition/tests/test_sparse_pca.py::test_correct_shapes", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[same-0.0-mu-int64-float64]", "sklearn/decomposition/tests/test_pca.py::test_pca_svd_solver_auto[data3-10-randomized]", "sklearn/decomposition/tests/test_online_lda.py::test_lda_transform", "sklearn/decomposition/tests/test_dict_learning.py::test_update_dict", "sklearn/decomposition/tests/test_pca.py::test_pca[1-randomized]", "sklearn/decomposition/tests/test_pca.py::test_pca_validation[arpack-0-must be between 1 and min\\\\(n_samples, n_features\\\\)-data1]", "sklearn/decomposition/tests/test_online_lda.py::test_lda_perplexity[batch]", "sklearn/decomposition/tests/test_pca.py::test_mle_redundant_data", "sklearn/decomposition/tests/test_sparse_pca.py::test_fit_transform_parallel", "sklearn/decomposition/tests/test_dict_learning.py::test_sparse_encode_positivity[False-lasso_lars]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[1.0-1.0-mu-int64-float64]", "sklearn/decomposition/tests/test_dict_learning.py::test_dict_learning_positivity[True-True-threshold]", "sklearn/decomposition/tests/test_pca.py::test_pca_svd_solver_auto[data0-0.5-full]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[0.0-1.0-nndsvdar-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[0.0-0.0-cd-int32-float64]", "sklearn/decomposition/tests/test_pca.py::test_pca_sanity_noise_variance[arpack]", "sklearn/decomposition/tests/test_sparse_pca.py::test_spca_n_components_[3-SparsePCA]", "sklearn/decomposition/tests/test_dict_learning.py::test_minibatch_dictionary_learning_positivity[False-False-lasso_cd]", "sklearn/decomposition/tests/test_nmf.py::test_non_negative_factorization_consistency[1.0-1.0-mu-random]", "sklearn/decomposition/tests/test_pca.py::test_pca_explained_variance_empirical[auto-random-data]", "sklearn/decomposition/tests/test_incremental_pca.py::test_incremental_pca_validation", "sklearn/decomposition/tests/test_pca.py::test_n_components_mle[auto]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_sparse_input[same-1.0-mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[0.0-1.0-random-mu]", "sklearn/decomposition/tests/test_pca.py::test_infer_dim_1", "sklearn/decomposition/tests/test_pca.py::test_assess_dimension_bad_rank", "sklearn/decomposition/tests/test_online_lda.py::test_lda_partial_fit", "sklearn/decomposition/tests/test_nmf.py::test_nmf_inverse_transform[cd]", "sklearn/decomposition/tests/test_nmf.py::test_special_sparse_dot", "sklearn/decomposition/tests/test_pca.py::test_mle_simple_case", "sklearn/decomposition/tests/test_nmf.py::test_nmf_sparse_input[0.0-0.0-mu]", "sklearn/decomposition/tests/test_dict_learning.py::test_minibatch_dictionary_learning_positivity[True-False-threshold]", "sklearn/decomposition/tests/test_online_lda.py::test_verbosity[True-1-3-3]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[0.0-0.0-nndsvda-cd]", "sklearn/decomposition/tests/test_pca.py::test_infer_dim_3", "sklearn/decomposition/tests/test_incremental_pca.py::test_incremental_pca_inverse", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[0.0-1.0-mu-int64-float64]", "sklearn/decomposition/tests/test_nmf.py::test_non_negative_factorization_consistency[0.0-1.0-mu-random]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[same-1.0-None-mu]", "sklearn/decomposition/tests/test_dict_learning.py::test_sparse_encode_unavailable_positivity[lars]", "sklearn/decomposition/tests/test_sparse_pca.py::test_spca_n_components_[None-MiniBatchSparsePCA]", "sklearn/decomposition/tests/test_dict_learning.py::test_unknown_method", "sklearn/decomposition/tests/test_pca.py::test_pca_check_projection_list[randomized]", "sklearn/decomposition/tests/test_online_lda.py::test_lda_empty_docs", "sklearn/decomposition/tests/test_pca.py::test_pca_dtype_preservation[full]", "sklearn/decomposition/tests/test_pca.py::test_pca_validation[arpack-0-must be between 1 and min\\\\(n_samples, n_features\\\\)-data0]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_close[mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[1.0-0.0-nndsvd-mu]", "sklearn/decomposition/tests/test_dict_learning.py::test_minibatch_dictionary_learning_positivity[False-False-lasso_lars]", "sklearn/decomposition/tests/test_dict_learning.py::test_dict_learning_lars_code_positivity", "sklearn/decomposition/tests/test_dict_learning.py::test_dict_learning_reconstruction", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[same-1.0-mu-int64-float64]", "sklearn/decomposition/tests/test_pca.py::test_pca_validation[arpack-2-must be strictly less than min-data0]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_sparse_input[0.0-1.0-cd]", "sklearn/decomposition/tests/test_pca.py::test_whitening[auto-True]", "sklearn/decomposition/tests/test_online_lda.py::test_lda_fit_transform[batch]", "sklearn/decomposition/tests/test_pca.py::test_pca_singular_values[auto]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[same-1.0-nndsvda-cd]", "sklearn/decomposition/tests/test_pca.py::test_pca_score[full]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_transform[cd]", "sklearn/decomposition/tests/test_pca.py::test_pca[2-arpack]", "sklearn/decomposition/tests/test_incremental_pca.py::test_explained_variances", "sklearn/decomposition/tests/test_dict_learning.py::test_dict_learning_online_partial_fit", "sklearn/decomposition/tests/test_dict_learning.py::test_minibatch_dictionary_learning_positivity[False-False-threshold]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[same-0.0-mu-float64-float64]", "sklearn/decomposition/tests/test_pca.py::test_pca[2-full]", "sklearn/decomposition/tests/test_pca.py::test_pca_explained_variance_empirical[full-correlated-data]", "sklearn/decomposition/tests/test_sparse_pca.py::test_spca_n_components_[3-MiniBatchSparsePCA]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[1.0-1.0-None-mu]", "sklearn/decomposition/tests/test_pca.py::test_pca_validation[auto-1.0-must be of type int-data0]", "sklearn/decomposition/tests/test_dict_learning.py::test_dict_learning_reconstruction_parallel", "sklearn/decomposition/tests/test_pca.py::test_pca_inverse[False-arpack]", "sklearn/decomposition/tests/test_online_lda.py::test_lda_fit_transform[online]", "sklearn/decomposition/tests/test_dict_learning.py::test_minibatch_dictionary_learning_lars[True]", "sklearn/decomposition/tests/test_nmf.py::test_non_negative_factorization_consistency[same-0.0-mu-random]", "sklearn/decomposition/tests/test_incremental_pca.py::test_n_components_none", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[0.0-1.0-nndsvd-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_multiplicative_update_sparse", "sklearn/decomposition/tests/test_nmf.py::test_non_negative_factorization_consistency[same-0.0-cd-nndsvd]", "sklearn/decomposition/tests/test_dict_learning.py::test_dict_learning_online_readonly_initialization", "sklearn/decomposition/tests/test_online_lda.py::test_verbosity[True-2-3-1]", "sklearn/decomposition/tests/test_pca.py::test_pca_score3", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[same-1.0-nndsvd-mu]", "sklearn/decomposition/tests/test_dict_learning.py::test_minibatch_dictionary_learning_positivity[True-False-lasso_lars]", "sklearn/decomposition/tests/test_incremental_pca.py::test_incremental_pca", "sklearn/decomposition/tests/test_nmf.py::test_nmf_sparse_transform", "sklearn/decomposition/tests/test_pca.py::test_pca_check_projection[arpack]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[same-1.0-random-mu]", "sklearn/decomposition/tests/test_dict_learning.py::test_minibatch_dictionary_learning_positivity[False-True-lasso_lars]", "sklearn/decomposition/tests/test_pca.py::test_pca_validation[auto--1-n_components={}L? must be between {}L? and min\\\\(n_samples, n_features\\\\)={}L? with svd_solver=\\\\'{}\\\\'-data0]", "sklearn/decomposition/tests/test_pca.py::test_pca_n_components_mostly_explained_variance_ratio", "sklearn/decomposition/tests/test_nmf.py::test_non_negative_factorization_consistency[0.0-0.0-mu-random]", "sklearn/decomposition/tests/test_pca.py::test_pca_explained_variance_empirical[arpack-correlated-data]", "sklearn/decomposition/tests/test_dict_learning.py::test_dict_learning_online_estimator_shapes", "sklearn/decomposition/tests/test_pca.py::test_pca_validation[randomized-0-must be between 1 and min\\\\(n_samples, n_features\\\\)-data1]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[1.0-0.0-nndsvda-cd]" ]
[ "sklearn/decomposition/tests/test_sparse_pca.py::test_spca_feature_names_out[SparsePCA]", "sklearn/decomposition/tests/test_dict_learning.py::test_get_feature_names_out[DictionaryLearning]", "sklearn/decomposition/tests/test_nmf.py::test_feature_names_out", "sklearn/decomposition/tests/test_online_lda.py::test_lda_feature_names_out", "sklearn/decomposition/tests/test_dict_learning.py::test_get_feature_names_out[MiniBatchDictionaryLearning]", "sklearn/decomposition/tests/test_sparse_pca.py::test_spca_feature_names_out[MiniBatchSparsePCA]", "sklearn/decomposition/tests/test_dict_learning.py::test_get_feature_names_out[SparseCoder]", "sklearn/decomposition/tests/test_pca.py::test_feature_names_out", "sklearn/decomposition/tests/test_incremental_pca.py::test_incremental_pca_feature_names_out" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 7141080afbc06..261b6f8eac6bf 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -58,6 +58,22 @@ Changelog\n - |Fix| :class:`decomposition.FastICA` now validates input parameters in `fit` instead of `__init__`.\n :pr:`<PRID>` by :user:`<NAME>` and :user:`<NAME>`.\n \n+- |API| Adds :term:`get_feature_names_out` to all transformers in the\n+ :mod:`~sklearn.decomposition` module:\n+ :class:`~sklearn.decomposition.DictionaryLearning`,\n+ :class:`~sklearn.decomposition.FactorAnalysis`,\n+ :class:`~sklearn.decomposition.FastICA`,\n+ :class:`~sklearn.decomposition.IncrementalPCA`,\n+ :class:`~sklearn.decomposition.KernelPCA`,\n+ :class:`~sklearn.decomposition.LatentDirichletAllocation`,\n+ :class:`~sklearn.decomposition.MiniBatchDictionaryLearning`,\n+ :class:`~sklearn.decomposition.MiniBatchSparsePCA`,\n+ :class:`~sklearn.decomposition.NMF`,\n+ :class:`~sklearn.decomposition.PCA`,\n+ :class:`~sklearn.decomposition.SparsePCA`,\n+ and :class:`~sklearn.decomposition.TruncatedSVD`. :pr:`<PRID>` by\n+ `Thomas Fan`_.\n+\n :mod:`sklearn.impute`\n .....................\n \n" } ]
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 7141080afbc06..261b6f8eac6bf 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -58,6 +58,22 @@ Changelog - |Fix| :class:`decomposition.FastICA` now validates input parameters in `fit` instead of `__init__`. :pr:`<PRID>` by :user:`<NAME>` and :user:`<NAME>`. +- |API| Adds :term:`get_feature_names_out` to all transformers in the + :mod:`~sklearn.decomposition` module: + :class:`~sklearn.decomposition.DictionaryLearning`, + :class:`~sklearn.decomposition.FactorAnalysis`, + :class:`~sklearn.decomposition.FastICA`, + :class:`~sklearn.decomposition.IncrementalPCA`, + :class:`~sklearn.decomposition.KernelPCA`, + :class:`~sklearn.decomposition.LatentDirichletAllocation`, + :class:`~sklearn.decomposition.MiniBatchDictionaryLearning`, + :class:`~sklearn.decomposition.MiniBatchSparsePCA`, + :class:`~sklearn.decomposition.NMF`, + :class:`~sklearn.decomposition.PCA`, + :class:`~sklearn.decomposition.SparsePCA`, + and :class:`~sklearn.decomposition.TruncatedSVD`. :pr:`<PRID>` by + `Thomas Fan`_. + :mod:`sklearn.impute` .....................
scikit-learn/scikit-learn
scikit-learn__scikit-learn-21086
https://github.com/scikit-learn/scikit-learn/pull/21086
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 37dc4c56dc860..e6cf2d70efbba 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -221,7 +221,10 @@ Changelog a parameter in order to provide an estimate of the noise variance. This is particularly relevant when `n_features > n_samples` and the estimator of the noise variance cannot be computed. - :pr:`21481` by :user:`Guillaume Lemaitre <glemaitre>` + :pr:`21481` by :user:`Guillaume Lemaitre <glemaitre>`. + +- |Enhancement| :class:`linear_model.QuantileRegressor` support sparse inputs. + :pr:`21086` by :user:`Venkatachalam Natchiappan <venkyyuvy>`. - |Fix| :class:`linear_model.LassoLarsIC` now correctly computes AIC and BIC. An error is now raised when `n_features > n_samples` and diff --git a/sklearn/linear_model/_quantile.py b/sklearn/linear_model/_quantile.py index 352f13db48245..2e605f4d43d5a 100644 --- a/sklearn/linear_model/_quantile.py +++ b/sklearn/linear_model/_quantile.py @@ -4,11 +4,13 @@ import warnings import numpy as np +from scipy import sparse from scipy.optimize import linprog from ..base import BaseEstimator, RegressorMixin from ._base import LinearModel from ..exceptions import ConvergenceWarning +from ..utils import _safe_indexing from ..utils.validation import _check_sample_weight from ..utils.fixes import sp_version, parse_version @@ -44,6 +46,8 @@ class QuantileRegressor(LinearModel, RegressorMixin, BaseEstimator): Method used by :func:`scipy.optimize.linprog` to solve the linear programming formulation. Note that the highs methods are recommended for usage with `scipy>=1.6.0` because they are the fastest ones. + Solvers "highs-ds", "highs-ipm" and "highs" support + sparse input data. solver_options : dict, default=None Additional parameters passed to :func:`scipy.optimize.linprog` as @@ -112,7 +116,7 @@ def fit(self, X, y, sample_weight=None): Parameters ---------- - X : array-like of shape (n_samples, n_features) + X : {array-like, sparse matrix} of shape (n_samples, n_features) Training data. y : array-like of shape (n_samples,) @@ -127,7 +131,11 @@ def fit(self, X, y, sample_weight=None): Returns self. """ X, y = self._validate_data( - X, y, accept_sparse=False, y_numeric=True, multi_output=False + X, + y, + accept_sparse=["csc", "csr", "coo"], + y_numeric=True, + multi_output=False, ) sample_weight = _check_sample_weight(sample_weight, X) @@ -218,13 +226,17 @@ def fit(self, X, y, sample_weight=None): # # Filtering out zero samples weights from the beginning makes life # easier for the linprog solver. - mask = sample_weight != 0 - n_mask = int(np.sum(mask)) # use n_mask instead of n_samples + indices = np.nonzero(sample_weight)[0] + n_indices = len(indices) # use n_mask instead of n_samples + if n_indices < len(sample_weight): + sample_weight = sample_weight[indices] + X = _safe_indexing(X, indices) + y = _safe_indexing(y, indices) c = np.concatenate( [ np.full(2 * n_params, fill_value=alpha), - sample_weight[mask] * self.quantile, - sample_weight[mask] * (1 - self.quantile), + sample_weight * self.quantile, + sample_weight * (1 - self.quantile), ] ) if self.fit_intercept: @@ -232,23 +244,29 @@ def fit(self, X, y, sample_weight=None): c[0] = 0 c[n_params] = 0 - A_eq = np.concatenate( - [ - np.ones((n_mask, 1)), - X[mask], - -np.ones((n_mask, 1)), - -X[mask], - np.eye(n_mask), - -np.eye(n_mask), - ], - axis=1, - ) + if sparse.issparse(X): + if self.solver not in ["highs-ds", "highs-ipm", "highs"]: + raise ValueError( + f"Solver {self.solver} does not support sparse X. " + "Use solver 'highs' for example." + ) + # Note that highs methods do convert to csc. + # Therefore, we work with csc matrices as much as possible. + eye = sparse.eye(n_indices, dtype=X.dtype, format="csc") + if self.fit_intercept: + ones = sparse.csc_matrix(np.ones(shape=(n_indices, 1), dtype=X.dtype)) + A_eq = sparse.hstack([ones, X, -ones, -X, eye, -eye], format="csc") + else: + A_eq = sparse.hstack([X, -X, eye, -eye], format="csc") else: - A_eq = np.concatenate( - [X[mask], -X[mask], np.eye(n_mask), -np.eye(n_mask)], axis=1 - ) - - b_eq = y[mask] + eye = np.eye(n_indices) + if self.fit_intercept: + ones = np.ones((n_indices, 1)) + A_eq = np.concatenate([ones, X, -ones, -X, eye, -eye], axis=1) + else: + A_eq = np.concatenate([X, -X, eye, -eye], axis=1) + + b_eq = y result = linprog( c=c,
diff --git a/sklearn/linear_model/tests/test_quantile.py b/sklearn/linear_model/tests/test_quantile.py index 9f29ae1b3604e..caf35830ea553 100644 --- a/sklearn/linear_model/tests/test_quantile.py +++ b/sklearn/linear_model/tests/test_quantile.py @@ -6,6 +6,7 @@ import pytest from pytest import approx from scipy.optimize import minimize +from scipy import sparse from sklearn.datasets import make_regression from sklearn.exceptions import ConvergenceWarning @@ -45,6 +46,21 @@ def test_init_parameters_validation(X_y_data, params, err_msg): QuantileRegressor(**params).fit(X, y) [email protected]( + sp_version < parse_version("1.3.0"), + reason="Solver 'revised simplex' is only available with of scipy>=1.3.0", +) [email protected]("solver", ["interior-point", "revised simplex"]) +def test_incompatible_solver_for_sparse_input(X_y_data, solver): + X, y = X_y_data + X_sparse = sparse.csc_matrix(X) + err_msg = ( + f"Solver {solver} does not support sparse X. Use solver 'highs' for example." + ) + with pytest.raises(ValueError, match=err_msg): + QuantileRegressor(solver=solver).fit(X_sparse, y) + + @pytest.mark.parametrize("solver", ("highs-ds", "highs-ipm", "highs")) @pytest.mark.skipif( sp_version >= parse_version("1.6.0"), @@ -250,3 +266,28 @@ def test_linprog_failure(): msg = "Linear programming for QuantileRegressor did not succeed." with pytest.warns(ConvergenceWarning, match=msg): reg.fit(X, y) + + [email protected]( + sp_version <= parse_version("1.6.0"), + reason="Solvers are available as of scipy 1.6.0", +) [email protected]( + "sparse_format", [sparse.csc_matrix, sparse.csr_matrix, sparse.coo_matrix] +) [email protected]("solver", ["highs", "highs-ds", "highs-ipm"]) [email protected]("fit_intercept", [True, False]) +def test_sparse_input(sparse_format, solver, fit_intercept): + """Test that sparse and dense X give same results.""" + X, y = make_regression(n_samples=100, n_features=20, random_state=1, noise=1.0) + X_sparse = sparse_format(X) + alpha = 1e-4 + quant_dense = QuantileRegressor(alpha=alpha, fit_intercept=fit_intercept).fit(X, y) + quant_sparse = QuantileRegressor( + alpha=alpha, fit_intercept=fit_intercept, solver=solver + ).fit(X_sparse, y) + assert_allclose(quant_sparse.coef_, quant_dense.coef_, rtol=1e-2) + if fit_intercept: + assert quant_sparse.intercept_ == approx(quant_dense.intercept_) + # check that we still predict fraction + assert 0.45 <= np.mean(y < quant_sparse.predict(X_sparse)) <= 0.55
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 37dc4c56dc860..e6cf2d70efbba 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -221,7 +221,10 @@ Changelog\n a parameter in order to provide an estimate of the noise variance.\n This is particularly relevant when `n_features > n_samples` and the\n estimator of the noise variance cannot be computed.\n- :pr:`21481` by :user:`Guillaume Lemaitre <glemaitre>`\n+ :pr:`21481` by :user:`Guillaume Lemaitre <glemaitre>`.\n+\n+- |Enhancement| :class:`linear_model.QuantileRegressor` support sparse inputs.\n+ :pr:`21086` by :user:`Venkatachalam Natchiappan <venkyyuvy>`.\n \n - |Fix| :class:`linear_model.LassoLarsIC` now correctly computes AIC\n and BIC. An error is now raised when `n_features > n_samples` and\n" } ]
1.01
056f993b411c1fa5cf6a2ced8e51de03617b25b4
[ "sklearn/linear_model/tests/test_quantile.py::test_init_parameters_validation[params5-The argument fit_intercept must be bool]", "sklearn/linear_model/tests/test_quantile.py::test_quantile_equals_huber_for_low_epsilon[False]", "sklearn/linear_model/tests/test_quantile.py::test_equivariance[0.5]", "sklearn/linear_model/tests/test_quantile.py::test_quantile_toy_example[0.51-0-1-10]", "sklearn/linear_model/tests/test_quantile.py::test_quantile_estimates_calibration[0.05]", "sklearn/linear_model/tests/test_quantile.py::test_quantile_estimates_calibration[0.5]", "sklearn/linear_model/tests/test_quantile.py::test_equivariance[0.8]", "sklearn/linear_model/tests/test_quantile.py::test_init_parameters_validation[params0-Quantile should be strictly between 0.0 and 1.0]", "sklearn/linear_model/tests/test_quantile.py::test_init_parameters_validation[params1-Quantile should be strictly between 0.0 and 1.0]", "sklearn/linear_model/tests/test_quantile.py::test_quantile_sample_weight", "sklearn/linear_model/tests/test_quantile.py::test_init_parameters_validation[params4-Penalty alpha must be a non-negative number]", "sklearn/linear_model/tests/test_quantile.py::test_equivariance[0.2]", "sklearn/linear_model/tests/test_quantile.py::test_quantile_estimates_calibration[0.9]", "sklearn/linear_model/tests/test_quantile.py::test_init_parameters_validation[params8-Invalid value for argument solver_options]", "sklearn/linear_model/tests/test_quantile.py::test_init_parameters_validation[params6-The argument fit_intercept must be bool]", "sklearn/linear_model/tests/test_quantile.py::test_init_parameters_validation[params2-Quantile should be strictly between 0.0 and 1.0]", "sklearn/linear_model/tests/test_quantile.py::test_too_new_solver_methods_raise_error[highs-ds]", "sklearn/linear_model/tests/test_quantile.py::test_quantile_toy_example[0.5-0.01-1-1]", "sklearn/linear_model/tests/test_quantile.py::test_too_new_solver_methods_raise_error[highs-ipm]", "sklearn/linear_model/tests/test_quantile.py::test_too_new_solver_methods_raise_error[highs]", "sklearn/linear_model/tests/test_quantile.py::test_quantile_toy_example[0.5-0-1-None]", "sklearn/linear_model/tests/test_quantile.py::test_linprog_failure", "sklearn/linear_model/tests/test_quantile.py::test_quantile_equals_huber_for_low_epsilon[True]", "sklearn/linear_model/tests/test_quantile.py::test_quantile_toy_example[0.49-0-1-1]", "sklearn/linear_model/tests/test_quantile.py::test_init_parameters_validation[params7-Invalid value for argument solver]", "sklearn/linear_model/tests/test_quantile.py::test_init_parameters_validation[params3-Quantile should be strictly between 0.0 and 1.0]", "sklearn/linear_model/tests/test_quantile.py::test_quantile_toy_example[0.5-100-2-0]" ]
[ "sklearn/linear_model/tests/test_quantile.py::test_incompatible_solver_for_sparse_input[revised simplex]", "sklearn/linear_model/tests/test_quantile.py::test_incompatible_solver_for_sparse_input[interior-point]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 37dc4c56dc860..e6cf2d70efbba 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -221,7 +221,10 @@ Changelog\n a parameter in order to provide an estimate of the noise variance.\n This is particularly relevant when `n_features > n_samples` and the\n estimator of the noise variance cannot be computed.\n- :pr:`<PRID>` by :user:`<NAME>`\n+ :pr:`<PRID>` by :user:`<NAME>`.\n+\n+- |Enhancement| :class:`linear_model.QuantileRegressor` support sparse inputs.\n+ :pr:`<PRID>` by :user:`<NAME>`.\n \n - |Fix| :class:`linear_model.LassoLarsIC` now correctly computes AIC\n and BIC. An error is now raised when `n_features > n_samples` and\n" } ]
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 37dc4c56dc860..e6cf2d70efbba 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -221,7 +221,10 @@ Changelog a parameter in order to provide an estimate of the noise variance. This is particularly relevant when `n_features > n_samples` and the estimator of the noise variance cannot be computed. - :pr:`<PRID>` by :user:`<NAME>` + :pr:`<PRID>` by :user:`<NAME>`. + +- |Enhancement| :class:`linear_model.QuantileRegressor` support sparse inputs. + :pr:`<PRID>` by :user:`<NAME>`. - |Fix| :class:`linear_model.LassoLarsIC` now correctly computes AIC and BIC. An error is now raised when `n_features > n_samples` and
scikit-learn/scikit-learn
scikit-learn__scikit-learn-17266
https://github.com/scikit-learn/scikit-learn/pull/17266
diff --git a/doc/modules/model_evaluation.rst b/doc/modules/model_evaluation.rst index 730b094581276..079313a45c3d0 100644 --- a/doc/modules/model_evaluation.rst +++ b/doc/modules/model_evaluation.rst @@ -2005,6 +2005,19 @@ then the explained variance is estimated as follow: The best possible score is 1.0, lower values are worse. +Note: when the prediction residuals have zero mean, the Explained Variance +score and the :ref:`r2_score` are identical. + +In the particular case where the true target is constant, the Explained +Variance score is not finite: it is either ``NaN`` (perfect predictions) or +``-Inf`` (imperfect predictions). Such non-finite scores may prevent correct +model optimization such as grid-search cross-validation to be performed +correctly. For this reason the default behaviour of +:func:`explained_variance_score` is to replace them with 1.0 (perfect +predictions) or 0.0 (imperfect predictions). You can set the ``force_finite`` +parameter to ``False`` to prevent this fix from happening and fallback on the +original Explained Variance score. + Here is a small example of usage of the :func:`explained_variance_score` function:: @@ -2019,6 +2032,18 @@ function:: array([0.967..., 1. ]) >>> explained_variance_score(y_true, y_pred, multioutput=[0.3, 0.7]) 0.990... + >>> y_true = [-2, -2, -2] + >>> y_pred = [-2, -2, -2] + >>> explained_variance_score(y_true, y_pred) + 1.0 + >>> explained_variance_score(y_true, y_pred, force_finite=False) + nan + >>> y_true = [-2, -2, -2] + >>> y_pred = [-2, -2, -2 + 1e-8] + >>> explained_variance_score(y_true, y_pred) + 0.0 + >>> explained_variance_score(y_true, y_pred, force_finite=False) + -inf .. _max_error: @@ -2241,8 +2266,11 @@ predicted by the model, through the proportion of explained variance. As such variance is dataset dependent, R² may not be meaningfully comparable across different datasets. Best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always -predicts the expected value of y, disregarding the input features, would get a -R² score of 0.0. +predicts the expected (average) value of y, disregarding the input features, +would get an :math:`R^2` score of 0.0. + +Note: when the prediction residuals have zero mean, the :math:`R^2` score and +the :ref:`explained_variance_score` are identical. If :math:`\hat{y}_i` is the predicted value of the :math:`i`-th sample and :math:`y_i` is the corresponding true value for total :math:`n` samples, @@ -2257,6 +2285,14 @@ where :math:`\bar{y} = \frac{1}{n} \sum_{i=1}^{n} y_i` and :math:`\sum_{i=1}^{n} Note that :func:`r2_score` calculates unadjusted R² without correcting for bias in sample variance of y. +In the particular case where the true target is constant, the :math:`R^2` score is +not finite: it is either ``NaN`` (perfect predictions) or ``-Inf`` (imperfect +predictions). Such non-finite scores may prevent correct model optimization +such as grid-search cross-validation to be performed correctly. For this reason +the default behaviour of :func:`r2_score` is to replace them with 1.0 (perfect +predictions) or 0.0 (imperfect predictions). If ``force_finite`` +is set to ``False``, this score falls back on the original :math:`R^2` definition. + Here is a small example of usage of the :func:`r2_score` function:: >>> from sklearn.metrics import r2_score @@ -2276,7 +2312,18 @@ Here is a small example of usage of the :func:`r2_score` function:: array([0.965..., 0.908...]) >>> r2_score(y_true, y_pred, multioutput=[0.3, 0.7]) 0.925... - + >>> y_true = [-2, -2, -2] + >>> y_pred = [-2, -2, -2] + >>> r2_score(y_true, y_pred) + 1.0 + >>> r2_score(y_true, y_pred, force_finite=False) + nan + >>> y_true = [-2, -2, -2] + >>> y_pred = [-2, -2, -2 + 1e-8] + >>> r2_score(y_true, y_pred) + 0.0 + >>> r2_score(y_true, y_pred, force_finite=False) + -inf .. topic:: Example: diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 5d49a6fd281c7..d67d08ac45f6b 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -288,6 +288,12 @@ Changelog :mod:`sklearn.metrics` ...................... +- |Feature| :func:`r2_score` and :func:`explained_variance_score` have a new + `force_finite` parameter. Setting this parameter to `False` will return the + actual non-finite score in case of perfect predictions or constant `y_true`, + instead of the finite approximation (`1.0` and `0.0` respectively) currently + returned by default. :pr:`17266` by :user:`Sylvain Marié <smarie>`. + - |API| :class:`metrics.DistanceMetric` has been moved from :mod:`sklearn.neighbors` to :mod:`sklearn.metric`. Using `neighbors.DistanceMetric` for imports is still valid for diff --git a/sklearn/metrics/_regression.py b/sklearn/metrics/_regression.py index ffa2b0b8218aa..ad7257ad55037 100644 --- a/sklearn/metrics/_regression.py +++ b/sklearn/metrics/_regression.py @@ -22,6 +22,7 @@ # Christian Lorentzen <[email protected]> # Ashutosh Hathidara <[email protected]> # Uttam kumar <[email protected]> +# Sylvain Marie <[email protected]> # License: BSD 3 clause import warnings @@ -608,13 +609,74 @@ def median_absolute_error( return np.average(output_errors, weights=multioutput) +def _assemble_r2_explained_variance( + numerator, denominator, n_outputs, multioutput, force_finite +): + """Common part used by explained variance score and :math:`R^2` score.""" + + nonzero_denominator = denominator != 0 + + if not force_finite: + # Standard formula, that may lead to NaN or -Inf + output_scores = 1 - (numerator / denominator) + else: + nonzero_numerator = numerator != 0 + # Default = Zero Numerator = perfect predictions. Set to 1.0 + # (note: even if denominator is zero, thus avoiding NaN scores) + output_scores = np.ones([n_outputs]) + # Non-zero Numerator and Non-zero Denominator: use the formula + valid_score = nonzero_denominator & nonzero_numerator + output_scores[valid_score] = 1 - ( + numerator[valid_score] / denominator[valid_score] + ) + # Non-zero Numerator and Zero Denominator: + # arbitrary set to 0.0 to avoid -inf scores + output_scores[nonzero_numerator & ~nonzero_denominator] = 0.0 + + if isinstance(multioutput, str): + if multioutput == "raw_values": + # return scores individually + return output_scores + elif multioutput == "uniform_average": + # Passing None as weights to np.average results is uniform mean + avg_weights = None + elif multioutput == "variance_weighted": + avg_weights = denominator + if not np.any(nonzero_denominator): + # All weights are zero, np.average would raise a ZeroDiv error. + # This only happens when all y are constant (or 1-element long) + # Since weights are all equal, fall back to uniform weights. + avg_weights = None + else: + avg_weights = multioutput + + return np.average(output_scores, weights=avg_weights) + + def explained_variance_score( - y_true, y_pred, *, sample_weight=None, multioutput="uniform_average" + y_true, + y_pred, + *, + sample_weight=None, + multioutput="uniform_average", + force_finite=True, ): """Explained variance regression score function. Best possible score is 1.0, lower values are worse. + In the particular case when ``y_true`` is constant, the explained variance + score is not finite: it is either ``NaN`` (perfect predictions) or + ``-Inf`` (imperfect predictions). To prevent such non-finite numbers to + pollute higher-level experiments such as a grid search cross-validation, + by default these cases are replaced with 1.0 (perfect predictions) or 0.0 + (imperfect predictions) respectively. If ``force_finite`` + is set to ``False``, this score falls back on the original :math:`R^2` + definition. + + Note: when the prediction residuals have zero mean, the Explained Variance + score is identical to the :func:`R^2 score <r2_score>`. + Read more in the :ref:`User Guide <explained_variance_score>`. Parameters @@ -643,6 +705,15 @@ def explained_variance_score( Scores of all outputs are averaged, weighted by the variances of each individual output. + force_finite : bool, default=True + Flag indicating if ``NaN`` and ``-Inf`` scores resulting from constant + data should be replaced with real numbers (``1.0`` if prediction is + perfect, ``0.0`` otherwise). Default is ``True``, a convenient setting + for hyperparameters' search procedures (e.g. grid search + cross-validation). + + .. versionadded:: 1.1 + Returns ------- score : float or ndarray of floats @@ -663,6 +734,18 @@ def explained_variance_score( >>> y_pred = [[0, 2], [-1, 2], [8, -5]] >>> explained_variance_score(y_true, y_pred, multioutput='uniform_average') 0.983... + >>> y_true = [-2, -2, -2] + >>> y_pred = [-2, -2, -2] + >>> explained_variance_score(y_true, y_pred) + 1.0 + >>> explained_variance_score(y_true, y_pred, force_finite=False) + nan + >>> y_true = [-2, -2, -2] + >>> y_pred = [-2, -2, -2 + 1e-8] + >>> explained_variance_score(y_true, y_pred) + 0.0 + >>> explained_variance_score(y_true, y_pred, force_finite=False) + -inf """ y_type, y_true, y_pred, multioutput = _check_reg_targets( y_true, y_pred, multioutput @@ -677,35 +760,41 @@ def explained_variance_score( y_true_avg = np.average(y_true, weights=sample_weight, axis=0) denominator = np.average((y_true - y_true_avg) ** 2, weights=sample_weight, axis=0) - nonzero_numerator = numerator != 0 - nonzero_denominator = denominator != 0 - valid_score = nonzero_numerator & nonzero_denominator - output_scores = np.ones(y_true.shape[1]) - - output_scores[valid_score] = 1 - (numerator[valid_score] / denominator[valid_score]) - output_scores[nonzero_numerator & ~nonzero_denominator] = 0.0 - if isinstance(multioutput, str): - if multioutput == "raw_values": - # return scores individually - return output_scores - elif multioutput == "uniform_average": - # passing to np.average() None as weights results is uniform mean - avg_weights = None - elif multioutput == "variance_weighted": - avg_weights = denominator - else: - avg_weights = multioutput - - return np.average(output_scores, weights=avg_weights) + return _assemble_r2_explained_variance( + numerator=numerator, + denominator=denominator, + n_outputs=y_true.shape[1], + multioutput=multioutput, + force_finite=force_finite, + ) -def r2_score(y_true, y_pred, *, sample_weight=None, multioutput="uniform_average"): +def r2_score( + y_true, + y_pred, + *, + sample_weight=None, + multioutput="uniform_average", + force_finite=True, +): """:math:`R^2` (coefficient of determination) regression score function. Best possible score is 1.0 and it can be negative (because the - model can be arbitrarily worse). A constant model that always - predicts the expected value of y, disregarding the input features, - would get a :math:`R^2` score of 0.0. + model can be arbitrarily worse). In the general case when the true y is + non-constant, a constant model that always predicts the average y + disregarding the input features would get a :math:`R^2` score of 0.0. + + In the particular case when ``y_true`` is constant, the :math:`R^2` score + is not finite: it is either ``NaN`` (perfect predictions) or ``-Inf`` + (imperfect predictions). To prevent such non-finite numbers to pollute + higher-level experiments such as a grid search cross-validation, by default + these cases are replaced with 1.0 (perfect predictions) or 0.0 (imperfect + predictions) respectively. You can set ``force_finite`` to ``False`` to + prevent this fix from happening. + + Note: when the prediction residuals have zero mean, the :math:`R^2` score + is identical to the + :func:`Explained Variance score <explained_variance_score>`. Read more in the :ref:`User Guide <r2_score>`. @@ -740,6 +829,15 @@ def r2_score(y_true, y_pred, *, sample_weight=None, multioutput="uniform_average .. versionchanged:: 0.19 Default value of multioutput is 'uniform_average'. + force_finite : bool, default=True + Flag indicating if ``NaN`` and ``-Inf`` scores resulting from constant + data should be replaced with real numbers (``1.0`` if prediction is + perfect, ``0.0`` otherwise). Default is ``True``, a convenient setting + for hyperparameters' search procedures (e.g. grid search + cross-validation). + + .. versionadded:: 1.1 + Returns ------- z : float or ndarray of floats @@ -785,6 +883,18 @@ def r2_score(y_true, y_pred, *, sample_weight=None, multioutput="uniform_average >>> y_pred = [3, 2, 1] >>> r2_score(y_true, y_pred) -3.0 + >>> y_true = [-2, -2, -2] + >>> y_pred = [-2, -2, -2] + >>> r2_score(y_true, y_pred) + 1.0 + >>> r2_score(y_true, y_pred, force_finite=False) + nan + >>> y_true = [-2, -2, -2] + >>> y_pred = [-2, -2, -2 + 1e-8] + >>> r2_score(y_true, y_pred) + 0.0 + >>> r2_score(y_true, y_pred, force_finite=False) + -inf """ y_type, y_true, y_pred, multioutput = _check_reg_targets( y_true, y_pred, multioutput @@ -806,33 +916,14 @@ def r2_score(y_true, y_pred, *, sample_weight=None, multioutput="uniform_average denominator = ( weight * (y_true - np.average(y_true, axis=0, weights=sample_weight)) ** 2 ).sum(axis=0, dtype=np.float64) - nonzero_denominator = denominator != 0 - nonzero_numerator = numerator != 0 - valid_score = nonzero_denominator & nonzero_numerator - output_scores = np.ones([y_true.shape[1]]) - output_scores[valid_score] = 1 - (numerator[valid_score] / denominator[valid_score]) - # arbitrary set to zero to avoid -inf scores, having a constant - # y_true is not interesting for scoring a regression anyway - output_scores[nonzero_numerator & ~nonzero_denominator] = 0.0 - if isinstance(multioutput, str): - if multioutput == "raw_values": - # return scores individually - return output_scores - elif multioutput == "uniform_average": - # passing None as weights results is uniform mean - avg_weights = None - elif multioutput == "variance_weighted": - avg_weights = denominator - # avoid fail on constant y or one-element arrays - if not np.any(nonzero_denominator): - if not np.any(nonzero_numerator): - return 1.0 - else: - return 0.0 - else: - avg_weights = multioutput - return np.average(output_scores, weights=avg_weights) + return _assemble_r2_explained_variance( + numerator=numerator, + denominator=denominator, + n_outputs=y_true.shape[1], + multioutput=multioutput, + force_finite=force_finite, + ) def max_error(y_true, y_pred):
diff --git a/sklearn/metrics/tests/test_regression.py b/sklearn/metrics/tests/test_regression.py index 1a64be4e5ab53..249a3646fe41b 100644 --- a/sklearn/metrics/tests/test_regression.py +++ b/sklearn/metrics/tests/test_regression.py @@ -50,7 +50,11 @@ def test_regression_metrics(n_samples=50): assert mape > 1e6 assert_almost_equal(max_error(y_true, y_pred), 1.0) assert_almost_equal(r2_score(y_true, y_pred), 0.995, 2) + assert_almost_equal(r2_score(y_true, y_pred, force_finite=False), 0.995, 2) assert_almost_equal(explained_variance_score(y_true, y_pred), 1.0) + assert_almost_equal( + explained_variance_score(y_true, y_pred, force_finite=False), 1.0 + ) assert_almost_equal( mean_tweedie_deviance(y_true, y_pred, power=0), mean_squared_error(y_true, y_pred), @@ -135,8 +139,47 @@ def test_multioutput_regression(): error = r2_score(y_true, y_pred, multioutput="uniform_average") assert_almost_equal(error, -0.875) + # constant `y_true` with force_finite=True leads to 1. or 0. + yc = [5.0, 5.0] + error = r2_score(yc, [5.0, 5.0], multioutput="variance_weighted") + assert_almost_equal(error, 1.0) + error = r2_score(yc, [5.0, 5.1], multioutput="variance_weighted") + assert_almost_equal(error, 0.0) + + # Setting force_finite=False results in the nan for 4th output propagating + error = r2_score( + y_true, y_pred, multioutput="variance_weighted", force_finite=False + ) + assert_almost_equal(error, np.nan) + error = r2_score(y_true, y_pred, multioutput="uniform_average", force_finite=False) + assert_almost_equal(error, np.nan) + + # Dropping the 4th output to check `force_finite=False` for nominal + y_true = y_true[:, :-1] + y_pred = y_pred[:, :-1] + error = r2_score(y_true, y_pred, multioutput="variance_weighted") + error2 = r2_score( + y_true, y_pred, multioutput="variance_weighted", force_finite=False + ) + assert_almost_equal(error, error2) + error = r2_score(y_true, y_pred, multioutput="uniform_average") + error2 = r2_score(y_true, y_pred, multioutput="uniform_average", force_finite=False) + assert_almost_equal(error, error2) + + # constant `y_true` with force_finite=False leads to NaN or -Inf. + error = r2_score( + yc, [5.0, 5.0], multioutput="variance_weighted", force_finite=False + ) + assert_almost_equal(error, np.nan) + error = r2_score( + yc, [5.0, 6.0], multioutput="variance_weighted", force_finite=False + ) + assert_almost_equal(error, -np.inf) + def test_regression_metrics_at_limits(): + # Single-sample case + # Note: for r2 and d2_tweedie see also test_regression_single_sample assert_almost_equal(mean_squared_error([0.0], [0.0]), 0.0) assert_almost_equal(mean_squared_error([0.0], [0.0], squared=False), 0.0) assert_almost_equal(mean_squared_log_error([0.0], [0.0]), 0.0) @@ -146,7 +189,17 @@ def test_regression_metrics_at_limits(): assert_almost_equal(median_absolute_error([0.0], [0.0]), 0.0) assert_almost_equal(max_error([0.0], [0.0]), 0.0) assert_almost_equal(explained_variance_score([0.0], [0.0]), 1.0) + + # Perfect cases assert_almost_equal(r2_score([0.0, 1], [0.0, 1]), 1.0) + + # Non-finite cases + # R² and explained variance have a fix by default for non-finite cases + for s in (r2_score, explained_variance_score): + assert_almost_equal(s([0, 0], [1, -1]), 0.0) + assert_almost_equal(s([0, 0], [1, -1], force_finite=False), -np.inf) + assert_almost_equal(s([1, 1], [1, 1]), 1.0) + assert_almost_equal(s([1, 1], [1, 1], force_finite=False), np.nan) msg = ( "Mean Squared Logarithmic Error cannot be used when targets " "contain negative values." @@ -270,6 +323,9 @@ def test_regression_multioutput_array(): mape = mean_absolute_percentage_error(y_true, y_pred, multioutput="raw_values") r = r2_score(y_true, y_pred, multioutput="raw_values") evs = explained_variance_score(y_true, y_pred, multioutput="raw_values") + evs2 = explained_variance_score( + y_true, y_pred, multioutput="raw_values", force_finite=False + ) assert_array_almost_equal(mse, [0.125, 0.5625], decimal=2) assert_array_almost_equal(mae, [0.25, 0.625], decimal=2) @@ -277,6 +333,7 @@ def test_regression_multioutput_array(): assert_array_almost_equal(mape, [0.0778, 0.2262], decimal=2) assert_array_almost_equal(r, [0.95, 0.93], decimal=2) assert_array_almost_equal(evs, [0.95, 0.93], decimal=2) + assert_array_almost_equal(evs2, [0.95, 0.93], decimal=2) # mean_absolute_error and mean_squared_error are equal because # it is a binary problem. @@ -300,17 +357,38 @@ def test_regression_multioutput_array(): [[0, -1], [0, 1]], [[2, 2], [1, 1]], multioutput="raw_values" ) assert_array_almost_equal(evs, [0, -1.25], decimal=2) + evs2 = explained_variance_score( + [[0, -1], [0, 1]], + [[2, 2], [1, 1]], + multioutput="raw_values", + force_finite=False, + ) + assert_array_almost_equal(evs2, [-np.inf, -1.25], decimal=2) # Checking for the condition in which both numerator and denominator is # zero. - y_true = [[1, 3], [-1, 2]] - y_pred = [[1, 4], [-1, 1]] + y_true = [[1, 3], [1, 2]] + y_pred = [[1, 4], [1, 1]] r2 = r2_score(y_true, y_pred, multioutput="raw_values") assert_array_almost_equal(r2, [1.0, -3.0], decimal=2) assert np.mean(r2) == r2_score(y_true, y_pred, multioutput="uniform_average") + r22 = r2_score(y_true, y_pred, multioutput="raw_values", force_finite=False) + assert_array_almost_equal(r22, [np.nan, -3.0], decimal=2) + assert_almost_equal( + np.mean(r22), + r2_score(y_true, y_pred, multioutput="uniform_average", force_finite=False), + ) + evs = explained_variance_score(y_true, y_pred, multioutput="raw_values") assert_array_almost_equal(evs, [1.0, -3.0], decimal=2) assert np.mean(evs) == explained_variance_score(y_true, y_pred) + evs2 = explained_variance_score( + y_true, y_pred, multioutput="raw_values", force_finite=False + ) + assert_array_almost_equal(evs2, [np.nan, -3.0], decimal=2) + assert_almost_equal( + np.mean(evs2), explained_variance_score(y_true, y_pred, force_finite=False) + ) # Handling msle separately as it does not accept negative inputs. y_true = np.array([[0.5, 1], [1, 2], [7, 6]]) @@ -332,6 +410,9 @@ def test_regression_custom_weights(): mapew = mean_absolute_percentage_error(y_true, y_pred, multioutput=[0.4, 0.6]) rw = r2_score(y_true, y_pred, multioutput=[0.4, 0.6]) evsw = explained_variance_score(y_true, y_pred, multioutput=[0.4, 0.6]) + evsw2 = explained_variance_score( + y_true, y_pred, multioutput=[0.4, 0.6], force_finite=False + ) assert_almost_equal(msew, 0.39, decimal=2) assert_almost_equal(rmsew, 0.59, decimal=2) @@ -339,6 +420,7 @@ def test_regression_custom_weights(): assert_almost_equal(mapew, 0.1668, decimal=2) assert_almost_equal(rw, 0.94, decimal=2) assert_almost_equal(evsw, 0.94, decimal=2) + assert_almost_equal(evsw2, 0.94, decimal=2) # Handling msle separately as it does not accept negative inputs. y_true = np.array([[0.5, 1], [1, 2], [7, 6]])
[ { "path": "doc/modules/model_evaluation.rst", "old_path": "a/doc/modules/model_evaluation.rst", "new_path": "b/doc/modules/model_evaluation.rst", "metadata": "diff --git a/doc/modules/model_evaluation.rst b/doc/modules/model_evaluation.rst\nindex 730b094581276..079313a45c3d0 100644\n--- a/doc/modules/model_evaluation.rst\n+++ b/doc/modules/model_evaluation.rst\n@@ -2005,6 +2005,19 @@ then the explained variance is estimated as follow:\n \n The best possible score is 1.0, lower values are worse.\n \n+Note: when the prediction residuals have zero mean, the Explained Variance\n+score and the :ref:`r2_score` are identical.\n+\n+In the particular case where the true target is constant, the Explained\n+Variance score is not finite: it is either ``NaN`` (perfect predictions) or\n+``-Inf`` (imperfect predictions). Such non-finite scores may prevent correct\n+model optimization such as grid-search cross-validation to be performed\n+correctly. For this reason the default behaviour of\n+:func:`explained_variance_score` is to replace them with 1.0 (perfect\n+predictions) or 0.0 (imperfect predictions). You can set the ``force_finite``\n+parameter to ``False`` to prevent this fix from happening and fallback on the\n+original Explained Variance score.\n+\n Here is a small example of usage of the :func:`explained_variance_score`\n function::\n \n@@ -2019,6 +2032,18 @@ function::\n array([0.967..., 1. ])\n >>> explained_variance_score(y_true, y_pred, multioutput=[0.3, 0.7])\n 0.990...\n+ >>> y_true = [-2, -2, -2]\n+ >>> y_pred = [-2, -2, -2]\n+ >>> explained_variance_score(y_true, y_pred)\n+ 1.0\n+ >>> explained_variance_score(y_true, y_pred, force_finite=False)\n+ nan\n+ >>> y_true = [-2, -2, -2]\n+ >>> y_pred = [-2, -2, -2 + 1e-8]\n+ >>> explained_variance_score(y_true, y_pred)\n+ 0.0\n+ >>> explained_variance_score(y_true, y_pred, force_finite=False)\n+ -inf\n \n .. _max_error:\n \n@@ -2241,8 +2266,11 @@ predicted by the model, through the proportion of explained variance.\n As such variance is dataset dependent, R² may not be meaningfully comparable\n across different datasets. Best possible score is 1.0 and it can be negative\n (because the model can be arbitrarily worse). A constant model that always\n-predicts the expected value of y, disregarding the input features, would get a\n-R² score of 0.0.\n+predicts the expected (average) value of y, disregarding the input features,\n+would get an :math:`R^2` score of 0.0.\n+\n+Note: when the prediction residuals have zero mean, the :math:`R^2` score and\n+the :ref:`explained_variance_score` are identical.\n \n If :math:`\\hat{y}_i` is the predicted value of the :math:`i`-th sample\n and :math:`y_i` is the corresponding true value for total :math:`n` samples,\n@@ -2257,6 +2285,14 @@ where :math:`\\bar{y} = \\frac{1}{n} \\sum_{i=1}^{n} y_i` and :math:`\\sum_{i=1}^{n}\n Note that :func:`r2_score` calculates unadjusted R² without correcting for\n bias in sample variance of y.\n \n+In the particular case where the true target is constant, the :math:`R^2` score is\n+not finite: it is either ``NaN`` (perfect predictions) or ``-Inf`` (imperfect\n+predictions). Such non-finite scores may prevent correct model optimization\n+such as grid-search cross-validation to be performed correctly. For this reason\n+the default behaviour of :func:`r2_score` is to replace them with 1.0 (perfect\n+predictions) or 0.0 (imperfect predictions). If ``force_finite``\n+is set to ``False``, this score falls back on the original :math:`R^2` definition.\n+\n Here is a small example of usage of the :func:`r2_score` function::\n \n >>> from sklearn.metrics import r2_score\n@@ -2276,7 +2312,18 @@ Here is a small example of usage of the :func:`r2_score` function::\n array([0.965..., 0.908...])\n >>> r2_score(y_true, y_pred, multioutput=[0.3, 0.7])\n 0.925...\n-\n+ >>> y_true = [-2, -2, -2]\n+ >>> y_pred = [-2, -2, -2]\n+ >>> r2_score(y_true, y_pred)\n+ 1.0\n+ >>> r2_score(y_true, y_pred, force_finite=False)\n+ nan\n+ >>> y_true = [-2, -2, -2]\n+ >>> y_pred = [-2, -2, -2 + 1e-8]\n+ >>> r2_score(y_true, y_pred)\n+ 0.0\n+ >>> r2_score(y_true, y_pred, force_finite=False)\n+ -inf\n \n .. topic:: Example:\n \n" }, { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 5d49a6fd281c7..d67d08ac45f6b 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -288,6 +288,12 @@ Changelog\n :mod:`sklearn.metrics`\n ......................\n \n+- |Feature| :func:`r2_score` and :func:`explained_variance_score` have a new\n+ `force_finite` parameter. Setting this parameter to `False` will return the\n+ actual non-finite score in case of perfect predictions or constant `y_true`,\n+ instead of the finite approximation (`1.0` and `0.0` respectively) currently\n+ returned by default. :pr:`17266` by :user:`Sylvain Marié <smarie>`.\n+\n - |API| :class:`metrics.DistanceMetric` has been moved from\n :mod:`sklearn.neighbors` to :mod:`sklearn.metric`.\n Using `neighbors.DistanceMetric` for imports is still valid for\n" } ]
1.01
f87b5ae223b01414a83a610246a40dae2356a039
[ "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.5-normal]", "sklearn/metrics/tests/test_regression.py::test__check_reg_targets_exception", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.05-normal]", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.5-uniform]", "sklearn/metrics/tests/test_regression.py::test_dummy_quantile_parameter_tuning", "sklearn/metrics/tests/test_regression.py::test_tweedie_deviance_continuity", "sklearn/metrics/tests/test_regression.py::test_mean_absolute_percentage_error", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.75-uniform]", "sklearn/metrics/tests/test_regression.py::test_regression_single_sample[r2_score]", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.5-exponential]", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.75-exponential]", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.75-lognormal]", "sklearn/metrics/tests/test_regression.py::test_regression_single_sample[d2_tweedie_score]", "sklearn/metrics/tests/test_regression.py::test__check_reg_targets", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.05-exponential]", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.05-lognormal]", "sklearn/metrics/tests/test_regression.py::test_deprecation_positional_arguments_mape", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.75-normal]", "sklearn/metrics/tests/test_regression.py::test_mean_squared_error_multioutput_raw_value_squared", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.05-uniform]", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.5-lognormal]" ]
[ "sklearn/metrics/tests/test_regression.py::test_regression_multioutput_array", "sklearn/metrics/tests/test_regression.py::test_regression_metrics_at_limits", "sklearn/metrics/tests/test_regression.py::test_regression_custom_weights", "sklearn/metrics/tests/test_regression.py::test_regression_metrics", "sklearn/metrics/tests/test_regression.py::test_multioutput_regression" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/modules/model_evaluation.rst", "old_path": "a/doc/modules/model_evaluation.rst", "new_path": "b/doc/modules/model_evaluation.rst", "metadata": "diff --git a/doc/modules/model_evaluation.rst b/doc/modules/model_evaluation.rst\nindex 730b094581276..079313a45c3d0 100644\n--- a/doc/modules/model_evaluation.rst\n+++ b/doc/modules/model_evaluation.rst\n@@ -2005,6 +2005,19 @@ then the explained variance is estimated as follow:\n \n The best possible score is 1.0, lower values are worse.\n \n+Note: when the prediction residuals have zero mean, the Explained Variance\n+score and the :ref:`r2_score` are identical.\n+\n+In the particular case where the true target is constant, the Explained\n+Variance score is not finite: it is either ``NaN`` (perfect predictions) or\n+``-Inf`` (imperfect predictions). Such non-finite scores may prevent correct\n+model optimization such as grid-search cross-validation to be performed\n+correctly. For this reason the default behaviour of\n+:func:`explained_variance_score` is to replace them with 1.0 (perfect\n+predictions) or 0.0 (imperfect predictions). You can set the ``force_finite``\n+parameter to ``False`` to prevent this fix from happening and fallback on the\n+original Explained Variance score.\n+\n Here is a small example of usage of the :func:`explained_variance_score`\n function::\n \n@@ -2019,6 +2032,18 @@ function::\n array([0.967..., 1. ])\n >>> explained_variance_score(y_true, y_pred, multioutput=[0.3, 0.7])\n 0.990...\n+ >>> y_true = [-2, -2, -2]\n+ >>> y_pred = [-2, -2, -2]\n+ >>> explained_variance_score(y_true, y_pred)\n+ 1.0\n+ >>> explained_variance_score(y_true, y_pred, force_finite=False)\n+ nan\n+ >>> y_true = [-2, -2, -2]\n+ >>> y_pred = [-2, -2, -2 + 1e-8]\n+ >>> explained_variance_score(y_true, y_pred)\n+ 0.0\n+ >>> explained_variance_score(y_true, y_pred, force_finite=False)\n+ -inf\n \n .. _max_error:\n \n@@ -2241,8 +2266,11 @@ predicted by the model, through the proportion of explained variance.\n As such variance is dataset dependent, R² may not be meaningfully comparable\n across different datasets. Best possible score is 1.0 and it can be negative\n (because the model can be arbitrarily worse). A constant model that always\n-predicts the expected value of y, disregarding the input features, would get a\n-R² score of 0.0.\n+predicts the expected (average) value of y, disregarding the input features,\n+would get an :math:`R^2` score of 0.0.\n+\n+Note: when the prediction residuals have zero mean, the :math:`R^2` score and\n+the :ref:`explained_variance_score` are identical.\n \n If :math:`\\hat{y}_i` is the predicted value of the :math:`i`-th sample\n and :math:`y_i` is the corresponding true value for total :math:`n` samples,\n@@ -2257,6 +2285,14 @@ where :math:`\\bar{y} = \\frac{1}{n} \\sum_{i=1}^{n} y_i` and :math:`\\sum_{i=1}^{n}\n Note that :func:`r2_score` calculates unadjusted R² without correcting for\n bias in sample variance of y.\n \n+In the particular case where the true target is constant, the :math:`R^2` score is\n+not finite: it is either ``NaN`` (perfect predictions) or ``-Inf`` (imperfect\n+predictions). Such non-finite scores may prevent correct model optimization\n+such as grid-search cross-validation to be performed correctly. For this reason\n+the default behaviour of :func:`r2_score` is to replace them with 1.0 (perfect\n+predictions) or 0.0 (imperfect predictions). If ``force_finite``\n+is set to ``False``, this score falls back on the original :math:`R^2` definition.\n+\n Here is a small example of usage of the :func:`r2_score` function::\n \n >>> from sklearn.metrics import r2_score\n@@ -2276,7 +2312,18 @@ Here is a small example of usage of the :func:`r2_score` function::\n array([0.965..., 0.908...])\n >>> r2_score(y_true, y_pred, multioutput=[0.3, 0.7])\n 0.925...\n-\n+ >>> y_true = [-2, -2, -2]\n+ >>> y_pred = [-2, -2, -2]\n+ >>> r2_score(y_true, y_pred)\n+ 1.0\n+ >>> r2_score(y_true, y_pred, force_finite=False)\n+ nan\n+ >>> y_true = [-2, -2, -2]\n+ >>> y_pred = [-2, -2, -2 + 1e-8]\n+ >>> r2_score(y_true, y_pred)\n+ 0.0\n+ >>> r2_score(y_true, y_pred, force_finite=False)\n+ -inf\n \n .. topic:: Example:\n \n" }, { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 5d49a6fd281c7..d67d08ac45f6b 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -288,6 +288,12 @@ Changelog\n :mod:`sklearn.metrics`\n ......................\n \n+- |Feature| :func:`r2_score` and :func:`explained_variance_score` have a new\n+ `force_finite` parameter. Setting this parameter to `False` will return the\n+ actual non-finite score in case of perfect predictions or constant `y_true`,\n+ instead of the finite approximation (`1.0` and `0.0` respectively) currently\n+ returned by default. :pr:`<PRID>` by :user:`<NAME>`.\n+\n - |API| :class:`metrics.DistanceMetric` has been moved from\n :mod:`sklearn.neighbors` to :mod:`sklearn.metric`.\n Using `neighbors.DistanceMetric` for imports is still valid for\n" } ]
diff --git a/doc/modules/model_evaluation.rst b/doc/modules/model_evaluation.rst index 730b094581276..079313a45c3d0 100644 --- a/doc/modules/model_evaluation.rst +++ b/doc/modules/model_evaluation.rst @@ -2005,6 +2005,19 @@ then the explained variance is estimated as follow: The best possible score is 1.0, lower values are worse. +Note: when the prediction residuals have zero mean, the Explained Variance +score and the :ref:`r2_score` are identical. + +In the particular case where the true target is constant, the Explained +Variance score is not finite: it is either ``NaN`` (perfect predictions) or +``-Inf`` (imperfect predictions). Such non-finite scores may prevent correct +model optimization such as grid-search cross-validation to be performed +correctly. For this reason the default behaviour of +:func:`explained_variance_score` is to replace them with 1.0 (perfect +predictions) or 0.0 (imperfect predictions). You can set the ``force_finite`` +parameter to ``False`` to prevent this fix from happening and fallback on the +original Explained Variance score. + Here is a small example of usage of the :func:`explained_variance_score` function:: @@ -2019,6 +2032,18 @@ function:: array([0.967..., 1. ]) >>> explained_variance_score(y_true, y_pred, multioutput=[0.3, 0.7]) 0.990... + >>> y_true = [-2, -2, -2] + >>> y_pred = [-2, -2, -2] + >>> explained_variance_score(y_true, y_pred) + 1.0 + >>> explained_variance_score(y_true, y_pred, force_finite=False) + nan + >>> y_true = [-2, -2, -2] + >>> y_pred = [-2, -2, -2 + 1e-8] + >>> explained_variance_score(y_true, y_pred) + 0.0 + >>> explained_variance_score(y_true, y_pred, force_finite=False) + -inf .. _max_error: @@ -2241,8 +2266,11 @@ predicted by the model, through the proportion of explained variance. As such variance is dataset dependent, R² may not be meaningfully comparable across different datasets. Best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always -predicts the expected value of y, disregarding the input features, would get a -R² score of 0.0. +predicts the expected (average) value of y, disregarding the input features, +would get an :math:`R^2` score of 0.0. + +Note: when the prediction residuals have zero mean, the :math:`R^2` score and +the :ref:`explained_variance_score` are identical. If :math:`\hat{y}_i` is the predicted value of the :math:`i`-th sample and :math:`y_i` is the corresponding true value for total :math:`n` samples, @@ -2257,6 +2285,14 @@ where :math:`\bar{y} = \frac{1}{n} \sum_{i=1}^{n} y_i` and :math:`\sum_{i=1}^{n} Note that :func:`r2_score` calculates unadjusted R² without correcting for bias in sample variance of y. +In the particular case where the true target is constant, the :math:`R^2` score is +not finite: it is either ``NaN`` (perfect predictions) or ``-Inf`` (imperfect +predictions). Such non-finite scores may prevent correct model optimization +such as grid-search cross-validation to be performed correctly. For this reason +the default behaviour of :func:`r2_score` is to replace them with 1.0 (perfect +predictions) or 0.0 (imperfect predictions). If ``force_finite`` +is set to ``False``, this score falls back on the original :math:`R^2` definition. + Here is a small example of usage of the :func:`r2_score` function:: >>> from sklearn.metrics import r2_score @@ -2276,7 +2312,18 @@ Here is a small example of usage of the :func:`r2_score` function:: array([0.965..., 0.908...]) >>> r2_score(y_true, y_pred, multioutput=[0.3, 0.7]) 0.925... - + >>> y_true = [-2, -2, -2] + >>> y_pred = [-2, -2, -2] + >>> r2_score(y_true, y_pred) + 1.0 + >>> r2_score(y_true, y_pred, force_finite=False) + nan + >>> y_true = [-2, -2, -2] + >>> y_pred = [-2, -2, -2 + 1e-8] + >>> r2_score(y_true, y_pred) + 0.0 + >>> r2_score(y_true, y_pred, force_finite=False) + -inf .. topic:: Example: diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 5d49a6fd281c7..d67d08ac45f6b 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -288,6 +288,12 @@ Changelog :mod:`sklearn.metrics` ...................... +- |Feature| :func:`r2_score` and :func:`explained_variance_score` have a new + `force_finite` parameter. Setting this parameter to `False` will return the + actual non-finite score in case of perfect predictions or constant `y_true`, + instead of the finite approximation (`1.0` and `0.0` respectively) currently + returned by default. :pr:`<PRID>` by :user:`<NAME>`. + - |API| :class:`metrics.DistanceMetric` has been moved from :mod:`sklearn.neighbors` to :mod:`sklearn.metric`. Using `neighbors.DistanceMetric` for imports is still valid for
scikit-learn/scikit-learn
scikit-learn__scikit-learn-21078
https://github.com/scikit-learn/scikit-learn/pull/21078
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index a473908d8f1e7..cc1af2f237bf9 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -61,6 +61,13 @@ Changelog error when 'min_idf' or 'max_idf' are floating-point numbers greater than 1. :pr:`20752` by :user:`Alek Lefebvre <AlekLefebvre>`. +:mod:`sklearn.impute` +..................... + +- |API| Adds :meth:`get_feature_names_out` to :class:`impute.SimpleImputer`, + :class:`impute.KNNImputer`, :class:`impute.IterativeImputer`, and + :class:`impute.MissingIndicator`. :pr:`21078` by `Thomas Fan`_. + :mod:`sklearn.linear_model` ........................... diff --git a/sklearn/impute/_base.py b/sklearn/impute/_base.py index 32ec1624f0c2f..c97a8d24d4578 100644 --- a/sklearn/impute/_base.py +++ b/sklearn/impute/_base.py @@ -15,6 +15,7 @@ from ..utils.sparsefuncs import _get_median from ..utils.validation import check_is_fitted from ..utils.validation import FLOAT_DTYPES +from ..utils.validation import _check_feature_names_in from ..utils._mask import _get_mask from ..utils import is_scalar_nan @@ -113,6 +114,13 @@ def _concatenate_indicator(self, X_imputed, X_indicator): return hstack((X_imputed, X_indicator)) + def _concatenate_indicator_feature_names_out(self, names, input_features): + if not self.add_indicator: + return names + + indicator_names = self.indicator_.get_feature_names_out(input_features) + return np.concatenate([names, indicator_names]) + def _more_tags(self): return {"allow_nan": is_scalar_nan(self.missing_values)} @@ -596,6 +604,30 @@ def inverse_transform(self, X): X_original[full_mask] = self.missing_values return X_original + def get_feature_names_out(self, input_features=None): + """Get output feature names for transformation. + + Parameters + ---------- + input_features : array-like of str or None, default=None + Input features. + + - If `input_features` is `None`, then `feature_names_in_` is + used as feature names in. If `feature_names_in_` is not defined, + then names are generated: `[x0, x1, ..., x(n_features_in_)]`. + - If `input_features` is an array-like, then `input_features` must + match `feature_names_in_` if `feature_names_in_` is defined. + + Returns + ------- + feature_names_out : ndarray of str objects + Transformed feature names. + """ + input_features = _check_feature_names_in(self, input_features) + non_missing_mask = np.logical_not(_get_mask(self.statistics_, np.nan)) + names = input_features[non_missing_mask] + return self._concatenate_indicator_feature_names_out(names, input_features) + class MissingIndicator(TransformerMixin, BaseEstimator): """Binary indicators for missing values. @@ -922,6 +954,35 @@ def fit_transform(self, X, y=None): return imputer_mask + def get_feature_names_out(self, input_features=None): + """Get output feature names for transformation. + + Parameters + ---------- + input_features : array-like of str or None, default=None + Input features. + + - If `input_features` is `None`, then `feature_names_in_` is + used as feature names in. If `feature_names_in_` is not defined, + then names are generated: `[x0, x1, ..., x(n_features_in_)]`. + - If `input_features` is an array-like, then `input_features` must + match `feature_names_in_` if `feature_names_in_` is defined. + + Returns + ------- + feature_names_out : ndarray of str objects + Transformed feature names. + """ + input_features = _check_feature_names_in(self, input_features) + prefix = self.__class__.__name__.lower() + return np.asarray( + [ + f"{prefix}_{feature_name}" + for feature_name in input_features[self.features_] + ], + dtype=object, + ) + def _more_tags(self): return { "allow_nan": True, diff --git a/sklearn/impute/_iterative.py b/sklearn/impute/_iterative.py index 321c1f537520d..908ab5c9efeb1 100644 --- a/sklearn/impute/_iterative.py +++ b/sklearn/impute/_iterative.py @@ -10,6 +10,7 @@ from ..preprocessing import normalize from ..utils import check_array, check_random_state, _safe_indexing, is_scalar_nan from ..utils.validation import FLOAT_DTYPES, check_is_fitted +from ..utils.validation import _check_feature_names_in from ..utils._mask import _get_mask from ._base import _BaseImputer @@ -774,3 +775,26 @@ def fit(self, X, y=None): """ self.fit_transform(X) return self + + def get_feature_names_out(self, input_features=None): + """Get output feature names for transformation. + + Parameters + ---------- + input_features : array-like of str or None, default=None + Input features. + + - If `input_features` is `None`, then `feature_names_in_` is + used as feature names in. If `feature_names_in_` is not defined, + then names are generated: `[x0, x1, ..., x(n_features_in_)]`. + - If `input_features` is an array-like, then `input_features` must + match `feature_names_in_` if `feature_names_in_` is defined. + + Returns + ------- + feature_names_out : ndarray of str objects + Transformed feature names. + """ + input_features = _check_feature_names_in(self, input_features) + names = self.initial_imputer_.get_feature_names_out(input_features) + return self._concatenate_indicator_feature_names_out(names, input_features) diff --git a/sklearn/impute/_knn.py b/sklearn/impute/_knn.py index c2bd1410e8ecd..ad7e3537d445f 100644 --- a/sklearn/impute/_knn.py +++ b/sklearn/impute/_knn.py @@ -13,6 +13,7 @@ from ..utils import is_scalar_nan from ..utils._mask import _get_mask from ..utils.validation import check_is_fitted +from ..utils.validation import _check_feature_names_in class KNNImputer(_BaseImputer): @@ -206,6 +207,7 @@ def fit(self, X, y=None): _check_weights(self.weights) self._fit_X = X self._mask_fit_X = _get_mask(self._fit_X, self.missing_values) + self._valid_mask = ~np.all(self._mask_fit_X, axis=0) super()._fit_indicator(self._mask_fit_X) @@ -242,7 +244,7 @@ def transform(self, X): mask = _get_mask(X, self.missing_values) mask_fit_X = self._mask_fit_X - valid_mask = ~np.all(mask_fit_X, axis=0) + valid_mask = self._valid_mask X_indicator = super()._transform_indicator(mask) @@ -327,3 +329,26 @@ def process_chunk(dist_chunk, start): pass return super()._concatenate_indicator(X[:, valid_mask], X_indicator) + + def get_feature_names_out(self, input_features=None): + """Get output feature names for transformation. + + Parameters + ---------- + input_features : array-like of str or None, default=None + Input features. + + - If `input_features` is `None`, then `feature_names_in_` is + used as feature names in. If `feature_names_in_` is not defined, + then names are generated: `[x0, x1, ..., x(n_features_in_)]`. + - If `input_features` is an array-like, then `input_features` must + match `feature_names_in_` if `feature_names_in_` is defined. + + Returns + ------- + feature_names_out : ndarray of str objects + Transformed feature names. + """ + input_features = _check_feature_names_in(self, input_features) + names = input_features[self._valid_mask] + return self._concatenate_indicator_feature_names_out(names, input_features)
diff --git a/sklearn/impute/tests/test_common.py b/sklearn/impute/tests/test_common.py index c35245ac8c253..0c13547ce9b4c 100644 --- a/sklearn/impute/tests/test_common.py +++ b/sklearn/impute/tests/test_common.py @@ -14,7 +14,7 @@ from sklearn.impute import SimpleImputer -IMPUTERS = [IterativeImputer(), KNNImputer(), SimpleImputer()] +IMPUTERS = [IterativeImputer(tol=0.1), KNNImputer(), SimpleImputer()] SPARSE_IMPUTERS = [SimpleImputer()] @@ -122,3 +122,42 @@ def test_imputers_pandas_na_integer_array_support(imputer, add_indicator): X_trans = imputer.fit_transform(X_df) assert_allclose(X_trans_expected, X_trans) + + [email protected]("imputer", IMPUTERS, ids=lambda x: x.__class__.__name__) [email protected]("add_indicator", [True, False]) +def test_imputers_feature_names_out_pandas(imputer, add_indicator): + """Check feature names out for imputers.""" + pd = pytest.importorskip("pandas") + marker = np.nan + imputer = imputer.set_params(add_indicator=add_indicator, missing_values=marker) + + X = np.array( + [ + [marker, 1, 5, 3, marker, 1], + [2, marker, 1, 4, marker, 2], + [6, 3, 7, marker, marker, 3], + [1, 2, 9, 8, marker, 4], + ] + ) + X_df = pd.DataFrame(X, columns=["a", "b", "c", "d", "e", "f"]) + imputer.fit(X_df) + + names = imputer.get_feature_names_out() + + if add_indicator: + expected_names = [ + "a", + "b", + "c", + "d", + "f", + "missingindicator_a", + "missingindicator_b", + "missingindicator_d", + "missingindicator_e", + ] + assert_array_equal(expected_names, names) + else: + expected_names = ["a", "b", "c", "d", "f"] + assert_array_equal(expected_names, names) diff --git a/sklearn/impute/tests/test_impute.py b/sklearn/impute/tests/test_impute.py index 2534f94116b57..9a4da4a9230a0 100644 --- a/sklearn/impute/tests/test_impute.py +++ b/sklearn/impute/tests/test_impute.py @@ -1493,3 +1493,22 @@ def test_most_frequent(expected, array, dtype, extra_value, n_repeat): assert expected == _most_frequent( np.array(array, dtype=dtype), extra_value, n_repeat ) + + +def test_missing_indicator_feature_names_out(): + """Check that missing indicator return the feature names with a prefix.""" + pd = pytest.importorskip("pandas") + + missing_values = np.nan + X = pd.DataFrame( + [ + [missing_values, missing_values, 1, missing_values], + [4, missing_values, 2, 10], + ], + columns=["a", "b", "c", "d"], + ) + + indicator = MissingIndicator(missing_values=missing_values).fit(X) + feature_names = indicator.get_feature_names_out() + expected_names = ["missingindicator_a", "missingindicator_b", "missingindicator_d"] + assert_array_equal(expected_names, feature_names) diff --git a/sklearn/tests/test_common.py b/sklearn/tests/test_common.py index 4f6818081c67d..139a2bfb9702a 100644 --- a/sklearn/tests/test_common.py +++ b/sklearn/tests/test_common.py @@ -365,7 +365,6 @@ def test_pandas_column_name_consistency(estimator): "decomposition", "discriminant_analysis", "ensemble", - "impute", "isotonic", "kernel_approximation", "preprocessing",
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex a473908d8f1e7..cc1af2f237bf9 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -61,6 +61,13 @@ Changelog\n error when 'min_idf' or 'max_idf' are floating-point numbers greater than 1.\n :pr:`20752` by :user:`Alek Lefebvre <AlekLefebvre>`.\n \n+:mod:`sklearn.impute`\n+.....................\n+\n+- |API| Adds :meth:`get_feature_names_out` to :class:`impute.SimpleImputer`,\n+ :class:`impute.KNNImputer`, :class:`impute.IterativeImputer`, and\n+ :class:`impute.MissingIndicator`. :pr:`21078` by `Thomas Fan`_.\n+\n :mod:`sklearn.linear_model`\n ...........................\n \n" } ]
1.01
7601f87b7a8faaf0d3bd14add9a050b127cbb865
[ "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[all-3-features_indices1-0-int32-array]", "sklearn/impute/tests/test_impute.py::test_most_frequent[1-array5-int-10-1]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[all-3-features_indices1-nan-float64-csc_matrix]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_min_max_array_like[lists]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_no_missing", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[nan-coo_matrix-auto]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_imputation_order[random]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_imputation_order[descending]", "sklearn/impute/tests/test_impute.py::test_imputation_deletion_warning[mean]", "sklearn/impute/tests/test_common.py::test_imputers_add_indicator[imputer1--1]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_verbose", "sklearn/impute/tests/test_common.py::test_imputers_add_indicator[imputer2--1]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_min_max_array_like[scalars]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[all-3-features_indices1--1-int32-bsr_matrix]", "sklearn/impute/tests/test_impute.py::test_imputation_shape[mean]", "sklearn/impute/tests/test_impute.py::test_imputation_error_sparse_0[constant]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[missing-only-3-features_indices0--1-int32-array]", "sklearn/impute/tests/test_impute.py::test_imputation_most_frequent_pandas[object]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_no_explicit_zeros", "sklearn/impute/tests/test_common.py::test_imputers_add_indicator[imputer2-0]", "sklearn/impute/tests/test_common.py::test_imputers_add_indicator[imputer0-nan]", "sklearn/impute/tests/test_impute.py::test_imputation_error_sparse_0[median]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[nan-array-True]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_early_stopping", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_min_max_array_like[None-default]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[missing-only-3-features_indices0--1-int32-lil_matrix]", "sklearn/impute/tests/test_impute.py::test_imputation_constant_pandas[object]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[missing-only-3-features_indices0--1-int32-csc_matrix]", "sklearn/impute/tests/test_impute.py::test_simple_imputation_add_indicator_sparse_matrix[coo_matrix]", "sklearn/impute/tests/test_impute.py::test_imputation_const_mostf_error_invalid_types[dtype2-most_frequent]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[all-3-features_indices1-nan-float64-array]", "sklearn/impute/tests/test_impute.py::test_simple_imputation_inverse_transform_exceptions[-1]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_error_param[1--0.001-ValueError-should be a non-negative float]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_dont_set_random_state[1-rs_imputer2]", "sklearn/impute/tests/test_common.py::test_imputers_pandas_na_integer_array_support[True-imputer1]", "sklearn/impute/tests/test_impute.py::test_imputation_const_mostf_error_invalid_types[dtype1-most_frequent]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_string", "sklearn/impute/tests/test_common.py::test_imputers_add_indicator[imputer0-0]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[0-array-True]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[nan-csr_matrix-auto]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[nan-array-False]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[all-3-features_indices1-nan-float64-lil_matrix]", "sklearn/impute/tests/test_impute.py::test_simple_imputation_string_list[constant-missing_value]", "sklearn/impute/tests/test_impute.py::test_most_frequent[most_frequent_value-array1-object-extra_value-1]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_one_feature[X0]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_dont_set_random_state[rs_estimator2-None]", "sklearn/impute/tests/test_impute.py::test_simple_imputation_add_indicator_sparse_matrix[csr_matrix]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_clip_truncnorm", "sklearn/impute/tests/test_impute.py::test_imputation_error_sparse_0[mean]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_estimators[estimator3]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[all-3-features_indices1--1-int32-csc_matrix]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_with_imputer[X0-a-X_trans_exp0]", "sklearn/impute/tests/test_common.py::test_imputers_pandas_na_integer_array_support[True-imputer0]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_catch_min_max_error[min_value2-max_value2-_value' should be of shape]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_one_feature[X1]", "sklearn/impute/tests/test_impute.py::test_imputation_constant_object[nan]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_additive_matrix", "sklearn/impute/tests/test_impute.py::test_simple_imputation_add_indicator_sparse_matrix[bsr_matrix]", "sklearn/impute/tests/test_impute.py::test_imputation_constant_object[0]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[nan-csc_matrix-True]", "sklearn/impute/tests/test_common.py::test_imputers_add_indicator_sparse[imputer0--1]", "sklearn/impute/tests/test_impute.py::test_inconsistent_dtype_X_missing_values[-1--1-types are expected to be both numerical.-IterativeImputer]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_dont_set_random_state[1-None]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[all-3-features_indices1--1-int32-array]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_error[X_fit3-X_trans3-params3-MissingIndicator does not support data with dtype]", "sklearn/impute/tests/test_impute.py::test_imputation_order[ascending-idx_order0]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[nan-csr_matrix-False]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[missing-only-3-features_indices0--1-int32-csr_matrix]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_raise_on_sparse_with_missing_0[bsr_matrix]", "sklearn/impute/tests/test_impute.py::test_imputer_without_indicator[SimpleImputer]", "sklearn/impute/tests/test_impute.py::test_simple_imputation_inverse_transform[-1]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[missing-only-3-features_indices0-nan-float64-array]", "sklearn/impute/tests/test_common.py::test_imputation_missing_value_in_test_array[imputer0]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_min_max_array_like_imputation[Scalar-vs-vector]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[nan-lil_matrix-False]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_error_param[-1-0.001-ValueError-should be a positive integer]", "sklearn/impute/tests/test_impute.py::test_imputation_mean_median_error_invalid_type[str-median]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_estimators[estimator4]", "sklearn/impute/tests/test_impute.py::test_simple_imputation_inverse_transform[nan]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[all-3-features_indices1--1-int32-coo_matrix]", "sklearn/impute/tests/test_impute.py::test_imputation_mean_median", "sklearn/impute/tests/test_impute.py::test_imputation_shape[median]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_dont_set_random_state[1-1]", "sklearn/impute/tests/test_impute.py::test_imputation_order[descending-idx_order1]", "sklearn/impute/tests/test_common.py::test_imputers_pandas_na_integer_array_support[True-imputer2]", "sklearn/impute/tests/test_impute.py::test_imputation_most_frequent_objects[NAN]", "sklearn/impute/tests/test_common.py::test_imputation_missing_value_in_test_array[imputer2]", "sklearn/impute/tests/test_impute.py::test_imputation_mean_median_error_invalid_type[object-mean]", "sklearn/impute/tests/test_impute.py::test_inconsistent_dtype_X_missing_values[-1--1-types are expected to be both numerical.-SimpleImputer]", "sklearn/impute/tests/test_common.py::test_imputers_pandas_na_integer_array_support[False-imputer1]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[missing-only-3-features_indices0-nan-float64-lil_matrix]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_transform_recovery[3]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_truncated_normal_posterior", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_catch_min_max_error[inf--inf-min_value >= max_value.]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_missing_at_transform[most_frequent]", "sklearn/impute/tests/test_impute.py::test_imputation_const_mostf_error_invalid_types[str-most_frequent]", "sklearn/impute/tests/test_impute.py::test_imputation_const_mostf_error_invalid_types[dtype2-constant]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[missing-only-3-features_indices0-0-int32-array]", "sklearn/impute/tests/test_impute.py::test_imputation_constant_float[asarray]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[0-array-auto]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_all_missing", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_rank_one", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_skip_non_missing[False]", "sklearn/impute/tests/test_impute.py::test_imputation_most_frequent_objects[0]", "sklearn/impute/tests/test_impute.py::test_imputation_mean_median_error_invalid_type[None-median]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_with_imputer[X3-None-X_trans_exp3]", "sklearn/impute/tests/test_impute.py::test_imputation_constant_object[None]", "sklearn/impute/tests/test_impute.py::test_imputation_mean_median_error_invalid_type[object-median]", "sklearn/impute/tests/test_impute.py::test_imputation_mean_median_error_invalid_type_list_pandas[dataframe-median]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[missing-only-3-features_indices0-nan-float64-coo_matrix]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_raise_on_sparse_with_missing_0[lil_matrix]", "sklearn/impute/tests/test_impute.py::test_imputation_error_invalid_strategy[101]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_imputation_order[ascending]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_estimators[estimator1]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[nan-array-auto]", "sklearn/impute/tests/test_impute.py::test_imputation_constant_object[NAN]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_dont_set_random_state[rs_estimator2-rs_imputer2]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_min_max_array_like_imputation[None-vs-inf]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_imputation_order[arabic]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_skip_non_missing[True]", "sklearn/impute/tests/test_impute.py::test_imputation_copy", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_min_max_array_like[inf]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_imputation_order[roman]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[missing-only-3-features_indices0--1-int32-coo_matrix]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_missing_at_transform[median]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[nan-coo_matrix-True]", "sklearn/impute/tests/test_impute.py::test_imputation_mean_median_error_invalid_type_list_pandas[list-median]", "sklearn/impute/tests/test_common.py::test_imputation_missing_value_in_test_array[imputer1]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[all-3-features_indices1--1-int32-lil_matrix]", "sklearn/impute/tests/test_impute.py::test_most_frequent[a-array2-object-a-2]", "sklearn/impute/tests/test_impute.py::test_imputer_without_indicator[IterativeImputer]", "sklearn/impute/tests/test_impute.py::test_simple_imputation_add_indicator_sparse_matrix[csc_matrix]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_raise_on_sparse_with_missing_0[csr_matrix]", "sklearn/impute/tests/test_impute.py::test_imputation_most_frequent_objects[nan]", "sklearn/impute/tests/test_common.py::test_imputers_add_indicator[imputer0--1]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_with_imputer[X1-nan-X_trans_exp1]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_estimators[estimator2]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_catch_min_max_error[100-0-min_value >= max_value.]", "sklearn/impute/tests/test_common.py::test_imputers_add_indicator[imputer2-nan]", "sklearn/impute/tests/test_common.py::test_imputers_add_indicator[imputer1-nan]", "sklearn/impute/tests/test_impute.py::test_imputation_shape[most_frequent]", "sklearn/impute/tests/test_common.py::test_imputers_pandas_na_integer_array_support[False-imputer2]", "sklearn/impute/tests/test_impute.py::test_imputation_shape[constant]", "sklearn/impute/tests/test_impute.py::test_imputation_median_special_cases", "sklearn/impute/tests/test_impute.py::test_imputation_most_frequent_objects[None]", "sklearn/impute/tests/test_impute.py::test_inconsistent_dtype_X_missing_values[NaN-nan-Input contains NaN-IterativeImputer]", "sklearn/impute/tests/test_impute.py::test_imputation_error_sparse_0[most_frequent]", "sklearn/impute/tests/test_impute.py::test_imputation_deletion_warning[most_frequent]", "sklearn/impute/tests/test_impute.py::test_imputation_const_mostf_error_invalid_types[str-constant]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_error[X_fit1-X_trans1-params1-'features' has to be either 'missing-only' or 'all']", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[0-array-False]", "sklearn/impute/tests/test_impute.py::test_most_frequent[10-array6-int-10-2]", "sklearn/impute/tests/test_common.py::test_imputers_add_indicator[imputer1-0]", "sklearn/impute/tests/test_impute.py::test_imputation_mean_median_error_invalid_type[None-mean]", "sklearn/impute/tests/test_impute.py::test_imputation_most_frequent_pandas[category]", "sklearn/impute/tests/test_impute.py::test_inconsistent_dtype_X_missing_values[NaN-nan-Input contains NaN-SimpleImputer]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[nan-lil_matrix-True]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[missing-only-3-features_indices0-nan-float64-bsr_matrix]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_zero_iters", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_missing_at_transform[mean]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_transform_recovery[5]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_dont_set_random_state[None-None]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[all-3-features_indices1--1-int32-csr_matrix]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[all-3-features_indices1-nan-float64-coo_matrix]", "sklearn/impute/tests/test_impute.py::test_imputation_constant_error_invalid_type[1-0]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[nan-lil_matrix-auto]", "sklearn/impute/tests/test_impute.py::test_imputation_most_frequent", "sklearn/impute/tests/test_impute.py::test_missing_indicator_with_imputer[X2-nan-X_trans_exp2]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_estimators[None]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_dont_set_random_state[rs_estimator2-1]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[nan-csc_matrix-False]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[nan-csc_matrix-auto]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_dont_set_random_state[None-1]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[missing-only-3-features_indices0--1-int32-bsr_matrix]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[nan-coo_matrix-False]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[nan-csr_matrix-True]", "sklearn/impute/tests/test_impute.py::test_most_frequent[extra_value-array0-object-extra_value-2]", "sklearn/impute/tests/test_impute.py::test_imputation_deletion_warning[median]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[all-3-features_indices1-nan-float64-csr_matrix]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_error[X_fit0-X_trans0-params0-have missing values in transform but have no missing values in fit]", "sklearn/impute/tests/test_impute.py::test_imputation_const_mostf_error_invalid_types[dtype1-constant]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_clip", "sklearn/impute/tests/test_impute.py::test_imputation_mean_median_error_invalid_type_list_pandas[dataframe-mean]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_min_max_array_like[lists-with-inf]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_no_missing", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[missing-only-3-features_indices0-nan-float64-csc_matrix]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_raise_on_sparse_with_missing_0[coo_matrix]", "sklearn/impute/tests/test_impute.py::test_imputation_error_invalid_strategy[None]", "sklearn/impute/tests/test_common.py::test_imputers_add_indicator_sparse[imputer0-nan]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_dont_set_random_state[None-rs_imputer2]", "sklearn/impute/tests/test_impute.py::test_simple_imputation_add_indicator_sparse_matrix[lil_matrix]", "sklearn/impute/tests/test_impute.py::test_imputation_constant_pandas[category]", "sklearn/impute/tests/test_impute.py::test_imputation_constant_error_invalid_type[1.0-nan]", "sklearn/impute/tests/test_impute.py::test_simple_imputation_string_list[most_frequent-b]", "sklearn/impute/tests/test_impute.py::test_imputation_pipeline_grid_search", "sklearn/impute/tests/test_impute.py::test_imputation_constant_integer", "sklearn/impute/tests/test_impute.py::test_most_frequent[1-array7-int-10-2]", "sklearn/impute/tests/test_impute.py::test_imputation_most_frequent_objects[]", "sklearn/impute/tests/test_impute.py::test_simple_imputation_inverse_transform_exceptions[nan]", "sklearn/impute/tests/test_common.py::test_imputers_pandas_na_integer_array_support[False-imputer0]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[missing-only-3-features_indices0-nan-float64-csr_matrix]", "sklearn/impute/tests/test_impute.py::test_imputation_mean_median_error_invalid_type[str-mean]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_error[X_fit2-X_trans2-params2-'sparse' has to be a boolean or 'auto']", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[all-3-features_indices1-nan-float64-bsr_matrix]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_raise_on_sparse_with_missing_0[csc_matrix]", "sklearn/impute/tests/test_impute.py::test_imputation_constant_float[csr_matrix]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_transform_stochasticity", "sklearn/impute/tests/test_impute.py::test_most_frequent[min_value-array3-object-z-2]", "sklearn/impute/tests/test_impute.py::test_imputation_error_invalid_strategy[const]", "sklearn/impute/tests/test_impute.py::test_imputation_constant_object[]", "sklearn/impute/tests/test_impute.py::test_most_frequent[10-array4-int-10-2]", "sklearn/impute/tests/test_impute.py::test_imputation_mean_median_error_invalid_type_list_pandas[list-mean]" ]
[ "sklearn/impute/tests/test_common.py::test_imputers_feature_names_out_pandas[False-IterativeImputer]", "sklearn/impute/tests/test_common.py::test_imputers_feature_names_out_pandas[False-KNNImputer]", "sklearn/impute/tests/test_common.py::test_imputers_feature_names_out_pandas[True-SimpleImputer]", "sklearn/impute/tests/test_common.py::test_imputers_feature_names_out_pandas[True-IterativeImputer]", "sklearn/impute/tests/test_common.py::test_imputers_feature_names_out_pandas[False-SimpleImputer]", "sklearn/impute/tests/test_common.py::test_imputers_feature_names_out_pandas[True-KNNImputer]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_feature_names_out" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex a473908d8f1e7..cc1af2f237bf9 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -61,6 +61,13 @@ Changelog\n error when 'min_idf' or 'max_idf' are floating-point numbers greater than 1.\n :pr:`<PRID>` by :user:`<NAME>`.\n \n+:mod:`sklearn.impute`\n+.....................\n+\n+- |API| Adds :meth:`get_feature_names_out` to :class:`impute.SimpleImputer`,\n+ :class:`impute.KNNImputer`, :class:`impute.IterativeImputer`, and\n+ :class:`impute.MissingIndicator`. :pr:`<PRID>` by `<NAME>`_.\n+\n :mod:`sklearn.linear_model`\n ...........................\n \n" } ]
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index a473908d8f1e7..cc1af2f237bf9 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -61,6 +61,13 @@ Changelog error when 'min_idf' or 'max_idf' are floating-point numbers greater than 1. :pr:`<PRID>` by :user:`<NAME>`. +:mod:`sklearn.impute` +..................... + +- |API| Adds :meth:`get_feature_names_out` to :class:`impute.SimpleImputer`, + :class:`impute.KNNImputer`, :class:`impute.IterativeImputer`, and + :class:`impute.MissingIndicator`. :pr:`<PRID>` by `<NAME>`_. + :mod:`sklearn.linear_model` ...........................
scikit-learn/scikit-learn
scikit-learn__scikit-learn-21534
https://github.com/scikit-learn/scikit-learn/pull/21534
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 542636b1642f7..64e3c57a92214 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -117,6 +117,14 @@ Changelog backward compatibility, but this alias will be removed in 1.3. :pr:`21177` by :user:`Julien Jerphanion <jjerphan>`. +:mod:`sklearn.manifold` +....................... + +- |Enhancement| :func:`manifold.spectral_embedding` and + :class:`manifold.SpectralEmbedding` supports `np.float32` dtype and will + preserve this dtype. + :pr:`21534` by :user:`Andrew Knyazev <lobpcg>`. + :mod:`sklearn.model_selection` .............................. diff --git a/sklearn/manifold/_spectral_embedding.py b/sklearn/manifold/_spectral_embedding.py index e8cf61bfe783b..793f3958c64d2 100644 --- a/sklearn/manifold/_spectral_embedding.py +++ b/sklearn/manifold/_spectral_embedding.py @@ -315,8 +315,9 @@ def spectral_embedding( # problem. if not sparse.issparse(laplacian): warnings.warn("AMG works better for sparse matrices") - # lobpcg needs double precision floats - laplacian = check_array(laplacian, dtype=np.float64, accept_sparse=True) + laplacian = check_array( + laplacian, dtype=[np.float64, np.float32], accept_sparse=True + ) laplacian = _set_diag(laplacian, 1, norm_laplacian) # The Laplacian matrix is always singular, having at least one zero @@ -337,6 +338,7 @@ def spectral_embedding( # Create initial approximation X to eigenvectors X = random_state.rand(laplacian.shape[0], n_components + 1) X[:, 0] = dd.ravel() + X = X.astype(laplacian.dtype) _, diffusion_map = lobpcg(laplacian, X, M=M, tol=1.0e-5, largest=False) embedding = diffusion_map.T if norm_laplacian: @@ -346,8 +348,9 @@ def spectral_embedding( raise ValueError if eigen_solver == "lobpcg": - # lobpcg needs double precision floats - laplacian = check_array(laplacian, dtype=np.float64, accept_sparse=True) + laplacian = check_array( + laplacian, dtype=[np.float64, np.float32], accept_sparse=True + ) if n_nodes < 5 * n_components + 1: # see note above under arpack why lobpcg has problems with small # number of nodes @@ -366,6 +369,7 @@ def spectral_embedding( # approximation X to eigenvectors X = random_state.rand(laplacian.shape[0], n_components + 1) X[:, 0] = dd.ravel() + X = X.astype(laplacian.dtype) _, diffusion_map = lobpcg( laplacian, X, tol=1e-5, largest=False, maxiter=2000 )
diff --git a/sklearn/manifold/tests/test_spectral_embedding.py b/sklearn/manifold/tests/test_spectral_embedding.py index 8454accb7c59b..0f4bca2b07419 100644 --- a/sklearn/manifold/tests/test_spectral_embedding.py +++ b/sklearn/manifold/tests/test_spectral_embedding.py @@ -19,6 +19,15 @@ from sklearn.utils._testing import assert_array_almost_equal from sklearn.utils._testing import assert_array_equal +try: + from pyamg import smoothed_aggregation_solver # noqa + + pyamg_available = True +except ImportError: + pyamg_available = False +skip_if_no_pyamg = pytest.mark.skipif( + not pyamg_available, reason="PyAMG is required for the tests in this function." +) # non centered, sparse centers to check the centers = np.array( @@ -85,7 +94,16 @@ def test_sparse_graph_connected_component(): assert_array_equal(component_1, component_2) -def test_spectral_embedding_two_components(seed=36): [email protected]( + "eigen_solver", + [ + "arpack", + "lobpcg", + pytest.param("amg", marks=skip_if_no_pyamg), + ], +) [email protected]("dtype", [np.float32, np.float64]) +def test_spectral_embedding_two_components(eigen_solver, dtype, seed=36): # Test spectral embedding with two components random_state = np.random.RandomState(seed) n_sample = 100 @@ -117,31 +135,46 @@ def test_spectral_embedding_two_components(seed=36): true_label[0:n_sample] = 1 se_precomp = SpectralEmbedding( - n_components=1, affinity="precomputed", random_state=np.random.RandomState(seed) + n_components=1, + affinity="precomputed", + random_state=np.random.RandomState(seed), + eigen_solver=eigen_solver, ) - embedded_coordinate = se_precomp.fit_transform(affinity) - # Some numpy versions are touchy with types - embedded_coordinate = se_precomp.fit_transform(affinity.astype(np.float32)) - # thresholding on the first components using 0. - label_ = np.array(embedded_coordinate.ravel() < 0, dtype="float") - assert normalized_mutual_info_score(true_label, label_) == pytest.approx(1.0) + for dtype in [np.float32, np.float64]: + embedded_coordinate = se_precomp.fit_transform(affinity.astype(dtype)) + # thresholding on the first components using 0. + label_ = np.array(embedded_coordinate.ravel() < 0, dtype=np.int64) + assert normalized_mutual_info_score(true_label, label_) == pytest.approx(1.0) @pytest.mark.parametrize("X", [S, sparse.csr_matrix(S)], ids=["dense", "sparse"]) -def test_spectral_embedding_precomputed_affinity(X, seed=36): [email protected]( + "eigen_solver", + [ + "arpack", + "lobpcg", + pytest.param("amg", marks=skip_if_no_pyamg), + ], +) [email protected]("dtype", (np.float32, np.float64)) +def test_spectral_embedding_precomputed_affinity(X, eigen_solver, dtype, seed=36): # Test spectral embedding with precomputed kernel gamma = 1.0 se_precomp = SpectralEmbedding( - n_components=2, affinity="precomputed", random_state=np.random.RandomState(seed) + n_components=2, + affinity="precomputed", + random_state=np.random.RandomState(seed), + eigen_solver=eigen_solver, ) se_rbf = SpectralEmbedding( n_components=2, affinity="rbf", gamma=gamma, random_state=np.random.RandomState(seed), + eigen_solver=eigen_solver, ) - embed_precomp = se_precomp.fit_transform(rbf_kernel(X, gamma=gamma)) - embed_rbf = se_rbf.fit_transform(X) + embed_precomp = se_precomp.fit_transform(rbf_kernel(X.astype(dtype), gamma=gamma)) + embed_rbf = se_rbf.fit_transform(X.astype(dtype)) assert_array_almost_equal(se_precomp.affinity_matrix_, se_rbf.affinity_matrix_) _assert_equal_with_sign_flipping(embed_precomp, embed_rbf, 0.05) @@ -205,10 +238,11 @@ def test_spectral_embedding_callable_affinity(X, seed=36): @pytest.mark.filterwarnings( "ignore:scipy.linalg.pinv2 is deprecated:DeprecationWarning:pyamg.*" ) -def test_spectral_embedding_amg_solver(seed=36): - # Test spectral embedding with amg solver - pytest.importorskip("pyamg") - [email protected]( + not pyamg_available, reason="PyAMG is required for the tests in this function." +) [email protected]("dtype", (np.float32, np.float64)) +def test_spectral_embedding_amg_solver(dtype, seed=36): se_amg = SpectralEmbedding( n_components=2, affinity="nearest_neighbors", @@ -223,8 +257,8 @@ def test_spectral_embedding_amg_solver(seed=36): n_neighbors=5, random_state=np.random.RandomState(seed), ) - embed_amg = se_amg.fit_transform(S) - embed_arpack = se_arpack.fit_transform(S) + embed_amg = se_amg.fit_transform(S.astype(dtype)) + embed_arpack = se_arpack.fit_transform(S.astype(dtype)) _assert_equal_with_sign_flipping(embed_amg, embed_arpack, 1e-5) # same with special case in which amg is not actually used @@ -239,8 +273,8 @@ def test_spectral_embedding_amg_solver(seed=36): ).toarray() se_amg.affinity = "precomputed" se_arpack.affinity = "precomputed" - embed_amg = se_amg.fit_transform(affinity) - embed_arpack = se_arpack.fit_transform(affinity) + embed_amg = se_amg.fit_transform(affinity.astype(dtype)) + embed_arpack = se_arpack.fit_transform(affinity.astype(dtype)) _assert_equal_with_sign_flipping(embed_amg, embed_arpack, 1e-5) @@ -258,12 +292,15 @@ def test_spectral_embedding_amg_solver(seed=36): @pytest.mark.filterwarnings( "ignore:scipy.linalg.pinv2 is deprecated:DeprecationWarning:pyamg.*" ) -def test_spectral_embedding_amg_solver_failure(): [email protected]( + not pyamg_available, reason="PyAMG is required for the tests in this function." +) [email protected]("dtype", (np.float32, np.float64)) +def test_spectral_embedding_amg_solver_failure(dtype, seed=36): # Non-regression test for amg solver failure (issue #13393 on github) - pytest.importorskip("pyamg") - seed = 36 num_nodes = 100 X = sparse.rand(num_nodes, num_nodes, density=0.1, random_state=seed) + X = X.astype(dtype) upper = sparse.triu(X) - sparse.diags(X.diagonal()) sym_matrix = upper + upper.T embedding = spectral_embedding( @@ -314,7 +351,9 @@ def test_spectral_embedding_unknown_eigensolver(seed=36): def test_spectral_embedding_unknown_affinity(seed=36): # Test that SpectralClustering fails with an unknown affinity type se = SpectralEmbedding( - n_components=1, affinity="<unknown>", random_state=np.random.RandomState(seed) + n_components=1, + affinity="<unknown>", + random_state=np.random.RandomState(seed), ) with pytest.raises(ValueError): se.fit(S) @@ -399,6 +438,50 @@ def test_spectral_embedding_first_eigen_vector(): assert np.std(embedding[:, 1]) > 1e-3 [email protected]( + "eigen_solver", + [ + "arpack", + "lobpcg", + pytest.param("amg", marks=skip_if_no_pyamg), + ], +) [email protected]("dtype", [np.float32, np.float64]) +def test_spectral_embedding_preserves_dtype(eigen_solver, dtype): + """Check that `SpectralEmbedding is preserving the dtype of the fitted + attribute and transformed data. + + Ideally, this test should be covered by the common test + `check_transformer_preserve_dtypes`. However, this test only run + with transformers implementing `transform` while `SpectralEmbedding` + implements only `fit_transform`. + """ + X = S.astype(dtype) + se = SpectralEmbedding( + n_components=2, affinity="rbf", eigen_solver=eigen_solver, random_state=0 + ) + X_trans = se.fit_transform(X) + + assert X_trans.dtype == dtype + assert se.embedding_.dtype == dtype + assert se.affinity_matrix_.dtype == dtype + + [email protected]( + pyamg_available, + reason="PyAMG is installed and we should not test for an error.", +) +def test_error_pyamg_not_available(): + se_precomp = SpectralEmbedding( + n_components=2, + affinity="rbf", + eigen_solver="amg", + ) + err_msg = "The eigen_solver was set to 'amg', but pyamg is not available." + with pytest.raises(ValueError, match=err_msg): + se_precomp.fit_transform(S) + + # TODO: Remove in 1.1 @pytest.mark.parametrize("affinity", ["precomputed", "precomputed_nearest_neighbors"]) def test_spectral_embedding_pairwise_deprecated(affinity):
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 542636b1642f7..64e3c57a92214 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -117,6 +117,14 @@ Changelog\n backward compatibility, but this alias will be removed in 1.3.\n :pr:`21177` by :user:`Julien Jerphanion <jjerphan>`.\n \n+:mod:`sklearn.manifold`\n+.......................\n+\n+- |Enhancement| :func:`manifold.spectral_embedding` and\n+ :class:`manifold.SpectralEmbedding` supports `np.float32` dtype and will\n+ preserve this dtype.\n+ :pr:`21534` by :user:`Andrew Knyazev <lobpcg>`.\n+\n :mod:`sklearn.model_selection`\n ..............................\n \n" } ]
1.01
8cfbc38ab8864b68f9a504f96857bb2e527c9bbb
[ "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_two_components[float64-arpack]", "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_callable_affinity[sparse]", "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_pairwise_deprecated[precomputed]", "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_two_components[float64-lobpcg]", "sklearn/manifold/tests/test_spectral_embedding.py::test_precomputed_nearest_neighbors_filtering", "sklearn/manifold/tests/test_spectral_embedding.py::test_pipeline_spectral_clustering", "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_unknown_affinity", "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_precomputed_affinity[float32-arpack-dense]", "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_two_components[float32-arpack]", "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_precomputed_affinity[float64-lobpcg-sparse]", "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_deterministic", "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_unnormalized", "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_preserves_dtype[float64-lobpcg]", "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_precomputed_affinity[float32-lobpcg-sparse]", "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_preserves_dtype[float64-arpack]", "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_first_eigen_vector", "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_callable_affinity[dense]", "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_precomputed_affinity[float64-arpack-dense]", "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_precomputed_affinity[float64-arpack-sparse]", "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_two_components[float32-lobpcg]", "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_preserves_dtype[float32-arpack]", "sklearn/manifold/tests/test_spectral_embedding.py::test_connectivity", "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_precomputed_affinity[float32-lobpcg-dense]", "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_pairwise_deprecated[precomputed_nearest_neighbors]", "sklearn/manifold/tests/test_spectral_embedding.py::test_error_pyamg_not_available", "sklearn/manifold/tests/test_spectral_embedding.py::test_sparse_graph_connected_component", "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_precomputed_affinity[float64-lobpcg-dense]", "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_precomputed_affinity[float32-arpack-sparse]", "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_unknown_eigensolver" ]
[ "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_preserves_dtype[float32-lobpcg]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 542636b1642f7..64e3c57a92214 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -117,6 +117,14 @@ Changelog\n backward compatibility, but this alias will be removed in 1.3.\n :pr:`<PRID>` by :user:`<NAME>`.\n \n+:mod:`sklearn.manifold`\n+.......................\n+\n+- |Enhancement| :func:`manifold.spectral_embedding` and\n+ :class:`manifold.SpectralEmbedding` supports `np.float32` dtype and will\n+ preserve this dtype.\n+ :pr:`<PRID>` by :user:`<NAME>`.\n+\n :mod:`sklearn.model_selection`\n ..............................\n \n" } ]
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 542636b1642f7..64e3c57a92214 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -117,6 +117,14 @@ Changelog backward compatibility, but this alias will be removed in 1.3. :pr:`<PRID>` by :user:`<NAME>`. +:mod:`sklearn.manifold` +....................... + +- |Enhancement| :func:`manifold.spectral_embedding` and + :class:`manifold.SpectralEmbedding` supports `np.float32` dtype and will + preserve this dtype. + :pr:`<PRID>` by :user:`<NAME>`. + :mod:`sklearn.model_selection` ..............................
scikit-learn/scikit-learn
scikit-learn__scikit-learn-22118
https://github.com/scikit-learn/scikit-learn/pull/22118
diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst index b7000bcf7cbb2..c3e6c4f2f674b 100644 --- a/doc/modules/classes.rst +++ b/doc/modules/classes.rst @@ -996,6 +996,8 @@ details. metrics.mean_tweedie_deviance metrics.d2_tweedie_score metrics.mean_pinball_loss + metrics.d2_pinball_score + metrics.d2_absolute_error_score Multilabel ranking metrics -------------------------- diff --git a/doc/modules/model_evaluation.rst b/doc/modules/model_evaluation.rst index a1fce2d3454dc..8468dce3f93c5 100644 --- a/doc/modules/model_evaluation.rst +++ b/doc/modules/model_evaluation.rst @@ -101,6 +101,9 @@ Scoring Function 'neg_mean_poisson_deviance' :func:`metrics.mean_poisson_deviance` 'neg_mean_gamma_deviance' :func:`metrics.mean_gamma_deviance` 'neg_mean_absolute_percentage_error' :func:`metrics.mean_absolute_percentage_error` +'d2_absolute_error_score' :func:`metrics.d2_absolute_error_score` +'d2_pinball_score' :func:`metrics.d2_pinball_score` +'d2_tweedie_score' :func:`metrics.d2_tweedie_score` ==================================== ============================================== ================================== @@ -1968,7 +1971,8 @@ The :mod:`sklearn.metrics` module implements several loss, score, and utility functions to measure regression performance. Some of those have been enhanced to handle the multioutput case: :func:`mean_squared_error`, :func:`mean_absolute_error`, :func:`r2_score`, -:func:`explained_variance_score` and :func:`mean_pinball_loss`. +:func:`explained_variance_score`, :func:`mean_pinball_loss`, :func:`d2_pinball_score` +and :func:`d2_absolute_error_score`. These functions have an ``multioutput`` keyword argument which specifies the @@ -2370,8 +2374,8 @@ is defined as \sum_{i=0}^{n_\text{samples} - 1} \begin{cases} (y_i-\hat{y}_i)^2, & \text{for }p=0\text{ (Normal)}\\ - 2(y_i \log(y/\hat{y}_i) + \hat{y}_i - y_i), & \text{for}p=1\text{ (Poisson)}\\ - 2(\log(\hat{y}_i/y_i) + y_i/\hat{y}_i - 1), & \text{for}p=2\text{ (Gamma)}\\ + 2(y_i \log(y/\hat{y}_i) + \hat{y}_i - y_i), & \text{for }p=1\text{ (Poisson)}\\ + 2(\log(\hat{y}_i/y_i) + y_i/\hat{y}_i - 1), & \text{for }p=2\text{ (Gamma)}\\ 2\left(\frac{\max(y_i,0)^{2-p}}{(1-p)(2-p)}- \frac{y\,\hat{y}^{1-p}_i}{1-p}+\frac{\hat{y}^{2-p}_i}{2-p}\right), & \text{otherwise} @@ -2414,34 +2418,6 @@ the difference in errors decreases. Finally, by setting, ``power=2``:: we would get identical errors. The deviance when ``power=2`` is thus only sensitive to relative errors. -.. _d2_tweedie_score: - -D² score, the coefficient of determination -------------------------------------------- - -The :func:`d2_tweedie_score` function computes the percentage of deviance -explained. It is a generalization of R², where the squared error is replaced by -the Tweedie deviance. D², also known as McFadden's likelihood ratio index, is -calculated as - -.. math:: - - D^2(y, \hat{y}) = 1 - \frac{\text{D}(y, \hat{y})}{\text{D}(y, \bar{y})} \,. - -The argument ``power`` defines the Tweedie power as for -:func:`mean_tweedie_deviance`. Note that for `power=0`, -:func:`d2_tweedie_score` equals :func:`r2_score` (for single targets). - -Like R², the best possible score is 1.0 and it can be negative (because the -model can be arbitrarily worse). A constant model that always predicts the -expected value of y, disregarding the input features, would get a D² score -of 0.0. - -A scorer object with a specific choice of ``power`` can be built by:: - - >>> from sklearn.metrics import d2_tweedie_score, make_scorer - >>> d2_tweedie_score_15 = make_scorer(d2_tweedie_score, power=1.5) - .. _pinball_loss: Pinball loss @@ -2506,6 +2482,93 @@ explained in the example linked below. hyper-parameters of quantile regression models on data with non-symmetric noise and outliers. +.. _d2_score: + +D² score +-------- + +The D² score computes the fraction of deviance explained. +It is a generalization of R², where the squared error is generalized and replaced +by a deviance of choice :math:`\text{dev}(y, \hat{y})` +(e.g., Tweedie, pinball or mean absolute error). D² is a form of a *skill score*. +It is calculated as + +.. math:: + + D^2(y, \hat{y}) = 1 - \frac{\text{dev}(y, \hat{y})}{\text{dev}(y, y_{\text{null}})} \,. + +Where :math:`y_{\text{null}}` is the optimal prediction of an intercept-only model +(e.g., the mean of `y_true` for the Tweedie case, the median for absolute +error and the alpha-quantile for pinball loss). + +Like R², the best possible score is 1.0 and it can be negative (because the +model can be arbitrarily worse). A constant model that always predicts +:math:`y_{\text{null}}`, disregarding the input features, would get a D² score +of 0.0. + +D² Tweedie score +^^^^^^^^^^^^^^^^ + +The :func:`d2_tweedie_score` function implements the special case of D² +where :math:`\text{dev}(y, \hat{y})` is the Tweedie deviance, see :ref:`mean_tweedie_deviance`. +It is also known as D² Tweedie and is related to McFadden's likelihood ratio index. + +The argument ``power`` defines the Tweedie power as for +:func:`mean_tweedie_deviance`. Note that for `power=0`, +:func:`d2_tweedie_score` equals :func:`r2_score` (for single targets). + +A scorer object with a specific choice of ``power`` can be built by:: + + >>> from sklearn.metrics import d2_tweedie_score, make_scorer + >>> d2_tweedie_score_15 = make_scorer(d2_tweedie_score, power=1.5) + +D² pinball score +^^^^^^^^^^^^^^^^^^^^^ + +The :func:`d2_pinball_score` function implements the special case +of D² with the pinball loss, see :ref:`pinball_loss`, i.e.: + +.. math:: + + \text{dev}(y, \hat{y}) = \text{pinball}(y, \hat{y}). + +The argument ``alpha`` defines the slope of the pinball loss as for +:func:`mean_pinball_loss` (:ref:`pinball_loss`). It determines the +quantile level ``alpha`` for which the pinball loss and also D² +are optimal. Note that for `alpha=0.5` (the default) :func:`d2_pinball_score` +equals :func:`d2_absolute_error_score`. + +A scorer object with a specific choice of ``alpha`` can be built by:: + + >>> from sklearn.metrics import d2_pinball_score, make_scorer + >>> d2_pinball_score_08 = make_scorer(d2_pinball_score, alpha=0.8) + +D² absolute error score +^^^^^^^^^^^^^^^^^^^^^^^ + +The :func:`d2_absolute_error_score` function implements the special case of +the :ref:`mean_absolute_error`: + +.. math:: + + \text{dev}(y, \hat{y}) = \text{MAE}(y, \hat{y}). + +Here are some usage examples of the :func:`d2_absolute_error_score` function:: + + >>> from sklearn.metrics import d2_absolute_error_score + >>> y_true = [3, -0.5, 2, 7] + >>> y_pred = [2.5, 0.0, 2, 8] + >>> d2_absolute_error_score(y_true, y_pred) + 0.764... + >>> y_true = [1, 2, 3] + >>> y_pred = [1, 2, 3] + >>> d2_absolute_error_score(y_true, y_pred) + 1.0 + >>> y_true = [1, 2, 3] + >>> y_pred = [2, 2, 2] + >>> d2_absolute_error_score(y_true, y_pred) + 0.0 + .. _clustering_metrics: diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index b9ab45e1d344a..85053e5a68679 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -630,6 +630,14 @@ Changelog instead of the finite approximation (`1.0` and `0.0` respectively) currently returned by default. :pr:`17266` by :user:`Sylvain Marié <smarie>`. +- |Feature| :func:`d2_pinball_score` and :func:`d2_absolute_error_score` + calculate the :math:`D^2` regression score for the pinball loss and the + absolute error respectively. :func:`d2_absolute_error_score` is a special case + of :func:`d2_pinball_score` with a fixed quantile parameter `alpha=0.5` + for ease of use and discovery. The :math:`D^2` scores are generalizations + of the `r2_score` and can be interpeted as the fraction of deviance explained. + :pr:`22118` by :user:`Ohad Michel <ohadmich>` + - |Enhancement| :func:`metrics.top_k_accuracy_score` raises an improved error message when `y_true` is binary and `y_score` is 2d. :pr:`22284` by `Thomas Fan`_. diff --git a/sklearn/metrics/__init__.py b/sklearn/metrics/__init__.py index e4339229c5b64..02ae7d41ebc31 100644 --- a/sklearn/metrics/__init__.py +++ b/sklearn/metrics/__init__.py @@ -77,6 +77,8 @@ from ._regression import mean_poisson_deviance from ._regression import mean_gamma_deviance from ._regression import d2_tweedie_score +from ._regression import d2_pinball_score +from ._regression import d2_absolute_error_score from ._scorer import check_scoring @@ -113,6 +115,8 @@ "consensus_score", "coverage_error", "d2_tweedie_score", + "d2_absolute_error_score", + "d2_pinball_score", "dcg_score", "davies_bouldin_score", "DetCurveDisplay", diff --git a/sklearn/metrics/_regression.py b/sklearn/metrics/_regression.py index c701320f9c23a..de8aef20aa7c2 100644 --- a/sklearn/metrics/_regression.py +++ b/sklearn/metrics/_regression.py @@ -23,6 +23,7 @@ # Ashutosh Hathidara <[email protected]> # Uttam kumar <[email protected]> # Sylvain Marie <[email protected]> +# Ohad Michel <[email protected]> # License: BSD 3 clause import warnings @@ -54,6 +55,9 @@ "mean_tweedie_deviance", "mean_poisson_deviance", "mean_gamma_deviance", + "d2_tweedie_score", + "d2_pinball_score", + "d2_absolute_error_score", ] @@ -70,6 +74,9 @@ def _check_reg_targets(y_true, y_pred, multioutput, dtype="numeric"): 'variance_weighted'] or None None is accepted due to backward compatibility of r2_score(). + dtype : str or list, default="numeric" + the dtype argument passed to check_array. + Returns ------- type_true : one of {'continuous', continuous-multioutput'} @@ -87,9 +94,6 @@ def _check_reg_targets(y_true, y_pred, multioutput, dtype="numeric"): Custom output weights if ``multioutput`` is array-like or just the corresponding argument if ``multioutput`` is a correct keyword. - - dtype : str or list, default="numeric" - the dtype argument passed to check_array. """ check_consistent_length(y_true, y_pred) y_true = check_array(y_true, ensure_2d=False, dtype=dtype) @@ -1102,13 +1106,13 @@ def mean_gamma_deviance(y_true, y_pred, *, sample_weight=None): def d2_tweedie_score(y_true, y_pred, *, sample_weight=None, power=0): - """D^2 regression score function, percentage of Tweedie deviance explained. + """D^2 regression score function, fraction of Tweedie deviance explained. Best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A model that always uses the empirical mean of `y_true` as constant prediction, disregarding the input features, gets a D^2 score of 0.0. - Read more in the :ref:`User Guide <d2_tweedie_score>`. + Read more in the :ref:`User Guide <d2_score>`. .. versionadded:: 1.0 @@ -1203,3 +1207,237 @@ def d2_tweedie_score(y_true, y_pred, *, sample_weight=None, power=0): denominator = np.average(dev, weights=sample_weight) return 1 - numerator / denominator + + +def d2_pinball_score( + y_true, y_pred, *, sample_weight=None, alpha=0.5, multioutput="uniform_average" +): + """ + :math:`D^2` regression score function, fraction of pinball loss explained. + + Best possible score is 1.0 and it can be negative (because the model can be + arbitrarily worse). A model that always uses the empirical alpha-quantile of + `y_true` as constant prediction, disregarding the input features, + gets a :math:`D^2` score of 0.0. + + Read more in the :ref:`User Guide <d2_score>`. + + .. versionadded:: 1.1 + + Parameters + ---------- + y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) + Estimated target values. + + sample_weight : array-like of shape (n_samples,), optional + Sample weights. + + alpha : float, default=0.5 + Slope of the pinball deviance. It determines the quantile level alpha + for which the pinball deviance and also D2 are optimal. + The default `alpha=0.5` is equivalent to `d2_absolute_error_score`. + + multioutput : {'raw_values', 'uniform_average'} or array-like of shape \ + (n_outputs,), default='uniform_average' + Defines aggregating of multiple output values. + Array-like value defines weights used to average scores. + + 'raw_values' : + Returns a full set of errors in case of multioutput input. + + 'uniform_average' : + Scores of all outputs are averaged with uniform weight. + + Returns + ------- + score : float or ndarray of floats + The :math:`D^2` score with a pinball deviance + or ndarray of scores if `multioutput='raw_values'`. + + Notes + ----- + Like :math:`R^2`, :math:`D^2` score may be negative + (it need not actually be the square of a quantity D). + + This metric is not well-defined for a single point and will return a NaN + value if n_samples is less than two. + + References + ---------- + .. [1] Eq. (7) of `Koenker, Roger; Machado, José A. F. (1999). + "Goodness of Fit and Related Inference Processes for Quantile Regression" + <http://dx.doi.org/10.1080/01621459.1999.10473882>`_ + .. [2] Eq. (3.11) of Hastie, Trevor J., Robert Tibshirani and Martin J. + Wainwright. "Statistical Learning with Sparsity: The Lasso and + Generalizations." (2015). https://trevorhastie.github.io + + Examples + -------- + >>> from sklearn.metrics import d2_pinball_score + >>> y_true = [1, 2, 3] + >>> y_pred = [1, 3, 3] + >>> d2_pinball_score(y_true, y_pred) + 0.5 + >>> d2_pinball_score(y_true, y_pred, alpha=0.9) + 0.772... + >>> d2_pinball_score(y_true, y_pred, alpha=0.1) + -1.045... + >>> d2_pinball_score(y_true, y_true, alpha=0.1) + 1.0 + """ + y_type, y_true, y_pred, multioutput = _check_reg_targets( + y_true, y_pred, multioutput + ) + check_consistent_length(y_true, y_pred, sample_weight) + + if _num_samples(y_pred) < 2: + msg = "D^2 score is not well-defined with less than two samples." + warnings.warn(msg, UndefinedMetricWarning) + return float("nan") + + numerator = mean_pinball_loss( + y_true, + y_pred, + sample_weight=sample_weight, + alpha=alpha, + multioutput="raw_values", + ) + + if sample_weight is None: + y_quantile = np.tile( + np.percentile(y_true, q=alpha * 100, axis=0), (len(y_true), 1) + ) + else: + sample_weight = _check_sample_weight(sample_weight, y_true) + y_quantile = np.tile( + _weighted_percentile( + y_true, sample_weight=sample_weight, percentile=alpha * 100 + ), + (len(y_true), 1), + ) + + denominator = mean_pinball_loss( + y_true, + y_quantile, + sample_weight=sample_weight, + alpha=alpha, + multioutput="raw_values", + ) + + nonzero_numerator = numerator != 0 + nonzero_denominator = denominator != 0 + valid_score = nonzero_numerator & nonzero_denominator + output_scores = np.ones(y_true.shape[1]) + + output_scores[valid_score] = 1 - (numerator[valid_score] / denominator[valid_score]) + output_scores[nonzero_numerator & ~nonzero_denominator] = 0.0 + + if isinstance(multioutput, str): + if multioutput == "raw_values": + # return scores individually + return output_scores + elif multioutput == "uniform_average": + # passing None as weights to np.average results in uniform mean + avg_weights = None + else: + raise ValueError( + "multioutput is expected to be 'raw_values' " + "or 'uniform_average' but we got %r" + " instead." % multioutput + ) + else: + avg_weights = multioutput + + return np.average(output_scores, weights=avg_weights) + + +def d2_absolute_error_score( + y_true, y_pred, *, sample_weight=None, multioutput="uniform_average" +): + """ + :math:`D^2` regression score function, \ + fraction of absolute error explained. + + Best possible score is 1.0 and it can be negative (because the model can be + arbitrarily worse). A model that always uses the empirical median of `y_true` + as constant prediction, disregarding the input features, + gets a :math:`D^2` score of 0.0. + + Read more in the :ref:`User Guide <d2_score>`. + + .. versionadded:: 1.1 + + Parameters + ---------- + y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) + Estimated target values. + + sample_weight : array-like of shape (n_samples,), optional + Sample weights. + + multioutput : {'raw_values', 'uniform_average'} or array-like of shape \ + (n_outputs,), default='uniform_average' + Defines aggregating of multiple output values. + Array-like value defines weights used to average scores. + + 'raw_values' : + Returns a full set of errors in case of multioutput input. + + 'uniform_average' : + Scores of all outputs are averaged with uniform weight. + + Returns + ------- + score : float or ndarray of floats + The :math:`D^2` score with an absolute error deviance + or ndarray of scores if 'multioutput' is 'raw_values'. + + Notes + ----- + Like :math:`R^2`, :math:`D^2` score may be negative + (it need not actually be the square of a quantity D). + + This metric is not well-defined for single samples and will return a NaN + value if n_samples is less than two. + + References + ---------- + .. [1] Eq. (3.11) of Hastie, Trevor J., Robert Tibshirani and Martin J. + Wainwright. "Statistical Learning with Sparsity: The Lasso and + Generalizations." (2015). https://trevorhastie.github.io + + Examples + -------- + >>> from sklearn.metrics import d2_absolute_error_score + >>> y_true = [3, -0.5, 2, 7] + >>> y_pred = [2.5, 0.0, 2, 8] + >>> d2_absolute_error_score(y_true, y_pred) + 0.764... + >>> y_true = [[0.5, 1], [-1, 1], [7, -6]] + >>> y_pred = [[0, 2], [-1, 2], [8, -5]] + >>> d2_absolute_error_score(y_true, y_pred, multioutput='uniform_average') + 0.691... + >>> d2_absolute_error_score(y_true, y_pred, multioutput='raw_values') + array([0.8125 , 0.57142857]) + >>> y_true = [1, 2, 3] + >>> y_pred = [1, 2, 3] + >>> d2_absolute_error_score(y_true, y_pred) + 1.0 + >>> y_true = [1, 2, 3] + >>> y_pred = [2, 2, 2] + >>> d2_absolute_error_score(y_true, y_pred) + 0.0 + >>> y_true = [1, 2, 3] + >>> y_pred = [3, 2, 1] + >>> d2_absolute_error_score(y_true, y_pred) + -1.0 + """ + return d2_pinball_score( + y_true, y_pred, sample_weight=sample_weight, alpha=0.5, multioutput=multioutput + )
diff --git a/sklearn/metrics/tests/test_common.py b/sklearn/metrics/tests/test_common.py index dfd43ef34096f..1e627f9f86676 100644 --- a/sklearn/metrics/tests/test_common.py +++ b/sklearn/metrics/tests/test_common.py @@ -30,6 +30,8 @@ from sklearn.metrics import confusion_matrix from sklearn.metrics import coverage_error from sklearn.metrics import d2_tweedie_score +from sklearn.metrics import d2_pinball_score +from sklearn.metrics import d2_absolute_error_score from sklearn.metrics import det_curve from sklearn.metrics import explained_variance_score from sklearn.metrics import f1_score @@ -112,6 +114,8 @@ "mean_gamma_deviance": mean_gamma_deviance, "mean_compound_poisson_deviance": partial(mean_tweedie_deviance, power=1.4), "d2_tweedie_score": partial(d2_tweedie_score, power=1.4), + "d2_pinball_score": d2_pinball_score, + "d2_absolute_error_score": d2_absolute_error_score, } CLASSIFICATION_METRICS = { @@ -446,6 +450,8 @@ def precision_recall_curve_padded_thresholds(*args, **kwargs): "explained_variance_score", "mean_absolute_percentage_error", "mean_pinball_loss", + "d2_pinball_score", + "d2_absolute_error_score", } # Symmetric with respect to their input arguments y_true and y_pred @@ -513,6 +519,8 @@ def precision_recall_curve_padded_thresholds(*args, **kwargs): "mean_poisson_deviance", "mean_compound_poisson_deviance", "d2_tweedie_score", + "d2_pinball_score", + "d2_absolute_error_score", "mean_absolute_percentage_error", } diff --git a/sklearn/metrics/tests/test_regression.py b/sklearn/metrics/tests/test_regression.py index f5ffc648ed21b..a95125493047b 100644 --- a/sklearn/metrics/tests/test_regression.py +++ b/sklearn/metrics/tests/test_regression.py @@ -22,6 +22,8 @@ from sklearn.metrics import r2_score from sklearn.metrics import mean_tweedie_deviance from sklearn.metrics import d2_tweedie_score +from sklearn.metrics import d2_pinball_score +from sklearn.metrics import d2_absolute_error_score from sklearn.metrics import make_scorer from sklearn.metrics._regression import _check_reg_targets @@ -62,6 +64,26 @@ def test_regression_metrics(n_samples=50): assert_almost_equal( d2_tweedie_score(y_true, y_pred, power=0), r2_score(y_true, y_pred) ) + dev_median = np.abs(y_true - np.median(y_true)).sum() + assert_array_almost_equal( + d2_absolute_error_score(y_true, y_pred), + 1 - np.abs(y_true - y_pred).sum() / dev_median, + ) + alpha = 0.2 + pinball_loss = lambda y_true, y_pred, alpha: alpha * np.maximum( + y_true - y_pred, 0 + ) + (1 - alpha) * np.maximum(y_pred - y_true, 0) + y_quantile = np.percentile(y_true, q=alpha * 100) + assert_almost_equal( + d2_pinball_score(y_true, y_pred, alpha=alpha), + 1 + - pinball_loss(y_true, y_pred, alpha).sum() + / pinball_loss(y_true, y_quantile, alpha).sum(), + ) + assert_almost_equal( + d2_absolute_error_score(y_true, y_pred), + d2_pinball_score(y_true, y_pred, alpha=0.5), + ) # Tweedie deviance needs positive y_pred, except for p=0, # p>=2 needs positive y_true @@ -139,6 +161,20 @@ def test_multioutput_regression(): error = r2_score(y_true, y_pred, multioutput="uniform_average") assert_almost_equal(error, -0.875) + score = d2_pinball_score(y_true, y_pred, alpha=0.5, multioutput="raw_values") + raw_expected_score = [ + 1 + - np.abs(y_true[:, i] - y_pred[:, i]).sum() + / np.abs(y_true[:, i] - np.median(y_true[:, i])).sum() + for i in range(y_true.shape[1]) + ] + # in the last case, the denominator vanishes and hence we get nan, + # but since the the numerator vanishes as well the expected score is 1.0 + raw_expected_score = np.where(np.isnan(raw_expected_score), 1, raw_expected_score) + assert_array_almost_equal(score, raw_expected_score) + + score = d2_pinball_score(y_true, y_pred, alpha=0.5, multioutput="uniform_average") + assert_almost_equal(score, raw_expected_score.mean()) # constant `y_true` with force_finite=True leads to 1. or 0. yc = [5.0, 5.0] error = r2_score(yc, [5.0, 5.0], multioutput="variance_weighted") @@ -192,6 +228,7 @@ def test_regression_metrics_at_limits(): # Perfect cases assert_almost_equal(r2_score([0.0, 1], [0.0, 1]), 1.0) + assert_almost_equal(d2_pinball_score([0.0, 1], [0.0, 1]), 1.0) # Non-finite cases # R² and explained variance have a fix by default for non-finite cases @@ -319,10 +356,15 @@ def test_regression_multioutput_array(): ) with pytest.raises(ValueError, match=err_msg): mean_pinball_loss(y_true, y_pred, multioutput="variance_weighted") + + with pytest.raises(ValueError, match=err_msg): + d2_pinball_score(y_true, y_pred, multioutput="variance_weighted") + pbl = mean_pinball_loss(y_true, y_pred, multioutput="raw_values") mape = mean_absolute_percentage_error(y_true, y_pred, multioutput="raw_values") r = r2_score(y_true, y_pred, multioutput="raw_values") evs = explained_variance_score(y_true, y_pred, multioutput="raw_values") + d2ps = d2_pinball_score(y_true, y_pred, alpha=0.5, multioutput="raw_values") evs2 = explained_variance_score( y_true, y_pred, multioutput="raw_values", force_finite=False ) @@ -333,6 +375,7 @@ def test_regression_multioutput_array(): assert_array_almost_equal(mape, [0.0778, 0.2262], decimal=2) assert_array_almost_equal(r, [0.95, 0.93], decimal=2) assert_array_almost_equal(evs, [0.95, 0.93], decimal=2) + assert_array_almost_equal(d2ps, [0.833, 0.722], decimal=2) assert_array_almost_equal(evs2, [0.95, 0.93], decimal=2) # mean_absolute_error and mean_squared_error are equal because @@ -343,10 +386,12 @@ def test_regression_multioutput_array(): mae = mean_absolute_error(y_true, y_pred, multioutput="raw_values") pbl = mean_pinball_loss(y_true, y_pred, multioutput="raw_values") r = r2_score(y_true, y_pred, multioutput="raw_values") + d2ps = d2_pinball_score(y_true, y_pred, multioutput="raw_values") assert_array_almost_equal(mse, [1.0, 1.0], decimal=2) assert_array_almost_equal(mae, [1.0, 1.0], decimal=2) assert_array_almost_equal(pbl, [0.5, 0.5], decimal=2) assert_array_almost_equal(r, [0.0, 0.0], decimal=2) + assert_array_almost_equal(d2ps, [0.0, 0.0], decimal=2) r = r2_score([[0, -1], [0, 1]], [[2, 2], [1, 1]], multioutput="raw_values") assert_array_almost_equal(r, [0, -3.5], decimal=2) @@ -382,6 +427,8 @@ def test_regression_multioutput_array(): evs = explained_variance_score(y_true, y_pred, multioutput="raw_values") assert_array_almost_equal(evs, [1.0, -3.0], decimal=2) assert np.mean(evs) == explained_variance_score(y_true, y_pred) + d2ps = d2_pinball_score(y_true, y_pred, alpha=0.5, multioutput="raw_values") + assert_array_almost_equal(d2ps, [1.0, -1.0], decimal=2) evs2 = explained_variance_score( y_true, y_pred, multioutput="raw_values", force_finite=False ) @@ -410,6 +457,7 @@ def test_regression_custom_weights(): mapew = mean_absolute_percentage_error(y_true, y_pred, multioutput=[0.4, 0.6]) rw = r2_score(y_true, y_pred, multioutput=[0.4, 0.6]) evsw = explained_variance_score(y_true, y_pred, multioutput=[0.4, 0.6]) + d2psw = d2_pinball_score(y_true, y_pred, alpha=0.5, multioutput=[0.4, 0.6]) evsw2 = explained_variance_score( y_true, y_pred, multioutput=[0.4, 0.6], force_finite=False ) @@ -420,6 +468,7 @@ def test_regression_custom_weights(): assert_almost_equal(mapew, 0.1668, decimal=2) assert_almost_equal(rw, 0.94, decimal=2) assert_almost_equal(evsw, 0.94, decimal=2) + assert_almost_equal(d2psw, 0.766, decimal=2) assert_almost_equal(evsw2, 0.94, decimal=2) # Handling msle separately as it does not accept negative inputs. @@ -432,7 +481,7 @@ def test_regression_custom_weights(): assert_almost_equal(msle, msle2, decimal=2) [email protected]("metric", [r2_score, d2_tweedie_score]) [email protected]("metric", [r2_score, d2_tweedie_score, d2_pinball_score]) def test_regression_single_sample(metric): y_true = [0] y_pred = [1]
[ { "path": "doc/modules/classes.rst", "old_path": "a/doc/modules/classes.rst", "new_path": "b/doc/modules/classes.rst", "metadata": "diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst\nindex b7000bcf7cbb2..c3e6c4f2f674b 100644\n--- a/doc/modules/classes.rst\n+++ b/doc/modules/classes.rst\n@@ -996,6 +996,8 @@ details.\n metrics.mean_tweedie_deviance\n metrics.d2_tweedie_score\n metrics.mean_pinball_loss\n+ metrics.d2_pinball_score\n+ metrics.d2_absolute_error_score\n \n Multilabel ranking metrics\n --------------------------\n" }, { "path": "doc/modules/model_evaluation.rst", "old_path": "a/doc/modules/model_evaluation.rst", "new_path": "b/doc/modules/model_evaluation.rst", "metadata": "diff --git a/doc/modules/model_evaluation.rst b/doc/modules/model_evaluation.rst\nindex a1fce2d3454dc..8468dce3f93c5 100644\n--- a/doc/modules/model_evaluation.rst\n+++ b/doc/modules/model_evaluation.rst\n@@ -101,6 +101,9 @@ Scoring Function\n 'neg_mean_poisson_deviance' :func:`metrics.mean_poisson_deviance`\n 'neg_mean_gamma_deviance' :func:`metrics.mean_gamma_deviance`\n 'neg_mean_absolute_percentage_error' :func:`metrics.mean_absolute_percentage_error`\n+'d2_absolute_error_score' :func:`metrics.d2_absolute_error_score`\n+'d2_pinball_score' :func:`metrics.d2_pinball_score`\n+'d2_tweedie_score' :func:`metrics.d2_tweedie_score`\n ==================================== ============================================== ==================================\n \n \n@@ -1968,7 +1971,8 @@ The :mod:`sklearn.metrics` module implements several loss, score, and utility\n functions to measure regression performance. Some of those have been enhanced\n to handle the multioutput case: :func:`mean_squared_error`,\n :func:`mean_absolute_error`, :func:`r2_score`,\n-:func:`explained_variance_score` and :func:`mean_pinball_loss`.\n+:func:`explained_variance_score`, :func:`mean_pinball_loss`, :func:`d2_pinball_score`\n+and :func:`d2_absolute_error_score`.\n \n \n These functions have an ``multioutput`` keyword argument which specifies the\n@@ -2370,8 +2374,8 @@ is defined as\n \\sum_{i=0}^{n_\\text{samples} - 1}\n \\begin{cases}\n (y_i-\\hat{y}_i)^2, & \\text{for }p=0\\text{ (Normal)}\\\\\n- 2(y_i \\log(y/\\hat{y}_i) + \\hat{y}_i - y_i), & \\text{for}p=1\\text{ (Poisson)}\\\\\n- 2(\\log(\\hat{y}_i/y_i) + y_i/\\hat{y}_i - 1), & \\text{for}p=2\\text{ (Gamma)}\\\\\n+ 2(y_i \\log(y/\\hat{y}_i) + \\hat{y}_i - y_i), & \\text{for }p=1\\text{ (Poisson)}\\\\\n+ 2(\\log(\\hat{y}_i/y_i) + y_i/\\hat{y}_i - 1), & \\text{for }p=2\\text{ (Gamma)}\\\\\n 2\\left(\\frac{\\max(y_i,0)^{2-p}}{(1-p)(2-p)}-\n \\frac{y\\,\\hat{y}^{1-p}_i}{1-p}+\\frac{\\hat{y}^{2-p}_i}{2-p}\\right),\n & \\text{otherwise}\n@@ -2414,34 +2418,6 @@ the difference in errors decreases. Finally, by setting, ``power=2``::\n we would get identical errors. The deviance when ``power=2`` is thus only\n sensitive to relative errors.\n \n-.. _d2_tweedie_score:\n-\n-D² score, the coefficient of determination\n--------------------------------------------\n-\n-The :func:`d2_tweedie_score` function computes the percentage of deviance\n-explained. It is a generalization of R², where the squared error is replaced by\n-the Tweedie deviance. D², also known as McFadden's likelihood ratio index, is\n-calculated as\n-\n-.. math::\n-\n- D^2(y, \\hat{y}) = 1 - \\frac{\\text{D}(y, \\hat{y})}{\\text{D}(y, \\bar{y})} \\,.\n-\n-The argument ``power`` defines the Tweedie power as for\n-:func:`mean_tweedie_deviance`. Note that for `power=0`,\n-:func:`d2_tweedie_score` equals :func:`r2_score` (for single targets).\n-\n-Like R², the best possible score is 1.0 and it can be negative (because the\n-model can be arbitrarily worse). A constant model that always predicts the\n-expected value of y, disregarding the input features, would get a D² score\n-of 0.0.\n-\n-A scorer object with a specific choice of ``power`` can be built by::\n-\n- >>> from sklearn.metrics import d2_tweedie_score, make_scorer\n- >>> d2_tweedie_score_15 = make_scorer(d2_tweedie_score, power=1.5)\n-\n .. _pinball_loss:\n \n Pinball loss\n@@ -2506,6 +2482,93 @@ explained in the example linked below.\n hyper-parameters of quantile regression models on data with non-symmetric\n noise and outliers.\n \n+.. _d2_score:\n+\n+D² score\n+--------\n+\n+The D² score computes the fraction of deviance explained. \n+It is a generalization of R², where the squared error is generalized and replaced \n+by a deviance of choice :math:`\\text{dev}(y, \\hat{y})`\n+(e.g., Tweedie, pinball or mean absolute error). D² is a form of a *skill score*.\n+It is calculated as\n+\n+.. math::\n+\n+ D^2(y, \\hat{y}) = 1 - \\frac{\\text{dev}(y, \\hat{y})}{\\text{dev}(y, y_{\\text{null}})} \\,.\n+\n+Where :math:`y_{\\text{null}}` is the optimal prediction of an intercept-only model\n+(e.g., the mean of `y_true` for the Tweedie case, the median for absolute \n+error and the alpha-quantile for pinball loss).\n+\n+Like R², the best possible score is 1.0 and it can be negative (because the\n+model can be arbitrarily worse). A constant model that always predicts\n+:math:`y_{\\text{null}}`, disregarding the input features, would get a D² score\n+of 0.0.\n+\n+D² Tweedie score\n+^^^^^^^^^^^^^^^^\n+\n+The :func:`d2_tweedie_score` function implements the special case of D² \n+where :math:`\\text{dev}(y, \\hat{y})` is the Tweedie deviance, see :ref:`mean_tweedie_deviance`. \n+It is also known as D² Tweedie and is related to McFadden's likelihood ratio index.\n+\n+The argument ``power`` defines the Tweedie power as for\n+:func:`mean_tweedie_deviance`. Note that for `power=0`,\n+:func:`d2_tweedie_score` equals :func:`r2_score` (for single targets).\n+\n+A scorer object with a specific choice of ``power`` can be built by::\n+\n+ >>> from sklearn.metrics import d2_tweedie_score, make_scorer\n+ >>> d2_tweedie_score_15 = make_scorer(d2_tweedie_score, power=1.5)\n+\n+D² pinball score\n+^^^^^^^^^^^^^^^^^^^^^\n+\n+The :func:`d2_pinball_score` function implements the special case\n+of D² with the pinball loss, see :ref:`pinball_loss`, i.e.:\n+\n+.. math::\n+\n+ \\text{dev}(y, \\hat{y}) = \\text{pinball}(y, \\hat{y}).\n+\n+The argument ``alpha`` defines the slope of the pinball loss as for\n+:func:`mean_pinball_loss` (:ref:`pinball_loss`). It determines the \n+quantile level ``alpha`` for which the pinball loss and also D²\n+are optimal. Note that for `alpha=0.5` (the default) :func:`d2_pinball_score`\n+equals :func:`d2_absolute_error_score`.\n+\n+A scorer object with a specific choice of ``alpha`` can be built by::\n+\n+ >>> from sklearn.metrics import d2_pinball_score, make_scorer\n+ >>> d2_pinball_score_08 = make_scorer(d2_pinball_score, alpha=0.8)\n+\n+D² absolute error score\n+^^^^^^^^^^^^^^^^^^^^^^^\n+\n+The :func:`d2_absolute_error_score` function implements the special case of\n+the :ref:`mean_absolute_error`:\n+\n+.. math::\n+\n+ \\text{dev}(y, \\hat{y}) = \\text{MAE}(y, \\hat{y}).\n+\n+Here are some usage examples of the :func:`d2_absolute_error_score` function::\n+\n+ >>> from sklearn.metrics import d2_absolute_error_score\n+ >>> y_true = [3, -0.5, 2, 7]\n+ >>> y_pred = [2.5, 0.0, 2, 8]\n+ >>> d2_absolute_error_score(y_true, y_pred)\n+ 0.764...\n+ >>> y_true = [1, 2, 3]\n+ >>> y_pred = [1, 2, 3]\n+ >>> d2_absolute_error_score(y_true, y_pred)\n+ 1.0\n+ >>> y_true = [1, 2, 3]\n+ >>> y_pred = [2, 2, 2]\n+ >>> d2_absolute_error_score(y_true, y_pred)\n+ 0.0\n+\n \n .. _clustering_metrics:\n \n" }, { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex b9ab45e1d344a..85053e5a68679 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -630,6 +630,14 @@ Changelog\n instead of the finite approximation (`1.0` and `0.0` respectively) currently\n returned by default. :pr:`17266` by :user:`Sylvain Marié <smarie>`.\n \n+- |Feature| :func:`d2_pinball_score` and :func:`d2_absolute_error_score`\n+ calculate the :math:`D^2` regression score for the pinball loss and the\n+ absolute error respectively. :func:`d2_absolute_error_score` is a special case\n+ of :func:`d2_pinball_score` with a fixed quantile parameter `alpha=0.5`\n+ for ease of use and discovery. The :math:`D^2` scores are generalizations\n+ of the `r2_score` and can be interpeted as the fraction of deviance explained.\n+ :pr:`22118` by :user:`Ohad Michel <ohadmich>`\n+\n - |Enhancement| :func:`metrics.top_k_accuracy_score` raises an improved error\n message when `y_true` is binary and `y_score` is 2d. :pr:`22284` by `Thomas Fan`_.\n \n" } ]
1.01
142e388fa004e3367fdfc0be4a194be0d0c61c8c
[]
[ "sklearn/metrics/tests/test_common.py::test_symmetric_metric[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric21]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric37]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric41]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric29]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric29]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric3]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric33]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric38]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[log_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric30]", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.75-exponential]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric40]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric27]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_zeroes[recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric19]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-label_ranking_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[f1_score]", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[label_ranking_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-hinge_loss]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric18]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[samples_precision_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_representation_invariance", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric7]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-matthews_corrcoef]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-brier_score_loss]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric40]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-recall_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric35]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[d2_pinball_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_compound_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-ndcg_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-d2_pinball_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric39]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-accuracy_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[r2_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-hamming_loss]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-<lambda>]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric39]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric32]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric31]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric11]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[dcg_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric19]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[f0.5_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric31]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric9]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-recall_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric24]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[weighted_ovo_roc_auc]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric20]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-dcg_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric31]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-label_ranking_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-label_ranking_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric8]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric30]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric22]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[unnormalized_multilabel_confusion_matrix_sample]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric14]", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric18]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric22]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_f2_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[samples_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[object-average_precision_score-True]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-d2_pinball_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[d2_absolute_error_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-dcg_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[label_ranking_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_normalize_option_multiclass_classification[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[str-precision_score-False]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric7]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric21]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric10]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[str-brier_score_loss-True]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[hinge_loss]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric30]", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[d2_pinball_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-label_ranking_loss]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric20]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[d2_tweedie_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric38]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric14]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric2]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric3]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[d2_pinball_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-accuracy_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[r2_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_ones[f2_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric7]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[normalized_confusion_matrix]", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.05-normal]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[label_ranking_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[d2_absolute_error_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric35]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-label_ranking_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[log_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-roc_auc_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[samples_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric16]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[samples_recall_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-log_loss]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric18]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric34]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[matthews_corrcoef_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[partial_roc_auc]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric36]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-hamming_loss]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-d2_absolute_error_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric23]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-coverage_error]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric2]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric23]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-coverage_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-label_ranking_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric16]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-roc_auc_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-d2_pinball_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[recall_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[det_curve]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric7]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric21]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric19]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[object-recall_score-False]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric25]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric35]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[roc_auc_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric7]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-average_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric40]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric26]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric24]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric12]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[ovo_roc_auc]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric7]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric41]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[str-roc_curve-True]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-f1_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[hamming_loss]", "sklearn/metrics/tests/test_regression.py::test_mean_absolute_percentage_error", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric29]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[r2_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric41]", "sklearn/metrics/tests/test_common.py::test_single_sample[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric29]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-label_ranking_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-matthews_corrcoef]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-accuracy_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric31]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[samples_f1_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric26]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric41]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[r2_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric14]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[recall_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[d2_tweedie_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[log_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric15]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_roc_auc]", "sklearn/metrics/tests/test_common.py::test_single_sample[explained_variance_score]", "sklearn/metrics/tests/test_regression.py::test_multioutput_regression", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric33]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-log_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric19]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric35]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric31]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric18]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric13]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric33]", "sklearn/metrics/tests/test_regression.py::test__check_reg_targets_exception", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-d2_absolute_error_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric15]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_precision_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[roc_auc_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-d2_pinball_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric40]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[object-f1_score-False]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric10]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric8]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_single_sample[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_zeroes[f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric22]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric10]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric39]", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric9]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric38]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[hinge_loss]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_ones[f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-label_ranking_loss]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[r2_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric16]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-hinge_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-max_error]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_normal_deviance]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric13]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric10]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[partial_roc_auc]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[samples_roc_auc]", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[max_error]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-log_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-matthews_corrcoef]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric16]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric23]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric41]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric25]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[hinge_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric27]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric36]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_recall_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[log_loss]", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[r2_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric40]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[samples_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric29]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric27]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric3]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric32]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-d2_absolute_error_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric12]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[d2_tweedie_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric39]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric21]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric26]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[d2_absolute_error_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric37]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[samples_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[log_loss]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[mean_compound_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric30]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[weighted_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric20]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[micro_precision_score]", "sklearn/metrics/tests/test_regression.py::test_regression_metrics_at_limits", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric40]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric10]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_compound_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[matthews_corrcoef]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric24]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[coverage_error]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[weighted_roc_auc]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[average_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric20]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_roc_auc]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_averaging_multiclass[recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric28]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric35]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric10]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric19]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[dcg_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_roc_auc]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric2]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[coverage_error]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-mean_squared_error]", "sklearn/metrics/tests/test_regression.py::test__check_reg_targets", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[samples_recall_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric35]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric37]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric32]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric25]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric12]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric36]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[d2_pinball_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[samples_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric10]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[r2_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-precision_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[object-precision_recall_curve-True]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric39]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[roc_curve]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric28]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-roc_auc_score]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[object-roc_curve-True]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric40]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric22]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[log_loss]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[micro_roc_auc]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_ones[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric11]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_roc_auc]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric7]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric31]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric16]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric25]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-dcg_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric15]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric32]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[weighted_ovo_roc_auc]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric28]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric37]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-f1_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric17]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric3]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[partial_roc_auc]", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.75-normal]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-max_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric26]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[micro_roc_auc]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-brier_score_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric22]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric37]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric32]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[balanced_accuracy_score]", "sklearn/metrics/tests/test_regression.py::test_regression_custom_weights", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-hamming_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric18]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric33]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[samples_f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric34]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric28]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[ndcg_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric3]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-brier_score_loss]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[r2_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-precision_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[precision_recall_curve]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-ndcg_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric34]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric41]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[ovo_roc_auc]", "sklearn/metrics/tests/test_common.py::test_averaging_multiclass[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric34]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[average_precision_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[hinge_loss]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[samples_f2_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[samples_recall_score]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[d2_absolute_error_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_zeroes[precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-matthews_corrcoef]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_normal_deviance]", "sklearn/metrics/tests/test_common.py::test_single_sample[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric11]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[partial_roc_auc]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[<lambda>]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_ones[f0.5_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric9]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[matthews_corrcoef_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric25]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric30]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[ndcg_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-recall_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric7]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric32]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric38]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[weighted_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric34]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[dcg_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric32]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-log_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[samples_f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric19]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric3]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[samples_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-roc_auc_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric36]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance_multilabel_and_multioutput", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_roc_auc]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[str-precision_recall_curve-True]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric21]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric34]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-<lambda>]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric15]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_normal_deviance]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric35]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multiclass[f1_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric38]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[micro_f2_score]", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.05-uniform]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric33]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric36]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric34]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[d2_absolute_error_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[brier_score_loss]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric34]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric18]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-median_absolute_error]", "sklearn/metrics/tests/test_regression.py::test_mean_squared_error_multioutput_raw_value_squared", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric15]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric18]", "sklearn/metrics/tests/test_common.py::test_single_sample[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-precision_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric3]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-average_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[object-jaccard_score-False]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[d2_absolute_error_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[d2_pinball_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric11]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[hinge_loss]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-hamming_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric30]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric8]", "sklearn/metrics/tests/test_common.py::test_normalize_option_binary_classification[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric22]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[roc_auc_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[d2_tweedie_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[hinge_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[f1_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[samples_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric17]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric25]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-jaccard_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-jaccard_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric34]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric2]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric23]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric36]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric35]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-hinge_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric16]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric16]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric27]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_normal_deviance]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric30]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[str-f1_score-False]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric31]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric12]", "sklearn/metrics/tests/test_common.py::test_single_sample[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric16]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric30]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric33]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-recall_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric30]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[samples_precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[micro_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-<lambda>]", "sklearn/metrics/tests/test_common.py::test_single_sample[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric2]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_symmetry_consistency", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric24]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multiclass[f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric28]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric35]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-label_ranking_loss]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_ones[precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-<lambda>]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[micro_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[samples_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-precision_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[log_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric23]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[samples_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric39]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric26]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[precision_recall_curve]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[weighted_ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric31]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric13]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[f0.5_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_ovo_roc_auc]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_single_sample[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric34]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric16]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[d2_absolute_error_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-mean_squared_error]", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.5-uniform]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-matthews_corrcoef]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[object-metric3-False]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric37]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric21]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-d2_absolute_error_score]", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.05-exponential]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[recall_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-hinge_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[samples_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[d2_pinball_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[label_ranking_loss]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[f2_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-coverage_error]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-label_ranking_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric29]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[d2_absolute_error_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric24]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric27]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[samples_f2_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric14]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[samples_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[d2_tweedie_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric31]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_average_precision_score]", "sklearn/metrics/tests/test_regression.py::test_regression_multioutput_array", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric32]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-hamming_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-log_loss]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[roc_auc_score]", "sklearn/metrics/tests/test_regression.py::test_tweedie_deviance_continuity", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-matthews_corrcoef]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric30]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-ndcg_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric30]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric34]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric3]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[samples_roc_auc]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[object-precision_score-False]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[macro_precision_score]", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.75-lognormal]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric8]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[average_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric35]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric23]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric22]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric36]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-brier_score_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric2]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-hamming_loss]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[precision_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[d2_pinball_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[matthews_corrcoef_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric30]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[mean_normal_deviance]", "sklearn/metrics/tests/test_common.py::test_single_sample[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-recall_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric16]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric30]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric37]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[r2_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric20]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-max_error]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric8]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric20]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric15]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric11]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric27]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_ones[recall_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric12]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[max_error]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric26]", "sklearn/metrics/tests/test_common.py::test_no_averaging_labels", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_zeroes[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[d2_absolute_error_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric38]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric10]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-brier_score_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric17]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[d2_pinball_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric7]", "sklearn/metrics/tests/test_common.py::test_single_sample[d2_pinball_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[matthews_corrcoef_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-confusion_matrix]", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.75-uniform]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric10]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[str-metric3-False]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric3]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[label_ranking_loss]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric28]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_ovo_roc_auc]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-matthews_corrcoef]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric17]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric23]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_zeroes[f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric10]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_averaging_multiclass[f0.5_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[ndcg_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric39]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[partial_roc_auc]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric18]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-max_error]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[d2_pinball_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[roc_auc_score]", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.5-exponential]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric34]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric31]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric17]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric18]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[samples_precision_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric18]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric27]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[f2_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric14]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[ovo_roc_auc]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric29]", "sklearn/metrics/tests/test_common.py::test_normalize_option_multilabel_classification[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-coverage_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric33]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-average_precision_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_compound_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-max_error]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric40]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-d2_absolute_error_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric13]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric7]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[samples_recall_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[label_ranking_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_normalize_option_multiclass_classification[top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric15]", "sklearn/metrics/tests/test_common.py::test_single_sample[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-average_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-coverage_error]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric35]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample[matthews_corrcoef_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric18]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[str-jaccard_score-False]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric3]", "sklearn/metrics/tests/test_regression.py::test_regression_single_sample[d2_tweedie_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-hinge_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample[r2_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric23]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric35]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[average_precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[log_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric21]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-ndcg_score]", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.5-normal]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[average_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-ndcg_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-<lambda>]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric20]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric9]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric16]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-dcg_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric31]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric34]", "sklearn/metrics/tests/test_common.py::test_single_sample[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric19]", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[d2_absolute_error_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric36]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric28]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric9]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric24]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric3]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[samples_roc_auc]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_compound_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric41]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric3]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-<lambda>]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric18]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[weighted_roc_auc]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-recall_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[log_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric28]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[det_curve]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[samples_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[samples_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric2]", "sklearn/metrics/tests/test_common.py::test_averaging_multiclass[precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-hamming_loss]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric31]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric7]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric22]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-f1_score]", "sklearn/metrics/tests/test_common.py::test_normalize_option_multilabel_classification[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric37]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[object-brier_score_loss-True]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[matthews_corrcoef_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric21]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-dcg_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[samples_f2_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_zeroes[f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[str-average_precision_score-True]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric20]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric31]", "sklearn/metrics/tests/test_common.py::test_single_sample[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[top_k_accuracy_score]", "sklearn/metrics/tests/test_regression.py::test_regression_metrics", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[weighted_ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[recall_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[matthews_corrcoef_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-recall_score]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[str-recall_score-False]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric24]", "sklearn/metrics/tests/test_common.py::test_averaging_binary_multilabel_all_zeroes", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric35]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[hinge_loss]", "sklearn/metrics/tests/test_common.py::test_normalize_option_binary_classification[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[brier_score_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[coverage_error]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric26]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric7]", "sklearn/metrics/tests/test_common.py::test_single_sample[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric3]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_normalize_option_binary_classification[top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric25]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric18]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric27]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_single_sample[max_error]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[max_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric29]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[samples_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-average_precision_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[ovo_roc_auc]", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.5-lognormal]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric10]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-<lambda>]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric10]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-d2_pinball_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric7]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[samples_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric41]", "sklearn/metrics/tests/test_common.py::test_normalize_option_multiclass_classification[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric33]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric19]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric16]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric24]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-roc_auc_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric26]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric2]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[roc_curve]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric16]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric15]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric38]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-jaccard_score]", "sklearn/metrics/tests/test_regression.py::test_regression_single_sample[d2_pinball_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric39]", "sklearn/metrics/tests/test_regression.py::test_dummy_quantile_parameter_tuning", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[matthews_corrcoef_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[macro_f0.5_score]", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.05-lognormal]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric38]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[hamming_loss]", "sklearn/metrics/tests/test_regression.py::test_regression_single_sample[r2_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric13]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true6-y_score6-metric25]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric10]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/modules/classes.rst", "old_path": "a/doc/modules/classes.rst", "new_path": "b/doc/modules/classes.rst", "metadata": "diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst\nindex b7000bcf7cbb2..c3e6c4f2f674b 100644\n--- a/doc/modules/classes.rst\n+++ b/doc/modules/classes.rst\n@@ -996,6 +996,8 @@ details.\n metrics.mean_tweedie_deviance\n metrics.d2_tweedie_score\n metrics.mean_pinball_loss\n+ metrics.d2_pinball_score\n+ metrics.d2_absolute_error_score\n \n Multilabel ranking metrics\n --------------------------\n" }, { "path": "doc/modules/model_evaluation.rst", "old_path": "a/doc/modules/model_evaluation.rst", "new_path": "b/doc/modules/model_evaluation.rst", "metadata": "diff --git a/doc/modules/model_evaluation.rst b/doc/modules/model_evaluation.rst\nindex a1fce2d3454dc..8468dce3f93c5 100644\n--- a/doc/modules/model_evaluation.rst\n+++ b/doc/modules/model_evaluation.rst\n@@ -101,6 +101,9 @@ Scoring Function\n 'neg_mean_poisson_deviance' :func:`metrics.mean_poisson_deviance`\n 'neg_mean_gamma_deviance' :func:`metrics.mean_gamma_deviance`\n 'neg_mean_absolute_percentage_error' :func:`metrics.mean_absolute_percentage_error`\n+'d2_absolute_error_score' :func:`metrics.d2_absolute_error_score`\n+'d2_pinball_score' :func:`metrics.d2_pinball_score`\n+'d2_tweedie_score' :func:`metrics.d2_tweedie_score`\n ==================================== ============================================== ==================================\n \n \n@@ -1968,7 +1971,8 @@ The :mod:`sklearn.metrics` module implements several loss, score, and utility\n functions to measure regression performance. Some of those have been enhanced\n to handle the multioutput case: :func:`mean_squared_error`,\n :func:`mean_absolute_error`, :func:`r2_score`,\n-:func:`explained_variance_score` and :func:`mean_pinball_loss`.\n+:func:`explained_variance_score`, :func:`mean_pinball_loss`, :func:`d2_pinball_score`\n+and :func:`d2_absolute_error_score`.\n \n \n These functions have an ``multioutput`` keyword argument which specifies the\n@@ -2370,8 +2374,8 @@ is defined as\n \\sum_{i=0}^{n_\\text{samples} - 1}\n \\begin{cases}\n (y_i-\\hat{y}_i)^2, & \\text{for }p=0\\text{ (Normal)}\\\\\n- 2(y_i \\log(y/\\hat{y}_i) + \\hat{y}_i - y_i), & \\text{for}p=1\\text{ (Poisson)}\\\\\n- 2(\\log(\\hat{y}_i/y_i) + y_i/\\hat{y}_i - 1), & \\text{for}p=2\\text{ (Gamma)}\\\\\n+ 2(y_i \\log(y/\\hat{y}_i) + \\hat{y}_i - y_i), & \\text{for }p=1\\text{ (Poisson)}\\\\\n+ 2(\\log(\\hat{y}_i/y_i) + y_i/\\hat{y}_i - 1), & \\text{for }p=2\\text{ (Gamma)}\\\\\n 2\\left(\\frac{\\max(y_i,0)^{2-p}}{(1-p)(2-p)}-\n \\frac{y\\,\\hat{y}^{1-p}_i}{1-p}+\\frac{\\hat{y}^{2-p}_i}{2-p}\\right),\n & \\text{otherwise}\n@@ -2414,34 +2418,6 @@ the difference in errors decreases. Finally, by setting, ``power=2``::\n we would get identical errors. The deviance when ``power=2`` is thus only\n sensitive to relative errors.\n \n-.. _d2_tweedie_score:\n-\n-D² score, the coefficient of determination\n--------------------------------------------\n-\n-The :func:`d2_tweedie_score` function computes the percentage of deviance\n-explained. It is a generalization of R², where the squared error is replaced by\n-the Tweedie deviance. D², also known as McFadden's likelihood ratio index, is\n-calculated as\n-\n-.. math::\n-\n- D^2(y, \\hat{y}) = 1 - \\frac{\\text{D}(y, \\hat{y})}{\\text{D}(y, \\bar{y})} \\,.\n-\n-The argument ``power`` defines the Tweedie power as for\n-:func:`mean_tweedie_deviance`. Note that for `power=0`,\n-:func:`d2_tweedie_score` equals :func:`r2_score` (for single targets).\n-\n-Like R², the best possible score is 1.0 and it can be negative (because the\n-model can be arbitrarily worse). A constant model that always predicts the\n-expected value of y, disregarding the input features, would get a D² score\n-of 0.0.\n-\n-A scorer object with a specific choice of ``power`` can be built by::\n-\n- >>> from sklearn.metrics import d2_tweedie_score, make_scorer\n- >>> d2_tweedie_score_15 = make_scorer(d2_tweedie_score, power=1.5)\n-\n .. _pinball_loss:\n \n Pinball loss\n@@ -2506,6 +2482,93 @@ explained in the example linked below.\n hyper-parameters of quantile regression models on data with non-symmetric\n noise and outliers.\n \n+.. _d2_score:\n+\n+D² score\n+--------\n+\n+The D² score computes the fraction of deviance explained. \n+It is a generalization of R², where the squared error is generalized and replaced \n+by a deviance of choice :math:`\\text{dev}(y, \\hat{y})`\n+(e.g., Tweedie, pinball or mean absolute error). D² is a form of a *skill score*.\n+It is calculated as\n+\n+.. math::\n+\n+ D^2(y, \\hat{y}) = 1 - \\frac{\\text{dev}(y, \\hat{y})}{\\text{dev}(y, y_{\\text{null}})} \\,.\n+\n+Where :math:`y_{\\text{null}}` is the optimal prediction of an intercept-only model\n+(e.g., the mean of `y_true` for the Tweedie case, the median for absolute \n+error and the alpha-quantile for pinball loss).\n+\n+Like R², the best possible score is 1.0 and it can be negative (because the\n+model can be arbitrarily worse). A constant model that always predicts\n+:math:`y_{\\text{null}}`, disregarding the input features, would get a D² score\n+of 0.0.\n+\n+D² Tweedie score\n+^^^^^^^^^^^^^^^^\n+\n+The :func:`d2_tweedie_score` function implements the special case of D² \n+where :math:`\\text{dev}(y, \\hat{y})` is the Tweedie deviance, see :ref:`mean_tweedie_deviance`. \n+It is also known as D² Tweedie and is related to McFadden's likelihood ratio index.\n+\n+The argument ``power`` defines the Tweedie power as for\n+:func:`mean_tweedie_deviance`. Note that for `power=0`,\n+:func:`d2_tweedie_score` equals :func:`r2_score` (for single targets).\n+\n+A scorer object with a specific choice of ``power`` can be built by::\n+\n+ >>> from sklearn.metrics import d2_tweedie_score, make_scorer\n+ >>> d2_tweedie_score_15 = make_scorer(d2_tweedie_score, power=1.5)\n+\n+D² pinball score\n+^^^^^^^^^^^^^^^^^^^^^\n+\n+The :func:`d2_pinball_score` function implements the special case\n+of D² with the pinball loss, see :ref:`pinball_loss`, i.e.:\n+\n+.. math::\n+\n+ \\text{dev}(y, \\hat{y}) = \\text{pinball}(y, \\hat{y}).\n+\n+The argument ``alpha`` defines the slope of the pinball loss as for\n+:func:`mean_pinball_loss` (:ref:`pinball_loss`). It determines the \n+quantile level ``alpha`` for which the pinball loss and also D²\n+are optimal. Note that for `alpha=0.5` (the default) :func:`d2_pinball_score`\n+equals :func:`d2_absolute_error_score`.\n+\n+A scorer object with a specific choice of ``alpha`` can be built by::\n+\n+ >>> from sklearn.metrics import d2_pinball_score, make_scorer\n+ >>> d2_pinball_score_08 = make_scorer(d2_pinball_score, alpha=0.8)\n+\n+D² absolute error score\n+^^^^^^^^^^^^^^^^^^^^^^^\n+\n+The :func:`d2_absolute_error_score` function implements the special case of\n+the :ref:`mean_absolute_error`:\n+\n+.. math::\n+\n+ \\text{dev}(y, \\hat{y}) = \\text{MAE}(y, \\hat{y}).\n+\n+Here are some usage examples of the :func:`d2_absolute_error_score` function::\n+\n+ >>> from sklearn.metrics import d2_absolute_error_score\n+ >>> y_true = [3, -0.5, 2, 7]\n+ >>> y_pred = [2.5, 0.0, 2, 8]\n+ >>> d2_absolute_error_score(y_true, y_pred)\n+ 0.764...\n+ >>> y_true = [1, 2, 3]\n+ >>> y_pred = [1, 2, 3]\n+ >>> d2_absolute_error_score(y_true, y_pred)\n+ 1.0\n+ >>> y_true = [1, 2, 3]\n+ >>> y_pred = [2, 2, 2]\n+ >>> d2_absolute_error_score(y_true, y_pred)\n+ 0.0\n+\n \n .. _clustering_metrics:\n \n" }, { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex b9ab45e1d344a..85053e5a68679 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -630,6 +630,14 @@ Changelog\n instead of the finite approximation (`1.0` and `0.0` respectively) currently\n returned by default. :pr:`<PRID>` by :user:`<NAME>`.\n \n+- |Feature| :func:`d2_pinball_score` and :func:`d2_absolute_error_score`\n+ calculate the :math:`D^2` regression score for the pinball loss and the\n+ absolute error respectively. :func:`d2_absolute_error_score` is a special case\n+ of :func:`d2_pinball_score` with a fixed quantile parameter `alpha=0.5`\n+ for ease of use and discovery. The :math:`D^2` scores are generalizations\n+ of the `r2_score` and can be interpeted as the fraction of deviance explained.\n+ :pr:`<PRID>` by :user:`<NAME>`\n+\n - |Enhancement| :func:`metrics.top_k_accuracy_score` raises an improved error\n message when `y_true` is binary and `y_score` is 2d. :pr:`<PRID>` by `<NAME>`_.\n \n" } ]
diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst index b7000bcf7cbb2..c3e6c4f2f674b 100644 --- a/doc/modules/classes.rst +++ b/doc/modules/classes.rst @@ -996,6 +996,8 @@ details. metrics.mean_tweedie_deviance metrics.d2_tweedie_score metrics.mean_pinball_loss + metrics.d2_pinball_score + metrics.d2_absolute_error_score Multilabel ranking metrics -------------------------- diff --git a/doc/modules/model_evaluation.rst b/doc/modules/model_evaluation.rst index a1fce2d3454dc..8468dce3f93c5 100644 --- a/doc/modules/model_evaluation.rst +++ b/doc/modules/model_evaluation.rst @@ -101,6 +101,9 @@ Scoring Function 'neg_mean_poisson_deviance' :func:`metrics.mean_poisson_deviance` 'neg_mean_gamma_deviance' :func:`metrics.mean_gamma_deviance` 'neg_mean_absolute_percentage_error' :func:`metrics.mean_absolute_percentage_error` +'d2_absolute_error_score' :func:`metrics.d2_absolute_error_score` +'d2_pinball_score' :func:`metrics.d2_pinball_score` +'d2_tweedie_score' :func:`metrics.d2_tweedie_score` ==================================== ============================================== ================================== @@ -1968,7 +1971,8 @@ The :mod:`sklearn.metrics` module implements several loss, score, and utility functions to measure regression performance. Some of those have been enhanced to handle the multioutput case: :func:`mean_squared_error`, :func:`mean_absolute_error`, :func:`r2_score`, -:func:`explained_variance_score` and :func:`mean_pinball_loss`. +:func:`explained_variance_score`, :func:`mean_pinball_loss`, :func:`d2_pinball_score` +and :func:`d2_absolute_error_score`. These functions have an ``multioutput`` keyword argument which specifies the @@ -2370,8 +2374,8 @@ is defined as \sum_{i=0}^{n_\text{samples} - 1} \begin{cases} (y_i-\hat{y}_i)^2, & \text{for }p=0\text{ (Normal)}\\ - 2(y_i \log(y/\hat{y}_i) + \hat{y}_i - y_i), & \text{for}p=1\text{ (Poisson)}\\ - 2(\log(\hat{y}_i/y_i) + y_i/\hat{y}_i - 1), & \text{for}p=2\text{ (Gamma)}\\ + 2(y_i \log(y/\hat{y}_i) + \hat{y}_i - y_i), & \text{for }p=1\text{ (Poisson)}\\ + 2(\log(\hat{y}_i/y_i) + y_i/\hat{y}_i - 1), & \text{for }p=2\text{ (Gamma)}\\ 2\left(\frac{\max(y_i,0)^{2-p}}{(1-p)(2-p)}- \frac{y\,\hat{y}^{1-p}_i}{1-p}+\frac{\hat{y}^{2-p}_i}{2-p}\right), & \text{otherwise} @@ -2414,34 +2418,6 @@ the difference in errors decreases. Finally, by setting, ``power=2``:: we would get identical errors. The deviance when ``power=2`` is thus only sensitive to relative errors. -.. _d2_tweedie_score: - -D² score, the coefficient of determination -------------------------------------------- - -The :func:`d2_tweedie_score` function computes the percentage of deviance -explained. It is a generalization of R², where the squared error is replaced by -the Tweedie deviance. D², also known as McFadden's likelihood ratio index, is -calculated as - -.. math:: - - D^2(y, \hat{y}) = 1 - \frac{\text{D}(y, \hat{y})}{\text{D}(y, \bar{y})} \,. - -The argument ``power`` defines the Tweedie power as for -:func:`mean_tweedie_deviance`. Note that for `power=0`, -:func:`d2_tweedie_score` equals :func:`r2_score` (for single targets). - -Like R², the best possible score is 1.0 and it can be negative (because the -model can be arbitrarily worse). A constant model that always predicts the -expected value of y, disregarding the input features, would get a D² score -of 0.0. - -A scorer object with a specific choice of ``power`` can be built by:: - - >>> from sklearn.metrics import d2_tweedie_score, make_scorer - >>> d2_tweedie_score_15 = make_scorer(d2_tweedie_score, power=1.5) - .. _pinball_loss: Pinball loss @@ -2506,6 +2482,93 @@ explained in the example linked below. hyper-parameters of quantile regression models on data with non-symmetric noise and outliers. +.. _d2_score: + +D² score +-------- + +The D² score computes the fraction of deviance explained. +It is a generalization of R², where the squared error is generalized and replaced +by a deviance of choice :math:`\text{dev}(y, \hat{y})` +(e.g., Tweedie, pinball or mean absolute error). D² is a form of a *skill score*. +It is calculated as + +.. math:: + + D^2(y, \hat{y}) = 1 - \frac{\text{dev}(y, \hat{y})}{\text{dev}(y, y_{\text{null}})} \,. + +Where :math:`y_{\text{null}}` is the optimal prediction of an intercept-only model +(e.g., the mean of `y_true` for the Tweedie case, the median for absolute +error and the alpha-quantile for pinball loss). + +Like R², the best possible score is 1.0 and it can be negative (because the +model can be arbitrarily worse). A constant model that always predicts +:math:`y_{\text{null}}`, disregarding the input features, would get a D² score +of 0.0. + +D² Tweedie score +^^^^^^^^^^^^^^^^ + +The :func:`d2_tweedie_score` function implements the special case of D² +where :math:`\text{dev}(y, \hat{y})` is the Tweedie deviance, see :ref:`mean_tweedie_deviance`. +It is also known as D² Tweedie and is related to McFadden's likelihood ratio index. + +The argument ``power`` defines the Tweedie power as for +:func:`mean_tweedie_deviance`. Note that for `power=0`, +:func:`d2_tweedie_score` equals :func:`r2_score` (for single targets). + +A scorer object with a specific choice of ``power`` can be built by:: + + >>> from sklearn.metrics import d2_tweedie_score, make_scorer + >>> d2_tweedie_score_15 = make_scorer(d2_tweedie_score, power=1.5) + +D² pinball score +^^^^^^^^^^^^^^^^^^^^^ + +The :func:`d2_pinball_score` function implements the special case +of D² with the pinball loss, see :ref:`pinball_loss`, i.e.: + +.. math:: + + \text{dev}(y, \hat{y}) = \text{pinball}(y, \hat{y}). + +The argument ``alpha`` defines the slope of the pinball loss as for +:func:`mean_pinball_loss` (:ref:`pinball_loss`). It determines the +quantile level ``alpha`` for which the pinball loss and also D² +are optimal. Note that for `alpha=0.5` (the default) :func:`d2_pinball_score` +equals :func:`d2_absolute_error_score`. + +A scorer object with a specific choice of ``alpha`` can be built by:: + + >>> from sklearn.metrics import d2_pinball_score, make_scorer + >>> d2_pinball_score_08 = make_scorer(d2_pinball_score, alpha=0.8) + +D² absolute error score +^^^^^^^^^^^^^^^^^^^^^^^ + +The :func:`d2_absolute_error_score` function implements the special case of +the :ref:`mean_absolute_error`: + +.. math:: + + \text{dev}(y, \hat{y}) = \text{MAE}(y, \hat{y}). + +Here are some usage examples of the :func:`d2_absolute_error_score` function:: + + >>> from sklearn.metrics import d2_absolute_error_score + >>> y_true = [3, -0.5, 2, 7] + >>> y_pred = [2.5, 0.0, 2, 8] + >>> d2_absolute_error_score(y_true, y_pred) + 0.764... + >>> y_true = [1, 2, 3] + >>> y_pred = [1, 2, 3] + >>> d2_absolute_error_score(y_true, y_pred) + 1.0 + >>> y_true = [1, 2, 3] + >>> y_pred = [2, 2, 2] + >>> d2_absolute_error_score(y_true, y_pred) + 0.0 + .. _clustering_metrics: diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index b9ab45e1d344a..85053e5a68679 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -630,6 +630,14 @@ Changelog instead of the finite approximation (`1.0` and `0.0` respectively) currently returned by default. :pr:`<PRID>` by :user:`<NAME>`. +- |Feature| :func:`d2_pinball_score` and :func:`d2_absolute_error_score` + calculate the :math:`D^2` regression score for the pinball loss and the + absolute error respectively. :func:`d2_absolute_error_score` is a special case + of :func:`d2_pinball_score` with a fixed quantile parameter `alpha=0.5` + for ease of use and discovery. The :math:`D^2` scores are generalizations + of the `r2_score` and can be interpeted as the fraction of deviance explained. + :pr:`<PRID>` by :user:`<NAME>` + - |Enhancement| :func:`metrics.top_k_accuracy_score` raises an improved error message when `y_true` is binary and `y_score` is 2d. :pr:`<PRID>` by `<NAME>`_.
scikit-learn/scikit-learn
scikit-learn__scikit-learn-22284
https://github.com/scikit-learn/scikit-learn/pull/22284
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index f0ccdc999c175..ec1d546da6712 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -592,6 +592,9 @@ Changelog instead of the finite approximation (`1.0` and `0.0` respectively) currently returned by default. :pr:`17266` by :user:`Sylvain Marié <smarie>`. +- |Enhancement| :func:`metrics.top_k_accuracy_score` raises an improved error + message when `y_true` is binary and `y_score` is 2d. :pr:`22284` by `Thomas Fan`_. + - |API| :class:`metrics.DistanceMetric` has been moved from :mod:`sklearn.neighbors` to :mod:`sklearn.metric`. Using `neighbors.DistanceMetric` for imports is still valid for diff --git a/sklearn/metrics/_ranking.py b/sklearn/metrics/_ranking.py index 7aa4ff4b8884c..ac14d219d28dd 100644 --- a/sklearn/metrics/_ranking.py +++ b/sklearn/metrics/_ranking.py @@ -1707,15 +1707,21 @@ def top_k_accuracy_score( y_type = type_of_target(y_true, input_name="y_true") if y_type == "binary" and labels is not None and len(labels) > 2: y_type = "multiclass" - y_score = check_array(y_score, ensure_2d=False) - y_score = column_or_1d(y_score) if y_type == "binary" else y_score - check_consistent_length(y_true, y_score, sample_weight) - if y_type not in {"binary", "multiclass"}: raise ValueError( f"y type must be 'binary' or 'multiclass', got '{y_type}' instead." ) + y_score = check_array(y_score, ensure_2d=False) + if y_type == "binary": + if y_score.ndim == 2 and y_score.shape[1] != 1: + raise ValueError( + "`y_true` is binary while y_score is 2d with" + f" {y_score.shape[1]} classes. If `y_true` does not contain all the" + " labels, `labels` must be provided." + ) + y_score = column_or_1d(y_score) + check_consistent_length(y_true, y_score, sample_weight) y_score_n_classes = y_score.shape[1] if y_score.ndim == 2 else 2 if labels is None:
diff --git a/sklearn/metrics/tests/test_ranking.py b/sklearn/metrics/tests/test_ranking.py index 1b30afb174d28..bb000fddb55ef 100644 --- a/sklearn/metrics/tests/test_ranking.py +++ b/sklearn/metrics/tests/test_ranking.py @@ -1890,46 +1890,85 @@ def test_top_k_accuracy_score_warning(y_true, k): @pytest.mark.parametrize( - "y_true, labels, msg", + "y_true, y_score, labels, msg", [ ( [0, 0.57, 1, 2], + [ + [0.2, 0.1, 0.7], + [0.4, 0.3, 0.3], + [0.3, 0.4, 0.3], + [0.4, 0.5, 0.1], + ], None, "y type must be 'binary' or 'multiclass', got 'continuous'", ), ( [0, 1, 2, 3], + [ + [0.2, 0.1, 0.7], + [0.4, 0.3, 0.3], + [0.3, 0.4, 0.3], + [0.4, 0.5, 0.1], + ], None, r"Number of classes in 'y_true' \(4\) not equal to the number of " r"classes in 'y_score' \(3\).", ), ( ["c", "c", "a", "b"], + [ + [0.2, 0.1, 0.7], + [0.4, 0.3, 0.3], + [0.3, 0.4, 0.3], + [0.4, 0.5, 0.1], + ], ["a", "b", "c", "c"], "Parameter 'labels' must be unique.", ), - (["c", "c", "a", "b"], ["a", "c", "b"], "Parameter 'labels' must be ordered."), + ( + ["c", "c", "a", "b"], + [ + [0.2, 0.1, 0.7], + [0.4, 0.3, 0.3], + [0.3, 0.4, 0.3], + [0.4, 0.5, 0.1], + ], + ["a", "c", "b"], + "Parameter 'labels' must be ordered.", + ), ( [0, 0, 1, 2], + [ + [0.2, 0.1, 0.7], + [0.4, 0.3, 0.3], + [0.3, 0.4, 0.3], + [0.4, 0.5, 0.1], + ], [0, 1, 2, 3], r"Number of given labels \(4\) not equal to the number of classes in " r"'y_score' \(3\).", ), ( [0, 0, 1, 2], + [ + [0.2, 0.1, 0.7], + [0.4, 0.3, 0.3], + [0.3, 0.4, 0.3], + [0.4, 0.5, 0.1], + ], [0, 1, 3], "'y_true' contains labels not in parameter 'labels'.", ), + ( + [0, 1], + [[0.5, 0.2, 0.2], [0.3, 0.4, 0.2]], + None, + "`y_true` is binary while y_score is 2d with 3 classes. If" + " `y_true` does not contain all the labels, `labels` must be provided", + ), ], ) -def test_top_k_accuracy_score_error(y_true, labels, msg): - y_score = np.array( - [ - [0.2, 0.1, 0.7], - [0.4, 0.3, 0.3], - [0.3, 0.4, 0.3], - [0.4, 0.5, 0.1], - ] - ) +def test_top_k_accuracy_score_error(y_true, y_score, labels, msg): with pytest.raises(ValueError, match=msg): top_k_accuracy_score(y_true, y_score, k=2, labels=labels)
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex f0ccdc999c175..ec1d546da6712 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -592,6 +592,9 @@ Changelog\n instead of the finite approximation (`1.0` and `0.0` respectively) currently\n returned by default. :pr:`17266` by :user:`Sylvain Marié <smarie>`.\n \n+- |Enhancement| :func:`metrics.top_k_accuracy_score` raises an improved error\n+ message when `y_true` is binary and `y_score` is 2d. :pr:`22284` by `Thomas Fan`_.\n+\n - |API| :class:`metrics.DistanceMetric` has been moved from\n :mod:`sklearn.neighbors` to :mod:`sklearn.metric`.\n Using `neighbors.DistanceMetric` for imports is still valid for\n" } ]
1.01
4aeb1adec376b92876b37548fff5fdd8f3ee6cf4
[ "sklearn/metrics/tests/test_ranking.py::test_det_curve_tie_handling[y_true4-y_score4-expected_fpr4-expected_fnr4]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-5-20]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-2-1]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_binary[y_score0-1-1]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_bad_input[y_true0-y_pred0-inconsistent numbers of samples]", "sklearn/metrics/tests/test_ranking.py::test_lrap_sample_weighting_zero_labels", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_error[multi_class='ovp' is not supported for multiclass ROC AUC, multi_class must be in \\\\('ovo', 'ovr'\\\\)-kwargs4]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_multiclass_with_labels[True-y_true1-0.5-labels1]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_multiclass_with_labels[False-y_true3-0.75-labels3]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_multiclass_with_labels[False-y_true0-0.75-labels0]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_bad_input[y_true4-y_pred4-pos_label is not specified]", "sklearn/metrics/tests/test_ranking.py::test_coverage_tie_handling", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_ties[y_true0-1-0.25]", "sklearn/metrics/tests/test_ranking.py::test_precision_recall_curve", "sklearn/metrics/tests/test_ranking.py::test_ranking_loss_ties_handling", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true7-y_score7-expected_fpr7-expected_fnr7]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovo_roc_auc_toydata[y_true2-labels2]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_sanity_check", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true6-y_score6-expected_fpr6-expected_fnr6]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_tie_handling[y_true6-y_score6-expected_fpr6-expected_fnr6]", "sklearn/metrics/tests/test_ranking.py::test_ranking_appropriate_input_shape", "sklearn/metrics/tests/test_ranking.py::test_det_curve_tie_handling[y_true7-y_score7-expected_fpr7-expected_fnr7]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true10-y_score10-expected_fpr10-expected_fnr10]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_error[Partial AUC computation not available in multiclass setting, 'max_fpr' must be set to `None`, received `max_fpr=0.5` instead-kwargs3]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_binary[y_score4-1-0.5]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-Parameter 'labels' must be ordered-y_true3-labels3]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-Number of given labels, 2, not equal to the number of columns in 'y_score', 3-y_true4-labels4]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_multiclass_with_labels[True-y_true3-0.75-labels3]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_constant_scores[1]", "sklearn/metrics/tests/test_ranking.py::test_auc", "sklearn/metrics/tests/test_ranking.py::test_roc_curve[False]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve_end_points", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_binary[y_score3-1-1]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-5-2]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve_drop_intermediate", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_increasing", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovr_roc_auc_toydata[y_true2-labels2]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true18-y_score18-expected_fpr18-expected_fnr18]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true19-y_score19-expected_fpr19-expected_fnr19]", "sklearn/metrics/tests/test_ranking.py::test_label_ranking_avp[label_ranking_average_precision_score-check_lrap_only_ties]", "sklearn/metrics/tests/test_ranking.py::test_binary_clf_curve_zero_sample_weight[precision_recall_curve]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve_one_label", "sklearn/metrics/tests/test_ranking.py::test_det_curve_tie_handling[y_true0-y_score0-expected_fpr0-expected_fnr0]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovo_roc_auc_toydata[y_true0-labels0]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-Number of given labels, 4, not equal to the number of columns in 'y_score', 3-y_true6-labels6]", "sklearn/metrics/tests/test_ranking.py::test_precision_recall_curve_toydata", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-Number of classes in y_true not equal to the number of columns in 'y_score'-y_true2-None]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-'y_true' contains labels not in parameter 'labels'-y_true8-labels8]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_perfect_scores[y_true1]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-5-1]", "sklearn/metrics/tests/test_ranking.py::test_ndcg_invariant", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_multiclass_with_labels[True-y_true0-0.75-labels0]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-Number of given labels, 2, not equal to the number of columns in 'y_score', 3-y_true5-labels5]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true13-y_score13-expected_fpr13-expected_fnr13]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score[y_true1-2-0.5]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovo_roc_auc_toydata_binary[y_true1-labels1]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_pos_label", "sklearn/metrics/tests/test_ranking.py::test_binary_clf_curve_zero_sample_weight[det_curve]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve_toydata", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_error[y_true4-y_score4-labels4-Number of given labels \\\\(4\\\\) not equal to the number of classes in 'y_score' \\\\(3\\\\).]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true1-y_score1-expected_fpr1-expected_fnr1]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-5-8]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true15-y_score15-expected_fpr15-expected_fnr15]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_ties[y_true1-2-0.5]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovo_roc_auc_toydata[y_true3-None]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovr_roc_auc_toydata[y_true0-None]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true11-y_score11-expected_fpr11-expected_fnr11]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-2-20]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovo_roc_auc_toydata[y_true1-None]", "sklearn/metrics/tests/test_ranking.py::test_coverage_error", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_binary[y_score5-2-1]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-'y_true' contains labels not in parameter 'labels'-y_true9-labels9]", "sklearn/metrics/tests/test_ranking.py::test_label_ranking_loss", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_ties[y_true2-3-1]", "sklearn/metrics/tests/test_ranking.py::test_partial_roc_auc_score", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true14-y_score14-expected_fpr14-expected_fnr14]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-Parameter 'labels' must be unique-y_true1-labels1]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-'y_true' contains labels not in parameter 'labels'-y_true9-labels9]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-Number of given labels, 2, not equal to the number of columns in 'y_score', 3-y_true5-labels5]", "sklearn/metrics/tests/test_ranking.py::test_binary_clf_curve_implicit_pos_label[roc_curve]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-Number of given labels, 4, not equal to the number of columns in 'y_score', 3-y_true6-labels6]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve_confidence", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_error[y_true5-y_score5-labels5-'y_true' contains labels not in parameter 'labels'.]", "sklearn/metrics/tests/test_ranking.py::test_label_ranking_avp[_my_lrap-check_zero_or_all_relevant_labels]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-10-2]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_constant_scores[0]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_perfect_scores[y_true3]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_binary[y_score1-1-0.5]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score[y_true2-3-0.75]", "sklearn/metrics/tests/test_ranking.py::test_ndcg_toy_examples[False]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true17-y_score17-expected_fpr17-expected_fnr17]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_tie_handling[y_true2-y_score2-expected_fpr2-expected_fnr2]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_constant_scores[0.5]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-Parameter 'labels' must be unique-y_true0-labels0]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-'y_true' contains labels not in parameter 'labels'-y_true10-labels10]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_multiclass_with_labels[False-y_true2-0.5-labels2]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true5-y_score5-expected_fpr5-expected_fnr5]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_warning[y_true1-5]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_error[y_true1-y_score1-None-Number of classes in 'y_true' \\\\(4\\\\) not equal to the number of classes in 'y_score' \\\\(3\\\\).]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_perfect_scores[y_true0]", "sklearn/metrics/tests/test_ranking.py::test_dcg_score", "sklearn/metrics/tests/test_ranking.py::test_average_precision_score_pos_label_errors", "sklearn/metrics/tests/test_ranking.py::test_label_ranking_avp[_my_lrap-check_lrap_only_ties]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-2-2]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-10-8]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_error[y_true3-y_score3-labels3-Parameter 'labels' must be ordered.]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true0-y_score0-expected_fpr0-expected_fnr0]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-Number of classes in y_true not equal to the number of columns in 'y_score'-y_true2-None]", "sklearn/metrics/tests/test_ranking.py::test_binary_clf_curve_multiclass_error[det_curve]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-'y_true' contains labels not in parameter 'labels'-y_true10-labels10]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-Number of given labels, 4, not equal to the number of columns in 'y_score', 3-y_true7-labels7]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_error[y_true0-y_score0-None-y type must be 'binary' or 'multiclass', got 'continuous']", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-Number of given labels, 2, not equal to the number of columns in 'y_score', 3-y_true4-labels4]", "sklearn/metrics/tests/test_ranking.py::test_label_ranking_avp[_my_lrap-check_lrap_toy]", "sklearn/metrics/tests/test_ranking.py::test_label_ranking_avp[_my_lrap-check_lrap_without_tie_and_increasing_score]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovo_roc_auc_toydata_binary[y_true0-labels0]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_error[sample_weight is not supported for multiclass one-vs-one ROC AUC, 'sample_weight' must be None in this case-kwargs2]", "sklearn/metrics/tests/test_ranking.py::test_ndcg_ignore_ties_with_k", "sklearn/metrics/tests/test_ranking.py::test_ndcg_score", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-Parameter 'labels' must be unique-y_true1-labels1]", "sklearn/metrics/tests/test_ranking.py::test_label_ranking_avp[label_ranking_average_precision_score-check_lrap_without_tie_and_increasing_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-Parameter 'labels' must be ordered-y_true3-labels3]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_bad_input[y_true3-y_pred3-Only one class present in y_true]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_error[average must be one of \\\\('macro', 'weighted', None\\\\) for multiclass problems-kwargs0]", "sklearn/metrics/tests/test_ranking.py::test_binary_clf_curve_multiclass_error[precision_recall_curve]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_error[average must be one of \\\\('macro', 'weighted', None\\\\) for multiclass problems-kwargs1]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true9-y_score9-expected_fpr9-expected_fnr9]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovr_roc_auc_toydata[y_true3-labels3]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve_multi", "sklearn/metrics/tests/test_ranking.py::test_auc_score_non_binary_class", "sklearn/metrics/tests/test_ranking.py::test_det_curve_tie_handling[y_true3-y_score3-expected_fpr3-expected_fnr3]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-2-8]", "sklearn/metrics/tests/test_ranking.py::test_binary_clf_curve_implicit_pos_label[det_curve]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_multiclass_with_labels[True-y_true2-0.5-labels2]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_perfect_scores[y_true2]", "sklearn/metrics/tests/test_ranking.py::test_binary_clf_curve_implicit_pos_label[precision_recall_curve]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_tie_handling[y_true5-y_score5-expected_fpr5-expected_fnr5]", "sklearn/metrics/tests/test_ranking.py::test_label_ranking_avp[label_ranking_average_precision_score-check_lrap_toy]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_perfect_scores[y_true4]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true12-y_score12-expected_fpr12-expected_fnr12]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true16-y_score16-expected_fpr16-expected_fnr16]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_constant_scores[0.75]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve[True]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true3-y_score3-expected_fpr3-expected_fnr3]", "sklearn/metrics/tests/test_ranking.py::test_score_scale_invariance", "sklearn/metrics/tests/test_ranking.py::test_lrap_error_raised", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true2-y_score2-expected_fpr2-expected_fnr2]", "sklearn/metrics/tests/test_ranking.py::test_binary_clf_curve_zero_sample_weight[roc_curve]", "sklearn/metrics/tests/test_ranking.py::test_roc_returns_consistency", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-Parameter 'labels' must be unique-y_true0-labels0]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_multiclass_with_labels[False-y_true1-0.5-labels1]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_binary[y_score2-2-1]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-Number of given labels, 4, not equal to the number of columns in 'y_score', 3-y_true7-labels7]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true8-y_score8-expected_fpr8-expected_fnr8]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_tie_handling[y_true1-y_score1-expected_fpr1-expected_fnr1]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovr_roc_auc_toydata[y_true1-None]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true4-y_score4-expected_fpr4-expected_fnr4]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score[y_true0-1-0.25]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-'y_true' contains labels not in parameter 'labels'-y_true8-labels8]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-10-20]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_error[y_true2-y_score2-labels2-Parameter 'labels' must be unique.]", "sklearn/metrics/tests/test_ranking.py::test_auc_errors", "sklearn/metrics/tests/test_ranking.py::test_dcg_ties", "sklearn/metrics/tests/test_ranking.py::test_roc_curve_hard", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_error[multi_class must be in \\\\('ovo', 'ovr'\\\\)-kwargs5]", "sklearn/metrics/tests/test_ranking.py::test_binary_clf_curve_multiclass_error[roc_curve]", "sklearn/metrics/tests/test_ranking.py::test_label_ranking_avp[label_ranking_average_precision_score-check_zero_or_all_relevant_labels]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-10-1]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_constant_scores[0.25]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve_fpr_tpr_increasing", "sklearn/metrics/tests/test_ranking.py::test_det_curve_bad_input[y_true2-y_pred2-Only one class present in y_true]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_bad_input[y_true1-y_pred1-inconsistent numbers of samples]", "sklearn/metrics/tests/test_ranking.py::test_ndcg_toy_examples[True]", "sklearn/metrics/tests/test_ranking.py::test_average_precision_constant_values", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_warning[y_true0-4]" ]
[ "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_error[y_true6-y_score6-None-`y_true` is binary while y_score is 2d with 3 classes. If `y_true` does not contain all the labels, `labels` must be provided]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex f0ccdc999c175..ec1d546da6712 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -592,6 +592,9 @@ Changelog\n instead of the finite approximation (`1.0` and `0.0` respectively) currently\n returned by default. :pr:`<PRID>` by :user:`<NAME>`.\n \n+- |Enhancement| :func:`metrics.top_k_accuracy_score` raises an improved error\n+ message when `y_true` is binary and `y_score` is 2d. :pr:`<PRID>` by `<NAME>`_.\n+\n - |API| :class:`metrics.DistanceMetric` has been moved from\n :mod:`sklearn.neighbors` to :mod:`sklearn.metric`.\n Using `neighbors.DistanceMetric` for imports is still valid for\n" } ]
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index f0ccdc999c175..ec1d546da6712 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -592,6 +592,9 @@ Changelog instead of the finite approximation (`1.0` and `0.0` respectively) currently returned by default. :pr:`<PRID>` by :user:`<NAME>`. +- |Enhancement| :func:`metrics.top_k_accuracy_score` raises an improved error + message when `y_true` is binary and `y_score` is 2d. :pr:`<PRID>` by `<NAME>`_. + - |API| :class:`metrics.DistanceMetric` has been moved from :mod:`sklearn.neighbors` to :mod:`sklearn.metric`. Using `neighbors.DistanceMetric` for imports is still valid for
scikit-learn/scikit-learn
scikit-learn__scikit-learn-19158
https://github.com/scikit-learn/scikit-learn/pull/19158
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 1b83354e5c0c2..38d7709e8ea24 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -422,6 +422,10 @@ Changelog - |Fix| :func:`metrics.silhouette_score` now supports integer input for precomputed distances. :pr:`22108` by `Thomas Fan`_. +- |Enhancement| :func:`metrics.roc_auc_score` now supports ``average=None`` + in the multiclass case when ``multiclass='ovr'`` which will return the score + per class. :pr:`19158` by :user:`Nicki Skafte <SkafteNicki>`. + :mod:`sklearn.manifold` ....................... diff --git a/sklearn/metrics/_ranking.py b/sklearn/metrics/_ranking.py index 6e625169dd2cd..22975c672101a 100644 --- a/sklearn/metrics/_ranking.py +++ b/sklearn/metrics/_ranking.py @@ -414,10 +414,11 @@ class scores must correspond to the order of ``labels``, average : {'micro', 'macro', 'samples', 'weighted'} or None, \ default='macro' - If ``None``, the scores for each class are returned. Otherwise, - this determines the type of averaging performed on the data: + If ``None``, the scores for each class are returned. + Otherwise, this determines the type of averaging performed on the data. Note: multiclass ROC AUC currently only handles the 'macro' and - 'weighted' averages. + 'weighted' averages. For multiclass targets, `average=None` + is only implemented for `multi_class='ovo'`. ``'micro'``: Calculate metrics globally by considering each element of the label @@ -631,7 +632,7 @@ def _multiclass_roc_auc_score( ) # validation for multiclass parameter specifications - average_options = ("macro", "weighted") + average_options = ("macro", "weighted", None) if average not in average_options: raise ValueError( "average must be one of {0} for multiclass problems".format(average_options) @@ -645,6 +646,11 @@ def _multiclass_roc_auc_score( "in {1}".format(multi_class, multiclass_options) ) + if average is None and multi_class == "ovo": + raise NotImplementedError( + "average=None is not implemented for multi_class='ovo'." + ) + if labels is not None: labels = column_or_1d(labels) classes = _unique(labels)
diff --git a/sklearn/metrics/tests/test_ranking.py b/sklearn/metrics/tests/test_ranking.py index 01de37b189733..1b30afb174d28 100644 --- a/sklearn/metrics/tests/test_ranking.py +++ b/sklearn/metrics/tests/test_ranking.py @@ -526,6 +526,11 @@ def test_multiclass_ovo_roc_auc_toydata(y_true, labels): ovo_weighted_score, ) + # Check that average=None raises NotImplemented error + error_message = "average=None is not implemented for multi_class='ovo'." + with pytest.raises(NotImplementedError, match=error_message): + roc_auc_score(y_true, y_scores, labels=labels, multi_class="ovo", average=None) + @pytest.mark.parametrize( "y_true, labels", @@ -583,8 +588,13 @@ def test_multiclass_ovr_roc_auc_toydata(y_true, labels): out_0 = roc_auc_score([1, 0, 0, 0], y_scores[:, 0]) out_1 = roc_auc_score([0, 1, 0, 0], y_scores[:, 1]) out_2 = roc_auc_score([0, 0, 1, 1], y_scores[:, 2]) - result_unweighted = (out_0 + out_1 + out_2) / 3.0 + assert_almost_equal( + roc_auc_score(y_true, y_scores, multi_class="ovr", labels=labels, average=None), + [out_0, out_1, out_2], + ) + # Compute unweighted results (default behaviour) + result_unweighted = (out_0 + out_1 + out_2) / 3.0 assert_almost_equal( roc_auc_score(y_true, y_scores, multi_class="ovr", labels=labels), result_unweighted, @@ -677,14 +687,14 @@ def test_roc_auc_score_multiclass_labels_error(msg, y_true, labels, multi_class) [ ( ( - r"average must be one of \('macro', 'weighted'\) for " + r"average must be one of \('macro', 'weighted', None\) for " r"multiclass problems" ), {"average": "samples", "multi_class": "ovo"}, ), ( ( - r"average must be one of \('macro', 'weighted'\) for " + r"average must be one of \('macro', 'weighted', None\) for " r"multiclass problems" ), {"average": "micro", "multi_class": "ovr"},
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 1b83354e5c0c2..38d7709e8ea24 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -422,6 +422,10 @@ Changelog\n - |Fix| :func:`metrics.silhouette_score` now supports integer input for precomputed\n distances. :pr:`22108` by `Thomas Fan`_.\n \n+- |Enhancement| :func:`metrics.roc_auc_score` now supports ``average=None``\n+ in the multiclass case when ``multiclass='ovr'`` which will return the score\n+ per class. :pr:`19158` by :user:`Nicki Skafte <SkafteNicki>`.\n+\n :mod:`sklearn.manifold`\n .......................\n \n" } ]
1.01
b0067e0e7e0ae095592bc3a9a8cb7ba9e200c1be
[ "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-Number of given labels, 2, not equal to the number of columns in 'y_score', 3-y_true4-labels4]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_tie_handling[y_true7-y_score7-expected_fpr7-expected_fnr7]", "sklearn/metrics/tests/test_ranking.py::test_binary_clf_curve_multiclass_error[roc_curve]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_binary[y_score2-2-1]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-10-20]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_error[Partial AUC computation not available in multiclass setting, 'max_fpr' must be set to `None`, received `max_fpr=0.5` instead-kwargs3]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_error[y_true1-None-Number of classes in 'y_true' \\\\(4\\\\) not equal to the number of classes in 'y_score' \\\\(3\\\\).]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_binary[y_score3-1-1]", "sklearn/metrics/tests/test_ranking.py::test_binary_clf_curve_implicit_pos_label[det_curve]", "sklearn/metrics/tests/test_ranking.py::test_partial_roc_auc_score", "sklearn/metrics/tests/test_ranking.py::test_label_ranking_avp[label_ranking_average_precision_score-check_lrap_only_ties]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-5-8]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-Parameter 'labels' must be unique-y_true0-labels0]", "sklearn/metrics/tests/test_ranking.py::test_dcg_score", "sklearn/metrics/tests/test_ranking.py::test_average_precision_constant_values", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-'y_true' contains labels not in parameter 'labels'-y_true9-labels9]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-Number of given labels, 2, not equal to the number of columns in 'y_score', 3-y_true5-labels5]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true14-y_score14-expected_fpr14-expected_fnr14]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_perfect_scores[y_true1]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_error[y_true5-labels5-'y_true' contains labels not in parameter 'labels'.]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovo_roc_auc_toydata_binary[y_true1-labels1]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true13-y_score13-expected_fpr13-expected_fnr13]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-2-8]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-Parameter 'labels' must be ordered-y_true3-labels3]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-5-1]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve_toydata", "sklearn/metrics/tests/test_ranking.py::test_det_curve_tie_handling[y_true1-y_score1-expected_fpr1-expected_fnr1]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve_multi", "sklearn/metrics/tests/test_ranking.py::test_det_curve_tie_handling[y_true2-y_score2-expected_fpr2-expected_fnr2]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve_hard", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true4-y_score4-expected_fpr4-expected_fnr4]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true7-y_score7-expected_fpr7-expected_fnr7]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score[y_true0-1-0.25]", "sklearn/metrics/tests/test_ranking.py::test_binary_clf_curve_zero_sample_weight[precision_recall_curve]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true1-y_score1-expected_fpr1-expected_fnr1]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true16-y_score16-expected_fpr16-expected_fnr16]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-5-20]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_tie_handling[y_true4-y_score4-expected_fpr4-expected_fnr4]", "sklearn/metrics/tests/test_ranking.py::test_precision_recall_curve_toydata", "sklearn/metrics/tests/test_ranking.py::test_det_curve_tie_handling[y_true6-y_score6-expected_fpr6-expected_fnr6]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-Number of given labels, 4, not equal to the number of columns in 'y_score', 3-y_true7-labels7]", "sklearn/metrics/tests/test_ranking.py::test_ndcg_ignore_ties_with_k", "sklearn/metrics/tests/test_ranking.py::test_ranking_appropriate_input_shape", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true19-y_score19-expected_fpr19-expected_fnr19]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_sanity_check", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_error[y_true4-labels4-Number of given labels \\\\(4\\\\) not equal to the number of classes in 'y_score' \\\\(3\\\\).]", "sklearn/metrics/tests/test_ranking.py::test_score_scale_invariance", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_multiclass_with_labels[False-y_true0-0.75-labels0]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve_confidence", "sklearn/metrics/tests/test_ranking.py::test_average_precision_score_pos_label_errors", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-Number of given labels, 2, not equal to the number of columns in 'y_score', 3-y_true4-labels4]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve[False]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true15-y_score15-expected_fpr15-expected_fnr15]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_multiclass_with_labels[True-y_true3-0.75-labels3]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_constant_scores[1]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-Number of given labels, 4, not equal to the number of columns in 'y_score', 3-y_true6-labels6]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true17-y_score17-expected_fpr17-expected_fnr17]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true6-y_score6-expected_fpr6-expected_fnr6]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-'y_true' contains labels not in parameter 'labels'-y_true10-labels10]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_binary[y_score5-2-1]", "sklearn/metrics/tests/test_ranking.py::test_label_ranking_loss", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-Number of classes in y_true not equal to the number of columns in 'y_score'-y_true2-None]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_constant_scores[0.25]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true3-y_score3-expected_fpr3-expected_fnr3]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_perfect_scores[y_true0]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_error[y_true2-labels2-Parameter 'labels' must be unique.]", "sklearn/metrics/tests/test_ranking.py::test_ndcg_toy_examples[True]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-'y_true' contains labels not in parameter 'labels'-y_true8-labels8]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve[True]", "sklearn/metrics/tests/test_ranking.py::test_ndcg_invariant", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-Number of given labels, 4, not equal to the number of columns in 'y_score', 3-y_true6-labels6]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true0-y_score0-expected_fpr0-expected_fnr0]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true10-y_score10-expected_fpr10-expected_fnr10]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_ties[y_true1-2-0.5]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_error[y_true3-labels3-Parameter 'labels' must be ordered.]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_warning[y_true0-4]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-Number of given labels, 2, not equal to the number of columns in 'y_score', 3-y_true5-labels5]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true5-y_score5-expected_fpr5-expected_fnr5]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_constant_scores[0]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_bad_input[y_true4-y_pred4-pos_label is not specified]", "sklearn/metrics/tests/test_ranking.py::test_coverage_error", "sklearn/metrics/tests/test_ranking.py::test_det_curve_pos_label", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_binary[y_score4-1-0.5]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_perfect_scores[y_true2]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_ties[y_true2-3-1]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve_drop_intermediate", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true8-y_score8-expected_fpr8-expected_fnr8]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_increasing", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_error[sample_weight is not supported for multiclass one-vs-one ROC AUC, 'sample_weight' must be None in this case-kwargs2]", "sklearn/metrics/tests/test_ranking.py::test_binary_clf_curve_multiclass_error[precision_recall_curve]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_tie_handling[y_true5-y_score5-expected_fpr5-expected_fnr5]", "sklearn/metrics/tests/test_ranking.py::test_roc_returns_consistency", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score[y_true1-2-0.5]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_multiclass_with_labels[True-y_true0-0.75-labels0]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score[y_true2-3-0.75]", "sklearn/metrics/tests/test_ranking.py::test_binary_clf_curve_multiclass_error[det_curve]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_bad_input[y_true0-y_pred0-inconsistent numbers of samples]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-Parameter 'labels' must be unique-y_true1-labels1]", "sklearn/metrics/tests/test_ranking.py::test_label_ranking_avp[_my_lrap-check_lrap_toy]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_binary[y_score0-1-1]", "sklearn/metrics/tests/test_ranking.py::test_binary_clf_curve_zero_sample_weight[det_curve]", "sklearn/metrics/tests/test_ranking.py::test_auc", "sklearn/metrics/tests/test_ranking.py::test_ndcg_toy_examples[False]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-'y_true' contains labels not in parameter 'labels'-y_true8-labels8]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_multiclass_with_labels[False-y_true3-0.75-labels3]", "sklearn/metrics/tests/test_ranking.py::test_ranking_loss_ties_handling", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-5-2]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_binary[y_score1-1-0.5]", "sklearn/metrics/tests/test_ranking.py::test_precision_recall_curve", "sklearn/metrics/tests/test_ranking.py::test_binary_clf_curve_implicit_pos_label[precision_recall_curve]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_multiclass_with_labels[True-y_true2-0.5-labels2]", "sklearn/metrics/tests/test_ranking.py::test_ndcg_score", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-10-1]", "sklearn/metrics/tests/test_ranking.py::test_label_ranking_avp[label_ranking_average_precision_score-check_lrap_toy]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-Parameter 'labels' must be unique-y_true0-labels0]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_ties[y_true0-1-0.25]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_error[y_true0-None-y type must be 'binary' or 'multiclass', got 'continuous']", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true9-y_score9-expected_fpr9-expected_fnr9]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve_one_label", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-10-8]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_error[multi_class must be in \\\\('ovo', 'ovr'\\\\)-kwargs5]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_constant_scores[0.75]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_warning[y_true1-5]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_bad_input[y_true1-y_pred1-inconsistent numbers of samples]", "sklearn/metrics/tests/test_ranking.py::test_label_ranking_avp[_my_lrap-check_lrap_only_ties]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-Parameter 'labels' must be unique-y_true1-labels1]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_tie_handling[y_true3-y_score3-expected_fpr3-expected_fnr3]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-2-1]", "sklearn/metrics/tests/test_ranking.py::test_dcg_ties", "sklearn/metrics/tests/test_ranking.py::test_auc_errors", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-Number of given labels, 4, not equal to the number of columns in 'y_score', 3-y_true7-labels7]", "sklearn/metrics/tests/test_ranking.py::test_label_ranking_avp[_my_lrap-check_zero_or_all_relevant_labels]", "sklearn/metrics/tests/test_ranking.py::test_binary_clf_curve_implicit_pos_label[roc_curve]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_constant_scores[0.5]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_multiclass_with_labels[False-y_true2-0.5-labels2]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_error[multi_class='ovp' is not supported for multiclass ROC AUC, multi_class must be in \\\\('ovo', 'ovr'\\\\)-kwargs4]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-'y_true' contains labels not in parameter 'labels'-y_true9-labels9]", "sklearn/metrics/tests/test_ranking.py::test_binary_clf_curve_zero_sample_weight[roc_curve]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_perfect_scores[y_true3]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_multiclass_with_labels[True-y_true1-0.5-labels1]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true18-y_score18-expected_fpr18-expected_fnr18]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-Parameter 'labels' must be ordered-y_true3-labels3]", "sklearn/metrics/tests/test_ranking.py::test_auc_score_non_binary_class", "sklearn/metrics/tests/test_ranking.py::test_roc_curve_end_points", "sklearn/metrics/tests/test_ranking.py::test_det_curve_tie_handling[y_true0-y_score0-expected_fpr0-expected_fnr0]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true12-y_score12-expected_fpr12-expected_fnr12]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_bad_input[y_true2-y_pred2-Only one class present in y_true]", "sklearn/metrics/tests/test_ranking.py::test_label_ranking_avp[label_ranking_average_precision_score-check_zero_or_all_relevant_labels]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_multiclass_with_labels[False-y_true1-0.5-labels1]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve_fpr_tpr_increasing", "sklearn/metrics/tests/test_ranking.py::test_label_ranking_avp[_my_lrap-check_lrap_without_tie_and_increasing_score]", "sklearn/metrics/tests/test_ranking.py::test_lrap_error_raised", "sklearn/metrics/tests/test_ranking.py::test_lrap_sample_weighting_zero_labels", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-2-2]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true2-y_score2-expected_fpr2-expected_fnr2]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_bad_input[y_true3-y_pred3-Only one class present in y_true]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true11-y_score11-expected_fpr11-expected_fnr11]", "sklearn/metrics/tests/test_ranking.py::test_coverage_tie_handling", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-Number of classes in y_true not equal to the number of columns in 'y_score'-y_true2-None]", "sklearn/metrics/tests/test_ranking.py::test_label_ranking_avp[label_ranking_average_precision_score-check_lrap_without_tie_and_increasing_score]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovo_roc_auc_toydata_binary[y_true0-labels0]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-'y_true' contains labels not in parameter 'labels'-y_true10-labels10]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-10-2]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_perfect_scores[y_true4]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-2-20]" ]
[ "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_error[average must be one of \\\\('macro', 'weighted', None\\\\) for multiclass problems-kwargs0]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovr_roc_auc_toydata[y_true0-None]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovo_roc_auc_toydata[y_true3-None]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovo_roc_auc_toydata[y_true1-None]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_error[average must be one of \\\\('macro', 'weighted', None\\\\) for multiclass problems-kwargs1]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovr_roc_auc_toydata[y_true3-labels3]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovo_roc_auc_toydata[y_true0-labels0]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovo_roc_auc_toydata[y_true2-labels2]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovr_roc_auc_toydata[y_true2-labels2]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovr_roc_auc_toydata[y_true1-None]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 1b83354e5c0c2..38d7709e8ea24 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -422,6 +422,10 @@ Changelog\n - |Fix| :func:`metrics.silhouette_score` now supports integer input for precomputed\n distances. :pr:`<PRID>` by `<NAME>`_.\n \n+- |Enhancement| :func:`metrics.roc_auc_score` now supports ``average=None``\n+ in the multiclass case when ``multiclass='ovr'`` which will return the score\n+ per class. :pr:`<PRID>` by :user:`<NAME>`.\n+\n :mod:`sklearn.manifold`\n .......................\n \n" } ]
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 1b83354e5c0c2..38d7709e8ea24 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -422,6 +422,10 @@ Changelog - |Fix| :func:`metrics.silhouette_score` now supports integer input for precomputed distances. :pr:`<PRID>` by `<NAME>`_. +- |Enhancement| :func:`metrics.roc_auc_score` now supports ``average=None`` + in the multiclass case when ``multiclass='ovr'`` which will return the score + per class. :pr:`<PRID>` by :user:`<NAME>`. + :mod:`sklearn.manifold` .......................
scikit-learn/scikit-learn
scikit-learn__scikit-learn-20753
https://github.com/scikit-learn/scikit-learn/pull/20753
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index c9076838744ee..e215f03c9a089 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -607,6 +607,13 @@ Changelog in the multiclass case when ``multiclass='ovr'`` which will return the score per class. :pr:`19158` by :user:`Nicki Skafte <SkafteNicki>`. +- |Enhancement| Adds `im_kw` parameter to + :func:`~metrics.ConfusionMatrixDisplay.from_estimator` + :func:`~metrics.ConfusionMatrixDisplay.from_predictions`, and + :func:`~metrics.ConfusionMatrixDisplay.plot`. The `im_kw` parameter is passed + to the `matplotlib.pyplot.imshow` call when plotting the confusion matrix. + :pr:`20753` by `Thomas Fan`_. + - |Fix| Fixed a bug in :func:`metrics.normalized_mutual_info_score` which could return unbounded values. :pr:`22635` by :user:`Jérémie du Boisberranger <jeremiedbb>`. diff --git a/sklearn/metrics/_plot/confusion_matrix.py b/sklearn/metrics/_plot/confusion_matrix.py index 081e0034b26a0..4c64e3e89f337 100644 --- a/sklearn/metrics/_plot/confusion_matrix.py +++ b/sklearn/metrics/_plot/confusion_matrix.py @@ -88,6 +88,7 @@ def plot( values_format=None, ax=None, colorbar=True, + im_kw=None, ): """Plot visualization. @@ -114,6 +115,9 @@ def plot( colorbar : bool, default=True Whether or not to add a colorbar to the plot. + im_kw : dict, default=None + Dict with keywords passed to `matplotlib.pyplot.imshow` call. + Returns ------- display : :class:`~sklearn.metrics.ConfusionMatrixDisplay` @@ -128,7 +132,12 @@ def plot( cm = self.confusion_matrix n_classes = cm.shape[0] - self.im_ = ax.imshow(cm, interpolation="nearest", cmap=cmap) + + default_im_kw = dict(interpolation="nearest", cmap=cmap) + im_kw = im_kw or {} + im_kw = {**default_im_kw, **im_kw} + + self.im_ = ax.imshow(cm, **im_kw) self.text_ = None cmap_min, cmap_max = self.im_.cmap(0), self.im_.cmap(1.0) @@ -193,6 +202,7 @@ def from_estimator( cmap="viridis", ax=None, colorbar=True, + im_kw=None, ): """Plot Confusion Matrix given an estimator and some data. @@ -258,6 +268,9 @@ def from_estimator( colorbar : bool, default=True Whether or not to add a colorbar to the plot. + im_kw : dict, default=None + Dict with keywords passed to `matplotlib.pyplot.imshow` call. + Returns ------- display : :class:`~sklearn.metrics.ConfusionMatrixDisplay` @@ -304,6 +317,7 @@ def from_estimator( xticks_rotation=xticks_rotation, values_format=values_format, colorbar=colorbar, + im_kw=im_kw, ) @classmethod @@ -322,6 +336,7 @@ def from_predictions( cmap="viridis", ax=None, colorbar=True, + im_kw=None, ): """Plot Confusion Matrix given true and predicted labels. @@ -384,6 +399,9 @@ def from_predictions( colorbar : bool, default=True Whether or not to add a colorbar to the plot. + im_kw : dict, default=None + Dict with keywords passed to `matplotlib.pyplot.imshow` call. + Returns ------- display : :class:`~sklearn.metrics.ConfusionMatrixDisplay` @@ -437,6 +455,7 @@ def from_predictions( xticks_rotation=xticks_rotation, values_format=values_format, colorbar=colorbar, + im_kw=im_kw, )
diff --git a/sklearn/metrics/_plot/tests/test_confusion_matrix_display.py b/sklearn/metrics/_plot/tests/test_confusion_matrix_display.py index 8db971fb26971..e826888b65f89 100644 --- a/sklearn/metrics/_plot/tests/test_confusion_matrix_display.py +++ b/sklearn/metrics/_plot/tests/test_confusion_matrix_display.py @@ -365,3 +365,15 @@ def test_colormap_max(pyplot): color = disp.text_[1, 0].get_color() assert_allclose(color, [1.0, 1.0, 1.0, 1.0]) + + +def test_im_kw_adjust_vmin_vmax(pyplot): + """Check that im_kw passes kwargs to imshow""" + + confusion_matrix = np.array([[0.48, 0.04], [0.08, 0.4]]) + disp = ConfusionMatrixDisplay(confusion_matrix) + disp.plot(im_kw=dict(vmin=0.0, vmax=0.8)) + + clim = disp.im_.get_clim() + assert clim[0] == pytest.approx(0.0) + assert clim[1] == pytest.approx(0.8)
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex c9076838744ee..e215f03c9a089 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -607,6 +607,13 @@ Changelog\n in the multiclass case when ``multiclass='ovr'`` which will return the score\n per class. :pr:`19158` by :user:`Nicki Skafte <SkafteNicki>`.\n \n+- |Enhancement| Adds `im_kw` parameter to\n+ :func:`~metrics.ConfusionMatrixDisplay.from_estimator`\n+ :func:`~metrics.ConfusionMatrixDisplay.from_predictions`, and\n+ :func:`~metrics.ConfusionMatrixDisplay.plot`. The `im_kw` parameter is passed\n+ to the `matplotlib.pyplot.imshow` call when plotting the confusion matrix.\n+ :pr:`20753` by `Thomas Fan`_.\n+\n - |Fix| Fixed a bug in :func:`metrics.normalized_mutual_info_score` which could return\n unbounded values. :pr:`22635` by :user:`Jérémie du Boisberranger <jeremiedbb>`.\n \n" } ]
1.01
3605c140af992b6ac52f04f1689c58509cc0b5b2
[ "sklearn/metrics/_plot/tests/test_confusion_matrix_display.py::test_confusion_matrix_display_custom_labels[False-True-from_predictions]", "sklearn/metrics/_plot/tests/test_confusion_matrix_display.py::test_confusion_matrix_display_plotting[False-all-from_predictions]", "sklearn/metrics/_plot/tests/test_confusion_matrix_display.py::test_confusion_matrix_display_plotting[False-true-from_estimator]", "sklearn/metrics/_plot/tests/test_confusion_matrix_display.py::test_confusion_matrix_display_plotting[False-pred-from_predictions]", "sklearn/metrics/_plot/tests/test_confusion_matrix_display.py::test_confusion_matrix_display_plotting[True-pred-from_estimator]", "sklearn/metrics/_plot/tests/test_confusion_matrix_display.py::test_confusion_matrix_display_invalid_option[from_predictions]", "sklearn/metrics/_plot/tests/test_confusion_matrix_display.py::test_confusion_matrix_display_custom_labels[False-False-from_predictions]", "sklearn/metrics/_plot/tests/test_confusion_matrix_display.py::test_confusion_matrix_display_plotting[False-None-from_estimator]", "sklearn/metrics/_plot/tests/test_confusion_matrix_display.py::test_confusion_matrix_pipeline[pipeline-clf]", "sklearn/metrics/_plot/tests/test_confusion_matrix_display.py::test_confusion_matrix_display_custom_labels[True-True-from_predictions]", "sklearn/metrics/_plot/tests/test_confusion_matrix_display.py::test_confusion_matrix_display[from_predictions]", "sklearn/metrics/_plot/tests/test_confusion_matrix_display.py::test_confusion_matrix_display_custom_labels[True-False-from_predictions]", "sklearn/metrics/_plot/tests/test_confusion_matrix_display.py::test_confusion_matrix_display_plotting[True-all-from_predictions]", "sklearn/metrics/_plot/tests/test_confusion_matrix_display.py::test_confusion_matrix_display_custom_labels[True-False-from_estimator]", "sklearn/metrics/_plot/tests/test_confusion_matrix_display.py::test_confusion_matrix_display_plotting[False-true-from_predictions]", "sklearn/metrics/_plot/tests/test_confusion_matrix_display.py::test_confusion_matrix_display_custom_labels[False-False-from_estimator]", "sklearn/metrics/_plot/tests/test_confusion_matrix_display.py::test_confusion_matrix_pipeline[clf]", "sklearn/metrics/_plot/tests/test_confusion_matrix_display.py::test_confusion_matrix_with_unknown_labels[from_estimator]", "sklearn/metrics/_plot/tests/test_confusion_matrix_display.py::test_confusion_matrix_display_invalid_option[from_estimator]", "sklearn/metrics/_plot/tests/test_confusion_matrix_display.py::test_confusion_matrix_display_plotting[True-true-from_predictions]", "sklearn/metrics/_plot/tests/test_confusion_matrix_display.py::test_confusion_matrix_display_custom_labels[False-True-from_estimator]", "sklearn/metrics/_plot/tests/test_confusion_matrix_display.py::test_confusion_matrix_display[from_estimator]", "sklearn/metrics/_plot/tests/test_confusion_matrix_display.py::test_confusion_matrix_with_unknown_labels[from_predictions]", "sklearn/metrics/_plot/tests/test_confusion_matrix_display.py::test_confusion_matrix_display_plotting[True-pred-from_predictions]", "sklearn/metrics/_plot/tests/test_confusion_matrix_display.py::test_confusion_matrix_display_plotting[True-true-from_estimator]", "sklearn/metrics/_plot/tests/test_confusion_matrix_display.py::test_confusion_matrix_display_validation", "sklearn/metrics/_plot/tests/test_confusion_matrix_display.py::test_confusion_matrix_display_plotting[True-all-from_estimator]", "sklearn/metrics/_plot/tests/test_confusion_matrix_display.py::test_colormap_max", "sklearn/metrics/_plot/tests/test_confusion_matrix_display.py::test_confusion_matrix_display_plotting[False-all-from_estimator]", "sklearn/metrics/_plot/tests/test_confusion_matrix_display.py::test_confusion_matrix_display_plotting[False-None-from_predictions]", "sklearn/metrics/_plot/tests/test_confusion_matrix_display.py::test_confusion_matrix_pipeline[pipeline-column_transformer-clf]", "sklearn/metrics/_plot/tests/test_confusion_matrix_display.py::test_confusion_matrix_display_plotting[True-None-from_estimator]", "sklearn/metrics/_plot/tests/test_confusion_matrix_display.py::test_confusion_matrix_contrast", "sklearn/metrics/_plot/tests/test_confusion_matrix_display.py::test_confusion_matrix_display_custom_labels[True-True-from_estimator]", "sklearn/metrics/_plot/tests/test_confusion_matrix_display.py::test_confusion_matrix_display_plotting[False-pred-from_estimator]", "sklearn/metrics/_plot/tests/test_confusion_matrix_display.py::test_confusion_matrix_display_plotting[True-None-from_predictions]" ]
[ "sklearn/metrics/_plot/tests/test_confusion_matrix_display.py::test_im_kw_adjust_vmin_vmax" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex c9076838744ee..e215f03c9a089 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -607,6 +607,13 @@ Changelog\n in the multiclass case when ``multiclass='ovr'`` which will return the score\n per class. :pr:`<PRID>` by :user:`<NAME>`.\n \n+- |Enhancement| Adds `im_kw` parameter to\n+ :func:`~metrics.ConfusionMatrixDisplay.from_estimator`\n+ :func:`~metrics.ConfusionMatrixDisplay.from_predictions`, and\n+ :func:`~metrics.ConfusionMatrixDisplay.plot`. The `im_kw` parameter is passed\n+ to the `matplotlib.pyplot.imshow` call when plotting the confusion matrix.\n+ :pr:`<PRID>` by `<NAME>`_.\n+\n - |Fix| Fixed a bug in :func:`metrics.normalized_mutual_info_score` which could return\n unbounded values. :pr:`<PRID>` by :user:`<NAME>`.\n \n" } ]
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index c9076838744ee..e215f03c9a089 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -607,6 +607,13 @@ Changelog in the multiclass case when ``multiclass='ovr'`` which will return the score per class. :pr:`<PRID>` by :user:`<NAME>`. +- |Enhancement| Adds `im_kw` parameter to + :func:`~metrics.ConfusionMatrixDisplay.from_estimator` + :func:`~metrics.ConfusionMatrixDisplay.from_predictions`, and + :func:`~metrics.ConfusionMatrixDisplay.plot`. The `im_kw` parameter is passed + to the `matplotlib.pyplot.imshow` call when plotting the confusion matrix. + :pr:`<PRID>` by `<NAME>`_. + - |Fix| Fixed a bug in :func:`metrics.normalized_mutual_info_score` which could return unbounded values. :pr:`<PRID>` by :user:`<NAME>`.
scikit-learn/scikit-learn
scikit-learn__scikit-learn-22203
https://github.com/scikit-learn/scikit-learn/pull/22203
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index d14cd278f67a1..5339f4a399490 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -382,6 +382,11 @@ Changelog splits failed. Similarly raise an error during grid-search when the fits for all the models and all the splits failed. :pr:`21026` by :user:`Loïc Estève <lesteve>`. +- |Enhancement| it is now possible to pass `scoring="matthews_corrcoef"` to all + model selection tools with a `scoring` argument to use the Matthews + correlation coefficient (MCC). :pr:`22203` by :user:`Olivier Grisel + <ogrisel>`. + - |Fix| :class:`model_selection.GridSearchCV`, :class:`model_selection.HalvingGridSearchCV` now validate input parameters in `fit` instead of `__init__`. diff --git a/sklearn/metrics/_scorer.py b/sklearn/metrics/_scorer.py index c5a725ad3a13b..7a20ffd32c954 100644 --- a/sklearn/metrics/_scorer.py +++ b/sklearn/metrics/_scorer.py @@ -46,6 +46,7 @@ brier_score_loss, jaccard_score, mean_absolute_percentage_error, + matthews_corrcoef, ) from .cluster import adjusted_rand_score @@ -705,6 +706,7 @@ def make_scorer( # Standard Classification Scores accuracy_scorer = make_scorer(accuracy_score) balanced_accuracy_scorer = make_scorer(balanced_accuracy_score) +matthews_corrcoef_scorer = make_scorer(matthews_corrcoef) # Score functions that need decision values top_k_accuracy_scorer = make_scorer( @@ -749,6 +751,7 @@ def make_scorer( explained_variance=explained_variance_scorer, r2=r2_scorer, max_error=max_error_scorer, + matthews_corrcoef=matthews_corrcoef_scorer, neg_median_absolute_error=neg_median_absolute_error_scorer, neg_mean_absolute_error=neg_mean_absolute_error_scorer, neg_mean_absolute_percentage_error=neg_mean_absolute_percentage_error_scorer, # noqa
diff --git a/sklearn/metrics/tests/test_score_objects.py b/sklearn/metrics/tests/test_score_objects.py index 65d8efebe775f..60ca7fdceee42 100644 --- a/sklearn/metrics/tests/test_score_objects.py +++ b/sklearn/metrics/tests/test_score_objects.py @@ -31,6 +31,7 @@ recall_score, roc_auc_score, top_k_accuracy_score, + matthews_corrcoef, ) from sklearn.metrics import cluster as cluster_module from sklearn.metrics import check_scoring @@ -102,6 +103,7 @@ "roc_auc_ovo", "roc_auc_ovr_weighted", "roc_auc_ovo_weighted", + "matthews_corrcoef", ] # All supervised cluster scorers (They behave like classification metric) @@ -393,6 +395,7 @@ def test_make_scorer(): ("jaccard_macro", partial(jaccard_score, average="macro")), ("jaccard_micro", partial(jaccard_score, average="micro")), ("top_k_accuracy", top_k_accuracy_score), + ("matthews_corrcoef", matthews_corrcoef), ], ) def test_classification_binary_scores(scorer_name, metric):
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex d14cd278f67a1..5339f4a399490 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -382,6 +382,11 @@ Changelog\n splits failed. Similarly raise an error during grid-search when the fits for\n all the models and all the splits failed. :pr:`21026` by :user:`Loïc Estève <lesteve>`.\n \n+- |Enhancement| it is now possible to pass `scoring=\"matthews_corrcoef\"` to all\n+ model selection tools with a `scoring` argument to use the Matthews\n+ correlation coefficient (MCC). :pr:`22203` by :user:`Olivier Grisel\n+ <ogrisel>`.\n+\n - |Fix| :class:`model_selection.GridSearchCV`,\n :class:`model_selection.HalvingGridSearchCV`\n now validate input parameters in `fit` instead of `__init__`.\n" } ]
1.01
be89eb75f250dc5a769281939ba01e570fb12ae1
[ "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[f1_macro]", "sklearn/metrics/tests/test_score_objects.py::test_classification_binary_scores[f1-f1_score]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[completeness_score]", "sklearn/metrics/tests/test_score_objects.py::test_regression_scorer_sample_weight", "sklearn/metrics/tests/test_score_objects.py::test_check_scoring_and_check_multimetric_scoring[multi_tuple]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[roc_auc]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[average_precision]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[f1_weighted]", "sklearn/metrics/tests/test_score_objects.py::test_check_scoring_and_check_multimetric_scoring[single_tuple]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[explained_variance]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[neg_brier_score]", "sklearn/metrics/tests/test_score_objects.py::test_classification_multiclass_scores[recall_macro-metric9]", "sklearn/metrics/tests/test_score_objects.py::test_classification_multiclass_scores[jaccard_micro-metric13]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[jaccard_micro]", "sklearn/metrics/tests/test_score_objects.py::test_multiclass_roc_proba_scorer[roc_auc_ovo-metric1]", "sklearn/metrics/tests/test_score_objects.py::test_check_scoring_and_check_multimetric_scoring_errors[empty dict]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[max_error]", "sklearn/metrics/tests/test_score_objects.py::test_check_scoring_and_check_multimetric_scoring_errors[tuple of callables]", "sklearn/metrics/tests/test_score_objects.py::test_classification_binary_scores[f1_micro-metric3]", "sklearn/metrics/tests/test_score_objects.py::test_classification_multiclass_scores[precision_weighted-metric5]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[neg_mean_absolute_percentage_error]", "sklearn/metrics/tests/test_score_objects.py::test_non_symmetric_metric_pos_label[jaccard_score]", "sklearn/metrics/tests/test_score_objects.py::test_all_scorers_repr", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[mutual_info_score]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[precision_samples]", "sklearn/metrics/tests/test_score_objects.py::test_check_scoring_and_check_multimetric_scoring[dict_str]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[roc_auc_ovr_weighted]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_select_proba_error[ProbaScorer]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[adjusted_mutual_info_score]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[recall_micro]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[jaccard_macro]", "sklearn/metrics/tests/test_score_objects.py::test_classification_multiclass_scores[f1_micro-metric4]", "sklearn/metrics/tests/test_score_objects.py::test_classification_binary_scores[jaccard_macro-metric14]", "sklearn/metrics/tests/test_score_objects.py::test_check_scoring_and_check_multimetric_scoring_errors[non-string key dict]", "sklearn/metrics/tests/test_score_objects.py::test_classification_multiclass_scores[jaccard_macro-metric12]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[fowlkes_mallows_score]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[roc_auc_ovo_weighted]", "sklearn/metrics/tests/test_score_objects.py::test_non_symmetric_metric_pos_label[f1_score]", "sklearn/metrics/tests/test_score_objects.py::test_classification_binary_scores[precision-precision_score]", "sklearn/metrics/tests/test_score_objects.py::test_classification_binary_scores[f1_macro-metric2]", "sklearn/metrics/tests/test_score_objects.py::test_classification_binary_scores[precision_weighted-metric5]", "sklearn/metrics/tests/test_score_objects.py::test_classification_binary_scores[recall_macro-metric10]", "sklearn/metrics/tests/test_score_objects.py::test_check_scoring_and_check_multimetric_scoring[dict_callable]", "sklearn/metrics/tests/test_score_objects.py::test_classification_binary_scores[precision_micro-metric7]", "sklearn/metrics/tests/test_score_objects.py::test_brier_score_loss_pos_label", "sklearn/metrics/tests/test_score_objects.py::test_multiclass_roc_no_proba_scorer_errors[roc_auc_ovr]", "sklearn/metrics/tests/test_score_objects.py::test_supervised_cluster_scorers", "sklearn/metrics/tests/test_score_objects.py::test_multiclass_roc_proba_scorer[roc_auc_ovo_weighted-metric3]", "sklearn/metrics/tests/test_score_objects.py::test_check_scoring_and_check_multimetric_scoring_errors[empty tuple]", "sklearn/metrics/tests/test_score_objects.py::test_regression_scorers", "sklearn/metrics/tests/test_score_objects.py::test_classification_multiclass_scores[precision_macro-metric6]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[recall]", "sklearn/metrics/tests/test_score_objects.py::test_classification_binary_scores[recall_micro-metric11]", "sklearn/metrics/tests/test_score_objects.py::test_check_scoring_and_check_multimetric_scoring[multi_list]", "sklearn/metrics/tests/test_score_objects.py::test_classification_binary_scores[f1_weighted-metric1]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[jaccard]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[jaccard_samples]", "sklearn/metrics/tests/test_score_objects.py::test_multiclass_roc_proba_scorer[roc_auc_ovr-metric0]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[homogeneity_score]", "sklearn/metrics/tests/test_score_objects.py::test_custom_scorer_pickling", "sklearn/metrics/tests/test_score_objects.py::test_make_scorer", "sklearn/metrics/tests/test_score_objects.py::test_multimetric_scorer_calls_method_once[scorers1-1-0-1]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[top_k_accuracy]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[f1_samples]", "sklearn/metrics/tests/test_score_objects.py::test_non_symmetric_metric_pos_label[precision_score]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[precision_micro]", "sklearn/metrics/tests/test_score_objects.py::test_check_scoring_and_check_multimetric_scoring[single_list]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[v_measure_score]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[precision_weighted]", "sklearn/metrics/tests/test_score_objects.py::test_multimetric_scorer_calls_method_once[scorers0-1-1-1]", "sklearn/metrics/tests/test_score_objects.py::test_multimetric_scorer_calls_method_once[scorers2-1-1-0]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_select_proba_error[ThresholdScorer]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[jaccard_weighted]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_no_op_multiclass_select_proba", "sklearn/metrics/tests/test_score_objects.py::test_classification_binary_scores[top_k_accuracy-top_k_accuracy_score]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[recall_weighted]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[neg_mean_gamma_deviance]", "sklearn/metrics/tests/test_score_objects.py::test_multiclass_roc_no_proba_scorer_errors[roc_auc_ovo]", "sklearn/metrics/tests/test_score_objects.py::test_classification_binary_scores[jaccard-jaccard_score]", "sklearn/metrics/tests/test_score_objects.py::test_multiclass_roc_proba_scorer[roc_auc_ovr_weighted-metric2]", "sklearn/metrics/tests/test_score_objects.py::test_non_symmetric_metric_pos_label[recall_score]", "sklearn/metrics/tests/test_score_objects.py::test_classification_multiclass_scores[jaccard_weighted-metric11]", "sklearn/metrics/tests/test_score_objects.py::test_classification_multiclass_scores[recall_micro-metric10]", "sklearn/metrics/tests/test_score_objects.py::test_classification_multiclass_scores[balanced_accuracy-balanced_accuracy_score]", "sklearn/metrics/tests/test_score_objects.py::test_classification_scorer_sample_weight", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[neg_log_loss]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[neg_mean_squared_error]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[neg_mean_poisson_deviance]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[precision_macro]", "sklearn/metrics/tests/test_score_objects.py::test_multimetric_scorer_calls_method_once_classifier_no_decision", "sklearn/metrics/tests/test_score_objects.py::test_multiclass_roc_proba_scorer_label", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[r2]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[recall_macro]", "sklearn/metrics/tests/test_score_objects.py::test_average_precision_pos_label", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[neg_root_mean_squared_error]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[roc_auc_ovr]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[accuracy]", "sklearn/metrics/tests/test_score_objects.py::test_multimetric_scorer_sanity_check", "sklearn/metrics/tests/test_score_objects.py::test_classification_multiclass_scores[precision_micro-metric7]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[precision]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[f1_micro]", "sklearn/metrics/tests/test_score_objects.py::test_classification_multiclass_scores[f1_weighted-metric2]", "sklearn/metrics/tests/test_score_objects.py::test_multiclass_roc_no_proba_scorer_errors[roc_auc_ovr_weighted]", "sklearn/metrics/tests/test_score_objects.py::test_check_scoring_gridsearchcv", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[recall_samples]", "sklearn/metrics/tests/test_score_objects.py::test_classification_binary_scores[recall_weighted-metric9]", "sklearn/metrics/tests/test_score_objects.py::test_check_scoring_and_check_multimetric_scoring_errors[non-unique str]", "sklearn/metrics/tests/test_score_objects.py::test_scoring_is_not_metric", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[balanced_accuracy]", "sklearn/metrics/tests/test_score_objects.py::test_check_scoring_and_check_multimetric_scoring_errors[tuple of one callable]", "sklearn/metrics/tests/test_score_objects.py::test_classification_binary_scores[precision_macro-metric6]", "sklearn/metrics/tests/test_score_objects.py::test_thresholded_scorers", "sklearn/metrics/tests/test_score_objects.py::test_classification_binary_scores[jaccard_weighted-metric13]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[roc_auc_ovo]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[rand_score]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_select_proba_error[PredictScorer]", "sklearn/metrics/tests/test_score_objects.py::test_classification_multiclass_scores[f1_macro-metric3]", "sklearn/metrics/tests/test_score_objects.py::test_multimetric_scorer_calls_method_once_regressor_threshold", "sklearn/metrics/tests/test_score_objects.py::test_classification_binary_scores[recall-recall_score]", "sklearn/metrics/tests/test_score_objects.py::test_classification_multiclass_scores[recall_weighted-metric8]", "sklearn/metrics/tests/test_score_objects.py::test_classification_binary_scores[jaccard_micro-metric15]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[f1]", "sklearn/metrics/tests/test_score_objects.py::test_multiclass_roc_no_proba_scorer_errors[roc_auc_ovo_weighted]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[neg_mean_squared_log_error]", "sklearn/metrics/tests/test_score_objects.py::test_thresholded_scorers_multilabel_indicator_data", "sklearn/metrics/tests/test_score_objects.py::test_raises_on_score_list", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[neg_median_absolute_error]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[adjusted_rand_score]", "sklearn/metrics/tests/test_score_objects.py::test_classification_multiclass_scores[accuracy-accuracy_score]", "sklearn/metrics/tests/test_score_objects.py::test_check_scoring_and_check_multimetric_scoring_errors[list of int]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[neg_mean_absolute_error]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[normalized_mutual_info_score]" ]
[ "sklearn/metrics/tests/test_score_objects.py::test_classification_binary_scores[matthews_corrcoef-matthews_corrcoef]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[matthews_corrcoef]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex d14cd278f67a1..5339f4a399490 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -382,6 +382,11 @@ Changelog\n splits failed. Similarly raise an error during grid-search when the fits for\n all the models and all the splits failed. :pr:`<PRID>` by :user:`<NAME>`.\n \n+- |Enhancement| it is now possible to pass `scoring=\"matthews_corrcoef\"` to all\n+ model selection tools with a `scoring` argument to use the Matthews\n+ correlation coefficient (MCC). :pr:`<PRID>` by :user:`<NAME>`.\n+\n - |Fix| :class:`model_selection.GridSearchCV`,\n :class:`model_selection.HalvingGridSearchCV`\n now validate input parameters in `fit` instead of `__init__`.\n" } ]
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index d14cd278f67a1..5339f4a399490 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -382,6 +382,11 @@ Changelog splits failed. Similarly raise an error during grid-search when the fits for all the models and all the splits failed. :pr:`<PRID>` by :user:`<NAME>`. +- |Enhancement| it is now possible to pass `scoring="matthews_corrcoef"` to all + model selection tools with a `scoring` argument to use the Matthews + correlation coefficient (MCC). :pr:`<PRID>` by :user:`<NAME>`. + - |Fix| :class:`model_selection.GridSearchCV`, :class:`model_selection.HalvingGridSearchCV` now validate input parameters in `fit` instead of `__init__`.
scikit-learn/scikit-learn
scikit-learn__scikit-learn-21445
https://github.com/scikit-learn/scikit-learn/pull/21445
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 542636b1642f7..7036139bfb10e 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -134,6 +134,11 @@ Changelog :mod:`sklearn.preprocessing` ............................ +- |Enhancement| Adds a `subsample` parameter to :class:`preprocessing.KBinsDiscretizer`. + This allows specifying a maximum number of samples to be used while fitting + the model. The option is only available when `strategy` is set to `quantile`. + :pr:`21445` by :user:`Felipe Bidu <fbidu>` and :user:`Amanda Dsouza <amy12xx>`. + - |Fix| :class:`preprocessing.LabelBinarizer` now validates input parameters in `fit` instead of `__init__`. :pr:`21434` by :user:`Krum Arnaudov <krumeto>`. diff --git a/sklearn/preprocessing/_discretization.py b/sklearn/preprocessing/_discretization.py index 79a667911d354..9fd9ff9409092 100644 --- a/sklearn/preprocessing/_discretization.py +++ b/sklearn/preprocessing/_discretization.py @@ -15,7 +15,10 @@ from ..base import BaseEstimator, TransformerMixin from ..utils.validation import check_array from ..utils.validation import check_is_fitted +from ..utils.validation import check_random_state from ..utils.validation import _check_feature_names_in +from ..utils.validation import check_scalar +from ..utils import _safe_indexing class KBinsDiscretizer(TransformerMixin, BaseEstimator): @@ -63,6 +66,27 @@ class KBinsDiscretizer(TransformerMixin, BaseEstimator): .. versionadded:: 0.24 + subsample : int or None (default='warn') + Maximum number of samples, used to fit the model, for computational + efficiency. Used when `strategy="quantile"`. + `subsample=None` means that all the training samples are used when + computing the quantiles that determine the binning thresholds. + Since quantile computation relies on sorting each column of `X` and + that sorting has an `n log(n)` time complexity, + it is recommended to use subsampling on datasets with a + very large number of samples. + + .. deprecated:: 1.1 + In version 1.3 and onwards, `subsample=2e5` will be the default. + + random_state : int, RandomState instance or None, default=None + Determines random number generation for subsampling. + Pass an int for reproducible results across multiple function calls. + See the `subsample` parameter for more details. + See :term:`Glossary <random_state>`. + + .. versionadded:: 1.1 + Attributes ---------- bin_edges_ : ndarray of ndarray of shape (n_features,) @@ -136,11 +160,22 @@ class KBinsDiscretizer(TransformerMixin, BaseEstimator): [ 0.5, 3.5, -1.5, 1.5]]) """ - def __init__(self, n_bins=5, *, encode="onehot", strategy="quantile", dtype=None): + def __init__( + self, + n_bins=5, + *, + encode="onehot", + strategy="quantile", + dtype=None, + subsample="warn", + random_state=None, + ): self.n_bins = n_bins self.encode = encode self.strategy = strategy self.dtype = dtype + self.subsample = subsample + self.random_state = random_state def fit(self, X, y=None): """ @@ -174,6 +209,36 @@ def fit(self, X, y=None): " instead." ) + n_samples, n_features = X.shape + + if self.strategy == "quantile" and self.subsample is not None: + if self.subsample == "warn": + if n_samples > 2e5: + warnings.warn( + "In version 1.3 onwards, subsample=2e5 " + "will be used by default. Set subsample explicitly to " + "silence this warning in the mean time. Set " + "subsample=None to disable subsampling explicitly.", + FutureWarning, + ) + else: + self.subsample = check_scalar( + self.subsample, "subsample", numbers.Integral, min_val=1 + ) + rng = check_random_state(self.random_state) + if n_samples > self.subsample: + subsample_idx = rng.choice( + n_samples, size=self.subsample, replace=False + ) + X = _safe_indexing(X, subsample_idx) + elif self.strategy != "quantile" and isinstance( + self.subsample, numbers.Integral + ): + raise ValueError( + f"Invalid parameter for `strategy`: {self.strategy}. " + '`subsample` must be used with `strategy="quantile"`.' + ) + valid_encode = ("onehot", "onehot-dense", "ordinal") if self.encode not in valid_encode: raise ValueError(
diff --git a/sklearn/preprocessing/tests/test_discretization.py b/sklearn/preprocessing/tests/test_discretization.py index a053332619e39..fa8240893f7c3 100644 --- a/sklearn/preprocessing/tests/test_discretization.py +++ b/sklearn/preprocessing/tests/test_discretization.py @@ -3,6 +3,7 @@ import scipy.sparse as sp import warnings +from sklearn import clone from sklearn.preprocessing import KBinsDiscretizer from sklearn.preprocessing import OneHotEncoder from sklearn.utils._testing import ( @@ -37,16 +38,16 @@ def test_valid_n_bins(): def test_invalid_n_bins(): est = KBinsDiscretizer(n_bins=1) err_msg = ( - "KBinsDiscretizer received an invalid " - "number of bins. Received 1, expected at least 2." + "KBinsDiscretizer received an invalid number of bins. Received 1, expected at" + " least 2." ) with pytest.raises(ValueError, match=err_msg): est.fit_transform(X) est = KBinsDiscretizer(n_bins=1.1) err_msg = ( - "KBinsDiscretizer received an invalid " - "n_bins type. Received float, expected int." + "KBinsDiscretizer received an invalid n_bins type. Received float, expected" + " int." ) with pytest.raises(ValueError, match=err_msg): est.fit_transform(X) @@ -357,3 +358,80 @@ def test_32_equal_64(input_dtype, encode): Xt_64 = kbd_64.transform(X_input) assert_allclose_dense_sparse(Xt_32, Xt_64) + + +# FIXME: remove the `filterwarnings` in 1.3 [email protected]("ignore:In version 1.3 onwards, subsample=2e5") [email protected]("subsample", [None, "warn"]) +def test_kbinsdiscretizer_subsample_default(subsample): + # Since the size of X is small (< 2e5), subsampling will not take place. + X = np.array([-2, 1.5, -4, -1]).reshape(-1, 1) + kbd_default = KBinsDiscretizer(n_bins=10, encode="ordinal", strategy="quantile") + kbd_default.fit(X) + + kbd_with_subsampling = clone(kbd_default) + kbd_with_subsampling.set_params(subsample=subsample) + kbd_with_subsampling.fit(X) + + for bin_kbd_default, bin_kbd_with_subsampling in zip( + kbd_default.bin_edges_[0], kbd_with_subsampling.bin_edges_[0] + ): + np.testing.assert_allclose(bin_kbd_default, bin_kbd_with_subsampling) + assert kbd_default.bin_edges_.shape == kbd_with_subsampling.bin_edges_.shape + + +def test_kbinsdiscretizer_subsample_invalid_strategy(): + X = np.array([-2, 1.5, -4, -1]).reshape(-1, 1) + kbd = KBinsDiscretizer(n_bins=10, encode="ordinal", strategy="uniform", subsample=3) + + err_msg = '`subsample` must be used with `strategy="quantile"`.' + with pytest.raises(ValueError, match=err_msg): + kbd.fit(X) + + +def test_kbinsdiscretizer_subsample_invalid_type(): + X = np.array([-2, 1.5, -4, -1]).reshape(-1, 1) + kbd = KBinsDiscretizer( + n_bins=10, encode="ordinal", strategy="quantile", subsample="full" + ) + + msg = ( + "subsample must be an instance of <class 'numbers.Integral'>, not " + "<class 'str'>." + ) + with pytest.raises(TypeError, match=msg): + kbd.fit(X) + + +# TODO: Remove in 1.3 +def test_kbinsdiscretizer_subsample_warn(): + X = np.random.rand(200001, 1).reshape(-1, 1) + kbd = KBinsDiscretizer(n_bins=100, encode="ordinal", strategy="quantile") + + msg = "In version 1.3 onwards, subsample=2e5 will be used by default." + with pytest.warns(FutureWarning, match=msg): + kbd.fit(X) + + [email protected]("subsample", [0, int(2e5)]) +def test_kbinsdiscretizer_subsample_values(subsample): + X = np.random.rand(220000, 1).reshape(-1, 1) + kbd_default = KBinsDiscretizer(n_bins=10, encode="ordinal", strategy="quantile") + + kbd_with_subsampling = clone(kbd_default) + kbd_with_subsampling.set_params(subsample=subsample) + + if subsample == 0: + with pytest.raises(ValueError, match="subsample == 0, must be >= 1."): + kbd_with_subsampling.fit(X) + else: + # TODO: Remove in 1.3 + msg = "In version 1.3 onwards, subsample=2e5 will be used by default." + with pytest.warns(FutureWarning, match=msg): + kbd_default.fit(X) + + kbd_with_subsampling.fit(X) + assert not np.all( + kbd_default.bin_edges_[0] == kbd_with_subsampling.bin_edges_[0] + ) + assert kbd_default.bin_edges_.shape == kbd_with_subsampling.bin_edges_.shape
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 542636b1642f7..7036139bfb10e 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -134,6 +134,11 @@ Changelog\n :mod:`sklearn.preprocessing`\n ............................\n \n+- |Enhancement| Adds a `subsample` parameter to :class:`preprocessing.KBinsDiscretizer`.\n+ This allows specifying a maximum number of samples to be used while fitting\n+ the model. The option is only available when `strategy` is set to `quantile`.\n+ :pr:`21445` by :user:`Felipe Bidu <fbidu>` and :user:`Amanda Dsouza <amy12xx>`.\n+\n - |Fix| :class:`preprocessing.LabelBinarizer` now validates input parameters in `fit`\n instead of `__init__`.\n :pr:`21434` by :user:`Krum Arnaudov <krumeto>`.\n" } ]
1.01
1f8825c8dd6238355191e3d1c98f4e4d54cfbf16
[ "sklearn/preprocessing/tests/test_discretization.py::test_32_equal_64[ordinal-float32]", "sklearn/preprocessing/tests/test_discretization.py::test_inverse_transform[onehot-kmeans-expected_inv1]", "sklearn/preprocessing/tests/test_discretization.py::test_32_equal_64[ordinal-float16]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-dense-float32-float16]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[ordinal-float16-float16]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-float32-float32]", "sklearn/preprocessing/tests/test_discretization.py::test_fit_transform_n_bins_array[kmeans-expected1]", "sklearn/preprocessing/tests/test_discretization.py::test_same_min_max[quantile]", "sklearn/preprocessing/tests/test_discretization.py::test_numeric_stability[6]", "sklearn/preprocessing/tests/test_discretization.py::test_fit_transform_n_bins_array[uniform-expected0]", "sklearn/preprocessing/tests/test_discretization.py::test_fit_transform[quantile-expected2]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-None-float64]", "sklearn/preprocessing/tests/test_discretization.py::test_inverse_transform[onehot-dense-uniform-expected_inv0]", "sklearn/preprocessing/tests/test_discretization.py::test_numeric_stability[8]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[ordinal-float32-float16]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-float32-float16]", "sklearn/preprocessing/tests/test_discretization.py::test_numeric_stability[4]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-float16-float16]", "sklearn/preprocessing/tests/test_discretization.py::test_inverse_transform[onehot-quantile-expected_inv2]", "sklearn/preprocessing/tests/test_discretization.py::test_nonuniform_strategies[quantile-expected_2bins2-expected_3bins2-expected_5bins2]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-float16-float32]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[ordinal-None-float64]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-float32-float64]", "sklearn/preprocessing/tests/test_discretization.py::test_32_equal_64[onehot-dense-float16]", "sklearn/preprocessing/tests/test_discretization.py::test_redundant_bins[quantile-expected_bin_edges0]", "sklearn/preprocessing/tests/test_discretization.py::test_32_equal_64[onehot-float32]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-float64-float16]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[ordinal-None-float32]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-dense-float16-float16]", "sklearn/preprocessing/tests/test_discretization.py::test_fit_transform[uniform-expected0]", "sklearn/preprocessing/tests/test_discretization.py::test_nonuniform_strategies[uniform-expected_2bins0-expected_3bins0-expected_5bins0]", "sklearn/preprocessing/tests/test_discretization.py::test_32_equal_64[onehot-dense-float64]", "sklearn/preprocessing/tests/test_discretization.py::test_numeric_stability[3]", "sklearn/preprocessing/tests/test_discretization.py::test_transform_outside_fit_range[kmeans]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[ordinal-float32-float64]", "sklearn/preprocessing/tests/test_discretization.py::test_transform_outside_fit_range[quantile]", "sklearn/preprocessing/tests/test_discretization.py::test_inverse_transform[onehot-dense-kmeans-expected_inv1]", "sklearn/preprocessing/tests/test_discretization.py::test_same_min_max[uniform]", "sklearn/preprocessing/tests/test_discretization.py::test_fit_transform[kmeans-expected1]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-float64-float32]", "sklearn/preprocessing/tests/test_discretization.py::test_invalid_encode_option", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-dense-float64-float16]", "sklearn/preprocessing/tests/test_discretization.py::test_inverse_transform[ordinal-quantile-expected_inv2]", "sklearn/preprocessing/tests/test_discretization.py::test_transform_1d_behavior", "sklearn/preprocessing/tests/test_discretization.py::test_numeric_stability[5]", "sklearn/preprocessing/tests/test_discretization.py::test_encode_options", "sklearn/preprocessing/tests/test_discretization.py::test_32_equal_64[onehot-dense-float32]", "sklearn/preprocessing/tests/test_discretization.py::test_inverse_transform[onehot-uniform-expected_inv0]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[ordinal-float32-float32]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-dense-None-float16]", "sklearn/preprocessing/tests/test_discretization.py::test_inverse_transform[onehot-dense-quantile-expected_inv2]", "sklearn/preprocessing/tests/test_discretization.py::test_fit_transform_n_bins_array[quantile-expected2]", "sklearn/preprocessing/tests/test_discretization.py::test_same_min_max[kmeans]", "sklearn/preprocessing/tests/test_discretization.py::test_numeric_stability[1]", "sklearn/preprocessing/tests/test_discretization.py::test_valid_n_bins", "sklearn/preprocessing/tests/test_discretization.py::test_invalid_n_bins_array", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-dense-None-float32]", "sklearn/preprocessing/tests/test_discretization.py::test_redundant_bins[kmeans-expected_bin_edges1]", "sklearn/preprocessing/tests/test_discretization.py::test_inverse_transform[ordinal-uniform-expected_inv0]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[ordinal-float64-float64]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-dense-float64-float32]", "sklearn/preprocessing/tests/test_discretization.py::test_invalid_n_bins", "sklearn/preprocessing/tests/test_discretization.py::test_32_equal_64[onehot-float16]", "sklearn/preprocessing/tests/test_discretization.py::test_32_equal_64[onehot-float64]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-dense-float32-float64]", "sklearn/preprocessing/tests/test_discretization.py::test_32_equal_64[ordinal-float64]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-None-float32]", "sklearn/preprocessing/tests/test_discretization.py::test_overwrite", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[ordinal-float16-float64]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-dense-float16-float32]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-dense-float32-float32]", "sklearn/preprocessing/tests/test_discretization.py::test_numeric_stability[7]", "sklearn/preprocessing/tests/test_discretization.py::test_inverse_transform[ordinal-kmeans-expected_inv1]", "sklearn/preprocessing/tests/test_discretization.py::test_transform_outside_fit_range[uniform]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-float16-float64]", "sklearn/preprocessing/tests/test_discretization.py::test_numeric_stability[2]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[ordinal-float64-float16]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[ordinal-float64-float32]", "sklearn/preprocessing/tests/test_discretization.py::test_nonuniform_strategies[kmeans-expected_2bins1-expected_3bins1-expected_5bins1]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-dense-float16-float64]", "sklearn/preprocessing/tests/test_discretization.py::test_percentile_numeric_stability", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-dense-None-float64]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[ordinal-None-float16]", "sklearn/preprocessing/tests/test_discretization.py::test_invalid_strategy_option", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-dense-float64-float64]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[ordinal-float16-float32]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-float64-float64]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-None-float16]" ]
[ "sklearn/preprocessing/tests/test_discretization.py::test_kbinsdiscretizer_subsample_default[None]", "sklearn/preprocessing/tests/test_discretization.py::test_kbinsdiscretizer_subsample_values[200000]", "sklearn/preprocessing/tests/test_discretization.py::test_kbinsdiscretizer_subsample_default[warn]", "sklearn/preprocessing/tests/test_discretization.py::test_kbinsdiscretizer_subsample_warn", "sklearn/preprocessing/tests/test_discretization.py::test_kbinsdiscretizer_subsample_invalid_type", "sklearn/preprocessing/tests/test_discretization.py::test_kbinsdiscretizer_subsample_invalid_strategy", "sklearn/preprocessing/tests/test_discretization.py::test_kbinsdiscretizer_subsample_values[0]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 542636b1642f7..7036139bfb10e 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -134,6 +134,11 @@ Changelog\n :mod:`sklearn.preprocessing`\n ............................\n \n+- |Enhancement| Adds a `subsample` parameter to :class:`preprocessing.KBinsDiscretizer`.\n+ This allows specifying a maximum number of samples to be used while fitting\n+ the model. The option is only available when `strategy` is set to `quantile`.\n+ :pr:`<PRID>` by :user:`<NAME>` and :user:`<NAME>`.\n+\n - |Fix| :class:`preprocessing.LabelBinarizer` now validates input parameters in `fit`\n instead of `__init__`.\n :pr:`<PRID>` by :user:`<NAME>`.\n" } ]
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 542636b1642f7..7036139bfb10e 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -134,6 +134,11 @@ Changelog :mod:`sklearn.preprocessing` ............................ +- |Enhancement| Adds a `subsample` parameter to :class:`preprocessing.KBinsDiscretizer`. + This allows specifying a maximum number of samples to be used while fitting + the model. The option is only available when `strategy` is set to `quantile`. + :pr:`<PRID>` by :user:`<NAME>` and :user:`<NAME>`. + - |Fix| :class:`preprocessing.LabelBinarizer` now validates input parameters in `fit` instead of `__init__`. :pr:`<PRID>` by :user:`<NAME>`.
scikit-learn/scikit-learn
scikit-learn__scikit-learn-20408
https://github.com/scikit-learn/scikit-learn/pull/20408
diff --git a/doc/modules/mixture.rst b/doc/modules/mixture.rst index fb8e897270f0b..114b5ea3e8eb3 100644 --- a/doc/modules/mixture.rst +++ b/doc/modules/mixture.rst @@ -135,6 +135,43 @@ parameters to maximize the likelihood of the data given those assignments. Repeating this process is guaranteed to always converge to a local optimum. +Choice of the Initialization Method +----------------------------------- + +There is a choice of four initialization methods (as well as inputting user defined +initial means) to generate the initial centers for the model components: + +k-means (default) + This applies a traditional k-means clustering algorithm. + This can be computationally expensive compared to other initialization methods. + +k-means++ + This uses the initialization method of k-means clustering: k-means++. + This will pick the first center at random from the data. Subsequent centers will be + chosen from a weighted distribution of the data favouring points further away from + existing centers. k-means++ is the default initialization for k-means so will be + quicker than running a full k-means but can still take a significant amount of + time for large data sets with many components. + +random_from_data + This will pick random data points from the input data as the initial + centers. This is a very fast method of initialization but can produce non-convergent + results if the chosen points are too close to each other. + +random + Centers are chosen as a small pertubation away from the mean of all data. + This method is simple but can lead to the model taking longer to converge. + +.. figure:: ../auto_examples/mixture/images/sphx_glr_plot_gmm_init_001.png + :target: ../auto_examples/mixture/plot_gmm_init.html + :align: center + :scale: 50% + +.. topic:: Examples: + + * See :ref:`sphx_glr_auto_examples_mixture_plot_gmm_init.py` for an example of + using different initializations in Gaussian Mixture. + .. _bgmm: Variational Bayesian Gaussian Mixture diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index ef106adf0807b..32e33752a49b9 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -766,6 +766,20 @@ Changelog - |Fix| Fixes `precision_recall_curve` and `average_precision_score` when true labels are all negative. :pr:`19085` by :user:`Varun Agrawal <varunagrawal>`. +:mod:`sklearn.mixture` +...................... + +- |Enhancement| :class:`mixture.GaussianMixture` and + :class:`mixture.BayesianGaussianMixture` can now be initialized using + k-means++ and random data points. :pr:`20408` by + :user:`Gordon Walsh <g-walsh>`, :user:`Alberto Ceballos<alceballosa>` + and :user:`Andres Rios<ariosramirez>`. + +- |Fix| Fix a bug that correctly initialize `precisions_cholesky_` in + :class:`mixture.GaussianMixture` when providing `precisions_init` by taking + its square root. + :pr:`22058` by :user:`Guillaume Lemaitre <glemaitre>`. + :mod:`sklearn.model_selection` .............................. @@ -783,14 +797,6 @@ Changelog now validate input parameters in `fit` instead of `__init__`. :pr:`21880` by :user:`Mrinal Tyagi <MrinalTyagi>`. -:mod:`sklearn.mixture` -...................... - -- |Fix| Fix a bug that correctly initialize `precisions_cholesky_` in - :class:`mixture.GaussianMixture` when providing `precisions_init` by taking - its square root. - :pr:`22058` by :user:`Guillaume Lemaitre <glemaitre>`. - :mod:`sklearn.multiclass` ......................... diff --git a/examples/mixture/plot_gmm_init.py b/examples/mixture/plot_gmm_init.py new file mode 100644 index 0000000000000..23a4788b799b4 --- /dev/null +++ b/examples/mixture/plot_gmm_init.py @@ -0,0 +1,109 @@ +""" +========================== +GMM Initialization Methods +========================== + +Examples of the different methods of initialization in Gaussian Mixture Models + +See :ref:`gmm` for more information on the estimator. + +Here we generate some sample data with four easy to identify clusters. The +purpose of this example is to show the four different methods for the +initialization parameter *init_param*. + +The four initializations are *kmeans* (default), *random*, *random_from_data* and +*k-means++*. + +Orange diamonds represent the initialization centers for the gmm generated by +the *init_param*. The rest of the data is represented as crosses and the +colouring represents the eventual associated classification after the GMM has +finished. + +The numbers in the top right of each subplot represent the number of +iterations taken for the GaussianMixture to converge and the relative time +taken for the initialization part of the algorithm to run. The shorter +initialization times tend to have a greater number of iterations to converge. + +The initialization time is the ratio of the time taken for that method versus +the time taken for the default *kmeans* method. As you can see all three +alternative methods take less time to initialize when compared to *kmeans*. + +In this example, when initialized with *random_from_data* or *random* the model takes +more iterations to converge. Here *k-means++* does a good job of both low +time to initialize and low number of GaussianMixture iterations to converge. +""" + + +# Author: Gordon Walsh <[email protected]> +# Data generation code from Jake Vanderplas <[email protected]> + +import matplotlib.pyplot as plt +import numpy as np +from sklearn.mixture import GaussianMixture +from sklearn.utils.extmath import row_norms +from sklearn.datasets._samples_generator import make_blobs +from timeit import default_timer as timer + +print(__doc__) + +# Generate some data + +X, y_true = make_blobs(n_samples=4000, centers=4, cluster_std=0.60, random_state=0) +X = X[:, ::-1] + +n_samples = 4000 +n_components = 4 +x_squared_norms = row_norms(X, squared=True) + + +def get_initial_means(X, init_params, r): + # Run a GaussianMixture with max_iter=0 to output the initalization means + gmm = GaussianMixture( + n_components=4, init_params=init_params, tol=1e-9, max_iter=0, random_state=r + ).fit(X) + return gmm.means_ + + +methods = ["kmeans", "random_from_data", "k-means++", "random"] +colors = ["navy", "turquoise", "cornflowerblue", "darkorange"] +times_init = {} +relative_times = {} + +plt.figure(figsize=(4 * len(methods) // 2, 6)) +plt.subplots_adjust( + bottom=0.1, top=0.9, hspace=0.15, wspace=0.05, left=0.05, right=0.95 +) + +for n, method in enumerate(methods): + r = np.random.RandomState(seed=1234) + plt.subplot(2, len(methods) // 2, n + 1) + + start = timer() + ini = get_initial_means(X, method, r) + end = timer() + init_time = end - start + + gmm = GaussianMixture( + n_components=4, means_init=ini, tol=1e-9, max_iter=2000, random_state=r + ).fit(X) + + times_init[method] = init_time + for i, color in enumerate(colors): + data = X[gmm.predict(X) == i] + plt.scatter(data[:, 0], data[:, 1], color=color, marker="x") + + plt.scatter( + ini[:, 0], ini[:, 1], s=75, marker="D", c="orange", lw=1.5, edgecolors="black" + ) + relative_times[method] = times_init[method] / times_init[methods[0]] + + plt.xticks(()) + plt.yticks(()) + plt.title(method, loc="left", fontsize=12) + plt.title( + "Iter %i | Init Time %.2fx" % (gmm.n_iter_, relative_times[method]), + loc="right", + fontsize=10, + ) +plt.suptitle("GMM iterations and relative time taken to initialize") +plt.show() diff --git a/sklearn/mixture/_base.py b/sklearn/mixture/_base.py index 978d16c966890..2edc3b57aa4d2 100644 --- a/sklearn/mixture/_base.py +++ b/sklearn/mixture/_base.py @@ -4,6 +4,7 @@ # Modified by Thierry Guillemot <[email protected]> # License: BSD 3 clause +import numbers import warnings from abc import ABCMeta, abstractmethod from time import time @@ -12,10 +13,11 @@ from scipy.special import logsumexp from .. import cluster +from ..cluster import kmeans_plusplus from ..base import BaseEstimator from ..base import DensityMixin from ..exceptions import ConvergenceWarning -from ..utils import check_random_state +from ..utils import check_random_state, check_scalar from ..utils.validation import check_is_fitted @@ -76,40 +78,26 @@ def _check_initial_parameters(self, X): ---------- X : array-like of shape (n_samples, n_features) """ - if self.n_components < 1: - raise ValueError( - "Invalid value for 'n_components': %d " - "Estimation requires at least one component" - % self.n_components - ) + check_scalar( + self.n_components, + name="n_components", + target_type=numbers.Integral, + min_val=1, + ) - if self.tol < 0.0: - raise ValueError( - "Invalid value for 'tol': %.5f " - "Tolerance used by the EM must be non-negative" - % self.tol - ) + check_scalar(self.tol, name="tol", target_type=numbers.Real, min_val=0.0) - if self.n_init < 1: - raise ValueError( - "Invalid value for 'n_init': %d Estimation requires at least one run" - % self.n_init - ) + check_scalar( + self.n_init, name="n_init", target_type=numbers.Integral, min_val=1 + ) - if self.max_iter < 1: - raise ValueError( - "Invalid value for 'max_iter': %d " - "Estimation requires at least one iteration" - % self.max_iter - ) + check_scalar( + self.max_iter, name="max_iter", target_type=numbers.Integral, min_val=0 + ) - if self.reg_covar < 0.0: - raise ValueError( - "Invalid value for 'reg_covar': %.5f " - "regularization on covariance must be " - "non-negative" - % self.reg_covar - ) + check_scalar( + self.reg_covar, name="reg_covar", target_type=numbers.Real, min_val=0.0 + ) # Check all the parameters values of the derived class self._check_parameters(X) @@ -150,6 +138,20 @@ def _initialize_parameters(self, X, random_state): elif self.init_params == "random": resp = random_state.uniform(size=(n_samples, self.n_components)) resp /= resp.sum(axis=1)[:, np.newaxis] + elif self.init_params == "random_from_data": + resp = np.zeros((n_samples, self.n_components)) + indices = random_state.choice( + n_samples, size=self.n_components, replace=False + ) + resp[indices, np.arange(self.n_components)] = 1 + elif self.init_params == "k-means++": + resp = np.zeros((n_samples, self.n_components)) + _, indices = kmeans_plusplus( + X, + self.n_components, + random_state=random_state, + ) + resp[indices, np.arange(self.n_components)] = 1 else: raise ValueError( "Unimplemented initialization method '%s'" % self.init_params @@ -252,28 +254,35 @@ def fit_predict(self, X, y=None): lower_bound = -np.inf if do_init else self.lower_bound_ - for n_iter in range(1, self.max_iter + 1): - prev_lower_bound = lower_bound + if self.max_iter == 0: + best_params = self._get_parameters() + best_n_iter = 0 + else: + for n_iter in range(1, self.max_iter + 1): + prev_lower_bound = lower_bound - log_prob_norm, log_resp = self._e_step(X) - self._m_step(X, log_resp) - lower_bound = self._compute_lower_bound(log_resp, log_prob_norm) + log_prob_norm, log_resp = self._e_step(X) + self._m_step(X, log_resp) + lower_bound = self._compute_lower_bound(log_resp, log_prob_norm) - change = lower_bound - prev_lower_bound - self._print_verbose_msg_iter_end(n_iter, change) + change = lower_bound - prev_lower_bound + self._print_verbose_msg_iter_end(n_iter, change) - if abs(change) < self.tol: - self.converged_ = True - break + if abs(change) < self.tol: + self.converged_ = True + break - self._print_verbose_msg_init_end(lower_bound) + self._print_verbose_msg_init_end(lower_bound) - if lower_bound > max_lower_bound or max_lower_bound == -np.inf: - max_lower_bound = lower_bound - best_params = self._get_parameters() - best_n_iter = n_iter + if lower_bound > max_lower_bound or max_lower_bound == -np.inf: + max_lower_bound = lower_bound + best_params = self._get_parameters() + best_n_iter = n_iter - if not self.converged_: + # Should only warn about convergence if max_iter > 0, otherwise + # the user is assumed to have used 0-iters initialization + # to get the initial means. + if not self.converged_ and self.max_iter > 0: warnings.warn( "Initialization %d did not converge. " "Try different init parameters, " diff --git a/sklearn/mixture/_bayesian_mixture.py b/sklearn/mixture/_bayesian_mixture.py index cd98b1ed2433b..d1f0c5d0bab81 100644 --- a/sklearn/mixture/_bayesian_mixture.py +++ b/sklearn/mixture/_bayesian_mixture.py @@ -118,13 +118,20 @@ class BayesianGaussianMixture(BaseMixture): The number of initializations to perform. The result with the highest lower bound value on the likelihood is kept. - init_params : {'kmeans', 'random'}, default='kmeans' + init_params : {'kmeans', 'k-means++', 'random', 'random_from_data'}, \ + default='kmeans' The method used to initialize the weights, the means and the covariances. - Must be one of:: + String must be one of: 'kmeans' : responsibilities are initialized using kmeans. + 'k-means++' : use the k-means++ method to initialize. 'random' : responsibilities are initialized randomly. + 'random_from_data' : initial means are randomly selected data points. + + .. versionchanged:: v1.1 + `init_params` now accepts 'random_from_data' and 'k-means++' as + initialization methods. weight_concentration_prior_type : str, default='dirichlet_process' String describing the type of the weight concentration prior. diff --git a/sklearn/mixture/_gaussian_mixture.py b/sklearn/mixture/_gaussian_mixture.py index 75bd8f739990d..8fc0152359951 100644 --- a/sklearn/mixture/_gaussian_mixture.py +++ b/sklearn/mixture/_gaussian_mixture.py @@ -492,13 +492,20 @@ class GaussianMixture(BaseMixture): n_init : int, default=1 The number of initializations to perform. The best results are kept. - init_params : {'kmeans', 'random'}, default='kmeans' + init_params : {'kmeans', 'k-means++', 'random', 'random_from_data'}, \ + default='kmeans' The method used to initialize the weights, the means and the precisions. - Must be one of:: + String must be one of: - 'kmeans' : responsibilities are initialized using kmeans. - 'random' : responsibilities are initialized randomly. + - 'kmeans' : responsibilities are initialized using kmeans. + - 'k-means++' : use the k-means++ method to initialize. + - 'random' : responsibilities are initialized randomly. + - 'random_from_data' : initial means are randomly selected data points. + + .. versionchanged:: v1.1 + `init_params` now accepts 'random_from_data' and 'k-means++' as + initialization methods. weights_init : array-like of shape (n_components, ), default=None The user-provided initial weights.
diff --git a/sklearn/mixture/tests/test_gaussian_mixture.py b/sklearn/mixture/tests/test_gaussian_mixture.py index bbf9cd98b1413..f8531c7553202 100644 --- a/sklearn/mixture/tests/test_gaussian_mixture.py +++ b/sklearn/mixture/tests/test_gaussian_mixture.py @@ -2,6 +2,7 @@ # Thierry Guillemot <[email protected]> # License: BSD 3 clause +import itertools import re import sys import copy @@ -129,55 +130,41 @@ def test_gaussian_mixture_attributes(): n_components_bad = 0 gmm = GaussianMixture(n_components=n_components_bad) - msg = ( - f"Invalid value for 'n_components': {n_components_bad} " - "Estimation requires at least one component" - ) + msg = f"n_components == {n_components_bad}, must be >= 1." with pytest.raises(ValueError, match=msg): gmm.fit(X) # covariance_type should be in [spherical, diag, tied, full] covariance_type_bad = "bad_covariance_type" gmm = GaussianMixture(covariance_type=covariance_type_bad) - msg = ( - f"Invalid value for 'covariance_type': {covariance_type_bad} " - "'covariance_type' should be in ['spherical', 'tied', 'diag', 'full']" + msg = re.escape( + f"Invalid value for 'covariance_type': {covariance_type_bad} 'covariance_type'" + + " should be in ['spherical', 'tied', 'diag', 'full']" ) - with pytest.raises(ValueError): + with pytest.raises(ValueError, match=msg): gmm.fit(X) tol_bad = -1 gmm = GaussianMixture(tol=tol_bad) - msg = ( - f"Invalid value for 'tol': {tol_bad:.5f} " - "Tolerance used by the EM must be non-negative" - ) + msg = f"tol == {tol_bad}, must be >= 0." with pytest.raises(ValueError, match=msg): gmm.fit(X) reg_covar_bad = -1 gmm = GaussianMixture(reg_covar=reg_covar_bad) - msg = ( - f"Invalid value for 'reg_covar': {reg_covar_bad:.5f} " - "regularization on covariance must be non-negative" - ) + msg = f"reg_covar == {reg_covar_bad}, must be >= 0." with pytest.raises(ValueError, match=msg): gmm.fit(X) - max_iter_bad = 0 + max_iter_bad = -1 gmm = GaussianMixture(max_iter=max_iter_bad) - msg = ( - f"Invalid value for 'max_iter': {max_iter_bad} " - "Estimation requires at least one iteration" - ) + msg = f"max_iter == {max_iter_bad}, must be >= 0." with pytest.raises(ValueError, match=msg): gmm.fit(X) n_init_bad = 0 gmm = GaussianMixture(n_init=n_init_bad) - msg = ( - f"Invalid value for 'n_init': {n_init_bad} Estimation requires at least one run" - ) + msg = f"n_init == {n_init_bad}, must be >= 1." with pytest.raises(ValueError, match=msg): gmm.fit(X) @@ -1263,6 +1250,67 @@ def test_gaussian_mixture_setting_best_params(): assert hasattr(gmm, attr) [email protected]( + "init_params", ["random", "random_from_data", "k-means++", "kmeans"] +) +def test_init_means_not_duplicated(init_params, global_random_seed): + # Check that all initialisations provide not duplicated starting means + rng = np.random.RandomState(global_random_seed) + rand_data = RandomData(rng, scale=5) + n_components = rand_data.n_components + X = rand_data.X["full"] + + gmm = GaussianMixture( + n_components=n_components, init_params=init_params, random_state=rng, max_iter=0 + ) + gmm.fit(X) + + means = gmm.means_ + for i_mean, j_mean in itertools.combinations(means, r=2): + assert not np.allclose(i_mean, j_mean) + + [email protected]( + "init_params", ["random", "random_from_data", "k-means++", "kmeans"] +) +def test_means_for_all_inits(init_params, global_random_seed): + # Check fitted means properties for all initializations + rng = np.random.RandomState(global_random_seed) + rand_data = RandomData(rng, scale=5) + n_components = rand_data.n_components + X = rand_data.X["full"] + + gmm = GaussianMixture( + n_components=n_components, init_params=init_params, random_state=rng + ) + gmm.fit(X) + + assert gmm.means_.shape == (n_components, X.shape[1]) + assert np.all(X.min(axis=0) <= gmm.means_) + assert np.all(gmm.means_ <= X.max(axis=0)) + assert gmm.converged_ + + +def test_max_iter_zero(): + # Check that max_iter=0 returns initialisation as expected + # Pick arbitrary initial means and check equal to max_iter=0 + rng = np.random.RandomState(0) + rand_data = RandomData(rng, scale=5) + n_components = rand_data.n_components + X = rand_data.X["full"] + means_init = [[20, 30], [30, 25]] + gmm = GaussianMixture( + n_components=n_components, + random_state=rng, + means_init=means_init, + tol=1e-06, + max_iter=0, + ) + gmm.fit(X) + + assert_allclose(gmm.means_, means_init) + + def test_gaussian_mixture_precisions_init_diag(): """Check that we properly initialize `precision_cholesky_` when we manually provide the precision matrix.
[ { "path": "doc/modules/mixture.rst", "old_path": "a/doc/modules/mixture.rst", "new_path": "b/doc/modules/mixture.rst", "metadata": "diff --git a/doc/modules/mixture.rst b/doc/modules/mixture.rst\nindex fb8e897270f0b..114b5ea3e8eb3 100644\n--- a/doc/modules/mixture.rst\n+++ b/doc/modules/mixture.rst\n@@ -135,6 +135,43 @@ parameters to maximize the likelihood of the data given those\n assignments. Repeating this process is guaranteed to always converge\n to a local optimum.\n \n+Choice of the Initialization Method\n+-----------------------------------\n+\n+There is a choice of four initialization methods (as well as inputting user defined\n+initial means) to generate the initial centers for the model components: \n+\n+k-means (default)\n+ This applies a traditional k-means clustering algorithm.\n+ This can be computationally expensive compared to other initialization methods.\n+\n+k-means++\n+ This uses the initialization method of k-means clustering: k-means++.\n+ This will pick the first center at random from the data. Subsequent centers will be\n+ chosen from a weighted distribution of the data favouring points further away from\n+ existing centers. k-means++ is the default initialization for k-means so will be\n+ quicker than running a full k-means but can still take a significant amount of\n+ time for large data sets with many components.\n+\n+random_from_data\n+ This will pick random data points from the input data as the initial\n+ centers. This is a very fast method of initialization but can produce non-convergent\n+ results if the chosen points are too close to each other.\n+\n+random\n+ Centers are chosen as a small pertubation away from the mean of all data.\n+ This method is simple but can lead to the model taking longer to converge.\n+\n+.. figure:: ../auto_examples/mixture/images/sphx_glr_plot_gmm_init_001.png\n+ :target: ../auto_examples/mixture/plot_gmm_init.html\n+ :align: center\n+ :scale: 50%\n+\n+.. topic:: Examples:\n+\n+ * See :ref:`sphx_glr_auto_examples_mixture_plot_gmm_init.py` for an example of\n+ using different initializations in Gaussian Mixture.\n+\n .. _bgmm:\n \n Variational Bayesian Gaussian Mixture\n" }, { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex ef106adf0807b..32e33752a49b9 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -766,6 +766,20 @@ Changelog\n - |Fix| Fixes `precision_recall_curve` and `average_precision_score` when true labels\n are all negative. :pr:`19085` by :user:`Varun Agrawal <varunagrawal>`.\n \n+:mod:`sklearn.mixture`\n+......................\n+\n+- |Enhancement| :class:`mixture.GaussianMixture` and\n+ :class:`mixture.BayesianGaussianMixture` can now be initialized using\n+ k-means++ and random data points. :pr:`20408` by\n+ :user:`Gordon Walsh <g-walsh>`, :user:`Alberto Ceballos<alceballosa>`\n+ and :user:`Andres Rios<ariosramirez>`.\n+\n+- |Fix| Fix a bug that correctly initialize `precisions_cholesky_` in\n+ :class:`mixture.GaussianMixture` when providing `precisions_init` by taking\n+ its square root.\n+ :pr:`22058` by :user:`Guillaume Lemaitre <glemaitre>`.\n+\n :mod:`sklearn.model_selection`\n ..............................\n \n@@ -783,14 +797,6 @@ Changelog\n now validate input parameters in `fit` instead of `__init__`.\n :pr:`21880` by :user:`Mrinal Tyagi <MrinalTyagi>`.\n \n-:mod:`sklearn.mixture`\n-......................\n-\n-- |Fix| Fix a bug that correctly initialize `precisions_cholesky_` in\n- :class:`mixture.GaussianMixture` when providing `precisions_init` by taking\n- its square root.\n- :pr:`22058` by :user:`Guillaume Lemaitre <glemaitre>`.\n-\n :mod:`sklearn.multiclass`\n .........................\n \n" } ]
1.01
b99bd36830074ca6a82fcd50529a7365b01a23bf
[ "sklearn/mixture/tests/test_gaussian_mixture.py::test_regularisation", "sklearn/mixture/tests/test_gaussian_mixture.py::test_gaussian_mixture_predict_predict_proba", "sklearn/mixture/tests/test_gaussian_mixture.py::test_gaussian_mixture_fit_best_params", "sklearn/mixture/tests/test_gaussian_mixture.py::test_gaussian_suffstat_sk_spherical", "sklearn/mixture/tests/test_gaussian_mixture.py::test_warm_start[1]", "sklearn/mixture/tests/test_gaussian_mixture.py::test_gaussian_mixture_setting_best_params", "sklearn/mixture/tests/test_gaussian_mixture.py::test_gaussian_mixture_precisions_init_diag", "sklearn/mixture/tests/test_gaussian_mixture.py::test_gaussian_mixture_aic_bic", "sklearn/mixture/tests/test_gaussian_mixture.py::test_gaussian_mixture_fit_convergence_warning", "sklearn/mixture/tests/test_gaussian_mixture.py::test_gaussian_mixture_verbose", "sklearn/mixture/tests/test_gaussian_mixture.py::test_check_weights", "sklearn/mixture/tests/test_gaussian_mixture.py::test_init", "sklearn/mixture/tests/test_gaussian_mixture.py::test_suffstat_sk_full", "sklearn/mixture/tests/test_gaussian_mixture.py::test_gaussian_mixture_fit_predict[1-2-0.1]", "sklearn/mixture/tests/test_gaussian_mixture.py::test_convergence_detected_with_warm_start", "sklearn/mixture/tests/test_gaussian_mixture.py::test_multiple_init", "sklearn/mixture/tests/test_gaussian_mixture.py::test_sample", "sklearn/mixture/tests/test_gaussian_mixture.py::test_means_for_all_inits[42-kmeans]", "sklearn/mixture/tests/test_gaussian_mixture.py::test_gaussian_mixture_estimate_log_prob_resp", "sklearn/mixture/tests/test_gaussian_mixture.py::test_gaussian_mixture_log_probabilities", "sklearn/mixture/tests/test_gaussian_mixture.py::test_gaussian_mixture_n_parameters", "sklearn/mixture/tests/test_gaussian_mixture.py::test_monotonic_likelihood", "sklearn/mixture/tests/test_gaussian_mixture.py::test_gaussian_mixture_fit_predict_n_init", "sklearn/mixture/tests/test_gaussian_mixture.py::test_bic_1d_1component", "sklearn/mixture/tests/test_gaussian_mixture.py::test_means_for_all_inits[42-random]", "sklearn/mixture/tests/test_gaussian_mixture.py::test_score_samples", "sklearn/mixture/tests/test_gaussian_mixture.py::test_compute_log_det_cholesky", "sklearn/mixture/tests/test_gaussian_mixture.py::test_suffstat_sk_diag", "sklearn/mixture/tests/test_gaussian_mixture.py::test_gaussian_mixture_fit_predict[0-2-1e-07]", "sklearn/mixture/tests/test_gaussian_mixture.py::test_warm_start[2]", "sklearn/mixture/tests/test_gaussian_mixture.py::test_gaussian_mixture_fit", "sklearn/mixture/tests/test_gaussian_mixture.py::test_gaussian_mixture_fit_predict[4-300-0.1]", "sklearn/mixture/tests/test_gaussian_mixture.py::test_check_precisions", "sklearn/mixture/tests/test_gaussian_mixture.py::test_check_means", "sklearn/mixture/tests/test_gaussian_mixture.py::test_warm_start[0]", "sklearn/mixture/tests/test_gaussian_mixture.py::test_gaussian_mixture_fit_predict[3-300-1e-07]", "sklearn/mixture/tests/test_gaussian_mixture.py::test_score", "sklearn/mixture/tests/test_gaussian_mixture.py::test_suffstat_sk_tied", "sklearn/mixture/tests/test_gaussian_mixture.py::test_property" ]
[ "sklearn/mixture/tests/test_gaussian_mixture.py::test_means_for_all_inits[42-k-means++]", "sklearn/mixture/tests/test_gaussian_mixture.py::test_init_means_not_duplicated[42-random_from_data]", "sklearn/mixture/tests/test_gaussian_mixture.py::test_max_iter_zero", "sklearn/mixture/tests/test_gaussian_mixture.py::test_init_means_not_duplicated[42-kmeans]", "sklearn/mixture/tests/test_gaussian_mixture.py::test_gaussian_mixture_attributes", "sklearn/mixture/tests/test_gaussian_mixture.py::test_means_for_all_inits[42-random_from_data]", "sklearn/mixture/tests/test_gaussian_mixture.py::test_init_means_not_duplicated[42-random]", "sklearn/mixture/tests/test_gaussian_mixture.py::test_init_means_not_duplicated[42-k-means++]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [ { "type": "file", "name": "examples/mixture/plot_gmm_init.py" } ] }
[ { "path": "doc/modules/mixture.rst", "old_path": "a/doc/modules/mixture.rst", "new_path": "b/doc/modules/mixture.rst", "metadata": "diff --git a/doc/modules/mixture.rst b/doc/modules/mixture.rst\nindex fb8e897270f0b..114b5ea3e8eb3 100644\n--- a/doc/modules/mixture.rst\n+++ b/doc/modules/mixture.rst\n@@ -135,6 +135,43 @@ parameters to maximize the likelihood of the data given those\n assignments. Repeating this process is guaranteed to always converge\n to a local optimum.\n \n+Choice of the Initialization Method\n+-----------------------------------\n+\n+There is a choice of four initialization methods (as well as inputting user defined\n+initial means) to generate the initial centers for the model components: \n+\n+k-means (default)\n+ This applies a traditional k-means clustering algorithm.\n+ This can be computationally expensive compared to other initialization methods.\n+\n+k-means++\n+ This uses the initialization method of k-means clustering: k-means++.\n+ This will pick the first center at random from the data. Subsequent centers will be\n+ chosen from a weighted distribution of the data favouring points further away from\n+ existing centers. k-means++ is the default initialization for k-means so will be\n+ quicker than running a full k-means but can still take a significant amount of\n+ time for large data sets with many components.\n+\n+random_from_data\n+ This will pick random data points from the input data as the initial\n+ centers. This is a very fast method of initialization but can produce non-convergent\n+ results if the chosen points are too close to each other.\n+\n+random\n+ Centers are chosen as a small pertubation away from the mean of all data.\n+ This method is simple but can lead to the model taking longer to converge.\n+\n+.. figure:: ../auto_examples/mixture/images/sphx_glr_plot_gmm_init_001.png\n+ :target: ../auto_examples/mixture/plot_gmm_init.html\n+ :align: center\n+ :scale: 50%\n+\n+.. topic:: Examples:\n+\n+ * See :ref:`sphx_glr_auto_examples_mixture_plot_gmm_init.py` for an example of\n+ using different initializations in Gaussian Mixture.\n+\n .. _bgmm:\n \n Variational Bayesian Gaussian Mixture\n" }, { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex ef106adf0807b..32e33752a49b9 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -766,6 +766,20 @@ Changelog\n - |Fix| Fixes `precision_recall_curve` and `average_precision_score` when true labels\n are all negative. :pr:`<PRID>` by :user:`<NAME>`.\n \n+:mod:`sklearn.mixture`\n+......................\n+\n+- |Enhancement| :class:`mixture.GaussianMixture` and\n+ :class:`mixture.BayesianGaussianMixture` can now be initialized using\n+ k-means++ and random data points. :pr:`<PRID>` by\n+ :user:`<NAME>`, :user:`<NAME>`\n+ and :user:`<NAME>`.\n+\n+- |Fix| Fix a bug that correctly initialize `precisions_cholesky_` in\n+ :class:`mixture.GaussianMixture` when providing `precisions_init` by taking\n+ its square root.\n+ :pr:`<PRID>` by :user:`<NAME>`.\n+\n :mod:`sklearn.model_selection`\n ..............................\n \n@@ -783,14 +797,6 @@ Changelog\n now validate input parameters in `fit` instead of `__init__`.\n :pr:`<PRID>` by :user:`<NAME>`.\n \n-:mod:`sklearn.mixture`\n-......................\n-\n-- |Fix| Fix a bug that correctly initialize `precisions_cholesky_` in\n- :class:`mixture.GaussianMixture` when providing `precisions_init` by taking\n- its square root.\n- :pr:`<PRID>` by :user:`<NAME>`.\n-\n :mod:`sklearn.multiclass`\n .........................\n \n" } ]
diff --git a/doc/modules/mixture.rst b/doc/modules/mixture.rst index fb8e897270f0b..114b5ea3e8eb3 100644 --- a/doc/modules/mixture.rst +++ b/doc/modules/mixture.rst @@ -135,6 +135,43 @@ parameters to maximize the likelihood of the data given those assignments. Repeating this process is guaranteed to always converge to a local optimum. +Choice of the Initialization Method +----------------------------------- + +There is a choice of four initialization methods (as well as inputting user defined +initial means) to generate the initial centers for the model components: + +k-means (default) + This applies a traditional k-means clustering algorithm. + This can be computationally expensive compared to other initialization methods. + +k-means++ + This uses the initialization method of k-means clustering: k-means++. + This will pick the first center at random from the data. Subsequent centers will be + chosen from a weighted distribution of the data favouring points further away from + existing centers. k-means++ is the default initialization for k-means so will be + quicker than running a full k-means but can still take a significant amount of + time for large data sets with many components. + +random_from_data + This will pick random data points from the input data as the initial + centers. This is a very fast method of initialization but can produce non-convergent + results if the chosen points are too close to each other. + +random + Centers are chosen as a small pertubation away from the mean of all data. + This method is simple but can lead to the model taking longer to converge. + +.. figure:: ../auto_examples/mixture/images/sphx_glr_plot_gmm_init_001.png + :target: ../auto_examples/mixture/plot_gmm_init.html + :align: center + :scale: 50% + +.. topic:: Examples: + + * See :ref:`sphx_glr_auto_examples_mixture_plot_gmm_init.py` for an example of + using different initializations in Gaussian Mixture. + .. _bgmm: Variational Bayesian Gaussian Mixture diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index ef106adf0807b..32e33752a49b9 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -766,6 +766,20 @@ Changelog - |Fix| Fixes `precision_recall_curve` and `average_precision_score` when true labels are all negative. :pr:`<PRID>` by :user:`<NAME>`. +:mod:`sklearn.mixture` +...................... + +- |Enhancement| :class:`mixture.GaussianMixture` and + :class:`mixture.BayesianGaussianMixture` can now be initialized using + k-means++ and random data points. :pr:`<PRID>` by + :user:`<NAME>`, :user:`<NAME>` + and :user:`<NAME>`. + +- |Fix| Fix a bug that correctly initialize `precisions_cholesky_` in + :class:`mixture.GaussianMixture` when providing `precisions_init` by taking + its square root. + :pr:`<PRID>` by :user:`<NAME>`. + :mod:`sklearn.model_selection` .............................. @@ -783,14 +797,6 @@ Changelog now validate input parameters in `fit` instead of `__init__`. :pr:`<PRID>` by :user:`<NAME>`. -:mod:`sklearn.mixture` -...................... - -- |Fix| Fix a bug that correctly initialize `precisions_cholesky_` in - :class:`mixture.GaussianMixture` when providing `precisions_init` by taking - its square root. - :pr:`<PRID>` by :user:`<NAME>`. - :mod:`sklearn.multiclass` ......................... If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names: [{'type': 'file', 'name': 'examples/mixture/plot_gmm_init.py'}]
scikit-learn/scikit-learn
scikit-learn__scikit-learn-16018
https://github.com/scikit-learn/scikit-learn/pull/16018
diff --git a/doc/modules/preprocessing.rst b/doc/modules/preprocessing.rst index 035f2b90203ca..997bccf66782d 100644 --- a/doc/modules/preprocessing.rst +++ b/doc/modules/preprocessing.rst @@ -594,17 +594,19 @@ dataset:: array([[1., 0., 0., 1., 0., 0., 1., 0., 0., 0.]]) If there is a possibility that the training data might have missing categorical -features, it can often be better to specify ``handle_unknown='ignore'`` instead -of setting the ``categories`` manually as above. When -``handle_unknown='ignore'`` is specified and unknown categories are encountered -during transform, no error will be raised but the resulting one-hot encoded -columns for this feature will be all zeros -(``handle_unknown='ignore'`` is only supported for one-hot encoding):: - - >>> enc = preprocessing.OneHotEncoder(handle_unknown='ignore') +features, it can often be better to specify +`handle_unknown='infrequent_if_exist'` instead of setting the `categories` +manually as above. When `handle_unknown='infrequent_if_exist'` is specified +and unknown categories are encountered during transform, no error will be +raised but the resulting one-hot encoded columns for this feature will be all +zeros or considered as an infrequent category if enabled. +(`handle_unknown='infrequent_if_exist'` is only supported for one-hot +encoding):: + + >>> enc = preprocessing.OneHotEncoder(handle_unknown='infrequent_if_exist') >>> X = [['male', 'from US', 'uses Safari'], ['female', 'from Europe', 'uses Firefox']] >>> enc.fit(X) - OneHotEncoder(handle_unknown='ignore') + OneHotEncoder(handle_unknown='infrequent_if_exist') >>> enc.transform([['female', 'from Asia', 'uses Chrome']]).toarray() array([[1., 0., 0., 0., 0., 0.]]) @@ -621,7 +623,8 @@ since co-linearity would cause the covariance matrix to be non-invertible:: ... ['female', 'from Europe', 'uses Firefox']] >>> drop_enc = preprocessing.OneHotEncoder(drop='first').fit(X) >>> drop_enc.categories_ - [array(['female', 'male'], dtype=object), array(['from Europe', 'from US'], dtype=object), array(['uses Firefox', 'uses Safari'], dtype=object)] + [array(['female', 'male'], dtype=object), array(['from Europe', 'from US'], dtype=object), + array(['uses Firefox', 'uses Safari'], dtype=object)] >>> drop_enc.transform(X).toarray() array([[1., 1., 1.], [0., 0., 0.]]) @@ -634,7 +637,8 @@ categories. In this case, you can set the parameter `drop='if_binary'`. ... ['female', 'Asia', 'Chrome']] >>> drop_enc = preprocessing.OneHotEncoder(drop='if_binary').fit(X) >>> drop_enc.categories_ - [array(['female', 'male'], dtype=object), array(['Asia', 'Europe', 'US'], dtype=object), array(['Chrome', 'Firefox', 'Safari'], dtype=object)] + [array(['female', 'male'], dtype=object), array(['Asia', 'Europe', 'US'], dtype=object), + array(['Chrome', 'Firefox', 'Safari'], dtype=object)] >>> drop_enc.transform(X).toarray() array([[1., 0., 0., 1., 0., 0., 1.], [0., 0., 1., 0., 0., 1., 0.], @@ -699,6 +703,107 @@ separate categories:: See :ref:`dict_feature_extraction` for categorical features that are represented as a dict, not as scalars. +.. _one_hot_encoder_infrequent_categories: + +Infrequent categories +--------------------- + +:class:`OneHotEncoder` supports aggregating infrequent categories into a single +output for each feature. The parameters to enable the gathering of infrequent +categories are `min_frequency` and `max_categories`. + +1. `min_frequency` is either an integer greater or equal to 1, or a float in + the interval `(0.0, 1.0)`. If `min_frequency` is an integer, categories with + a cardinality smaller than `min_frequency` will be considered infrequent. + If `min_frequency` is a float, categories with a cardinality smaller than + this fraction of the total number of samples will be considered infrequent. + The default value is 1, which means every category is encoded separately. + +2. `max_categories` is either `None` or any integer greater than 1. This + parameter sets an upper limit to the number of output features for each + input feature. `max_categories` includes the feature that combines + infrequent categories. + +In the following example, the categories, `'dog', 'snake'` are considered +infrequent:: + + >>> X = np.array([['dog'] * 5 + ['cat'] * 20 + ['rabbit'] * 10 + + ... ['snake'] * 3], dtype=object).T + >>> enc = preprocessing.OneHotEncoder(min_frequency=6, sparse=False).fit(X) + >>> enc.infrequent_categories_ + [array(['dog', 'snake'], dtype=object)] + >>> enc.transform(np.array([['dog'], ['cat'], ['rabbit'], ['snake']])) + array([[0., 0., 1.], + [1., 0., 0.], + [0., 1., 0.], + [0., 0., 1.]]) + +By setting handle_unknown to `'infrequent_if_exist'`, unknown categories will +be considered infrequent:: + + >>> enc = preprocessing.OneHotEncoder( + ... handle_unknown='infrequent_if_exist', sparse=False, min_frequency=6) + >>> enc = enc.fit(X) + >>> enc.transform(np.array([['dragon']])) + array([[0., 0., 1.]]) + +:meth:`OneHotEncoder.get_feature_names_out` uses 'infrequent' as the infrequent +feature name:: + + >>> enc.get_feature_names_out() + array(['x0_cat', 'x0_rabbit', 'x0_infrequent_sklearn'], dtype=object) + +When `'handle_unknown'` is set to `'infrequent_if_exist'` and an unknown +category is encountered in transform: + +1. If infrequent category support was not configured or there was no + infrequent category during training, the resulting one-hot encoded columns + for this feature will be all zeros. In the inverse transform, an unknown + category will be denoted as `None`. + +2. If there is an infrequent category during training, the unknown category + will be considered infrequent. In the inverse transform, 'infrequent_sklearn' + will be used to represent the infrequent category. + +Infrequent categories can also be configured using `max_categories`. In the +following example, we set `max_categories=2` to limit the number of features in +the output. This will result in all but the `'cat'` category to be considered +infrequent, leading to two features, one for `'cat'` and one for infrequent +categories - which are all the others:: + + >>> enc = preprocessing.OneHotEncoder(max_categories=2, sparse=False) + >>> enc = enc.fit(X) + >>> enc.transform([['dog'], ['cat'], ['rabbit'], ['snake']]) + array([[0., 1.], + [1., 0.], + [0., 1.], + [0., 1.]]) + +If both `max_categories` and `min_frequency` are non-default values, then +categories are selected based on `min_frequency` first and `max_categories` +categories are kept. In the following example, `min_frequency=4` considers +only `snake` to be infrequent, but `max_categories=3`, forces `dog` to also be +infrequent:: + + >>> enc = preprocessing.OneHotEncoder(min_frequency=4, max_categories=3, sparse=False) + >>> enc = enc.fit(X) + >>> enc.transform([['dog'], ['cat'], ['rabbit'], ['snake']]) + array([[0., 0., 1.], + [1., 0., 0.], + [0., 1., 0.], + [0., 0., 1.]]) + +If there are infrequent categories with the same cardinality at the cutoff of +`max_categories`, then then the first `max_categories` are taken based on lexicon +ordering. In the following example, "b", "c", and "d", have the same cardinality +and with `max_categories=2`, "b" and "c" are infrequent because they have a higher +lexicon order. + + >>> X = np.asarray([["a"] * 20 + ["b"] * 10 + ["c"] * 10 + ["d"] * 10], dtype=object).T + >>> enc = preprocessing.OneHotEncoder(max_categories=3).fit(X) + >>> enc.infrequent_categories_ + [array(['b', 'c'], dtype=object)] + .. _preprocessing_discretization: Discretization @@ -981,7 +1086,7 @@ Interestingly, a :class:`SplineTransformer` of ``degree=0`` is the same as Penalties <10.1214/ss/1038425655>`. Statist. Sci. 11 (1996), no. 2, 89--121. * Perperoglou, A., Sauerbrei, W., Abrahamowicz, M. et al. :doi:`A review of - spline function procedures in R <10.1186/s12874-019-0666-3>`. + spline function procedures in R <10.1186/s12874-019-0666-3>`. BMC Med Res Methodol 19, 46 (2019). .. _function_transformer: diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 584dd796b5789..a0272f183bf81 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -688,6 +688,11 @@ Changelog :mod:`sklearn.preprocessing` ............................ +- |Feature| :class:`preprocessing.OneHotEncoder` now supports grouping + infrequent categories into a single feature. Grouping infrequent categories + is enabled by specifying how to select infrequent categories with + `min_frequency` or `max_categories`. :pr:`16018` by `Thomas Fan`_. + - |Enhancement| Adds a `subsample` parameter to :class:`preprocessing.KBinsDiscretizer`. This allows specifying a maximum number of samples to be used while fitting the model. The option is only available when `strategy` is set to `quantile`. diff --git a/sklearn/preprocessing/_encoders.py b/sklearn/preprocessing/_encoders.py index 33d87a09a7b39..740378645d774 100644 --- a/sklearn/preprocessing/_encoders.py +++ b/sklearn/preprocessing/_encoders.py @@ -2,10 +2,11 @@ # Joris Van den Bossche <[email protected]> # License: BSD 3 clause +import numbers import warnings + import numpy as np from scipy import sparse -import numbers from ..base import BaseEstimator, TransformerMixin, _OneToOneFeatureMixin from ..utils import check_array, is_scalar_nan @@ -14,7 +15,7 @@ from ..utils.validation import _check_feature_names_in from ..utils._mask import _get_mask -from ..utils._encode import _encode, _check_unknown, _unique +from ..utils._encode import _encode, _check_unknown, _unique, _get_counts __all__ = ["OneHotEncoder", "OrdinalEncoder"] @@ -71,7 +72,9 @@ def _get_feature(self, X, feature_idx): # numpy arrays, sparse arrays return X[:, feature_idx] - def _fit(self, X, handle_unknown="error", force_all_finite=True): + def _fit( + self, X, handle_unknown="error", force_all_finite=True, return_counts=False + ): self._check_n_features(X, reset=True) self._check_feature_names(X, reset=True) X_list, n_samples, n_features = self._check_X( @@ -87,11 +90,18 @@ def _fit(self, X, handle_unknown="error", force_all_finite=True): ) self.categories_ = [] + category_counts = [] for i in range(n_features): Xi = X_list[i] + if self.categories == "auto": - cats = _unique(Xi) + result = _unique(Xi, return_counts=return_counts) + if return_counts: + cats, counts = result + category_counts.append(counts) + else: + cats = result else: cats = np.array(self.categories[i], dtype=Xi.dtype) if Xi.dtype.kind not in "OUS": @@ -114,8 +124,16 @@ def _fit(self, X, handle_unknown="error", force_all_finite=True): " during fit".format(diff, i) ) raise ValueError(msg) + if return_counts: + category_counts.append(_get_counts(Xi, cats)) + self.categories_.append(cats) + output = {"n_samples": n_samples} + if return_counts: + output["category_counts"] = category_counts + return output + def _transform( self, X, handle_unknown="error", force_all_finite=True, warn_on_unknown=False ): @@ -244,19 +262,62 @@ class OneHotEncoder(_BaseEncoder): .. versionchanged:: 0.23 The option `drop='if_binary'` was added in 0.23. + .. versionchanged:: 1.1 + Support for dropping infrequent categories. + sparse : bool, default=True Will return sparse matrix if set True else will return an array. dtype : number type, default=float Desired dtype of output. - handle_unknown : {'error', 'ignore'}, default='error' - Whether to raise an error or ignore if an unknown categorical feature - is present during transform (default is to raise). When this parameter - is set to 'ignore' and an unknown category is encountered during - transform, the resulting one-hot encoded columns for this feature - will be all zeros. In the inverse transform, an unknown category - will be denoted as None. + handle_unknown : {'error', 'ignore', 'infrequent_if_exist'}, \ + default='error' + Specifies the way unknown categories are handled during :meth:`transform`. + + - 'error' : Raise an error if an unknown category is present during transform. + - 'ignore' : When an unknown category is encountered during + transform, the resulting one-hot encoded columns for this feature + will be all zeros. In the inverse transform, an unknown category + will be denoted as None. + - 'infrequent_if_exist' : When an unknown category is encountered + during transform, the resulting one-hot encoded columns for this + feature will map to the infrequent category if it exists. The + infrequent category will be mapped to the last position in the + encoding. During inverse transform, an unknown category will be + mapped to the category denoted `'infrequent'` if it exists. If the + `'infrequent'` category does not exist, then :meth:`transform` and + :meth:`inverse_transform` will handle an unknown category as with + `handle_unknown='ignore'`. Infrequent categories exist based on + `min_frequency` and `max_categories`. Read more in the + :ref:`User Guide <one_hot_encoder_infrequent_categories>`. + + .. versionchanged:: 1.1 + `'infrequent_if_exist'` was added to automatically handle unknown + categories and infrequent categories. + + min_frequency : int or float, default=None + Specifies the minimum frequency below which a category will be + considered infrequent. + + - If `int`, categories with a smaller cardinality will be considered + infrequent. + + - If `float`, categories with a smaller cardinality than + `min_frequency * n_samples` will be considered infrequent. + + .. versionadded:: 1.1 + Read more in the :ref:`User Guide <one_hot_encoder_infrequent_categories>`. + + max_categories : int, default=None + Specifies an upper limit to the number of output features for each input + feature when considering infrequent categories. If there are infrequent + categories, `max_categories` includes the category representing the + infrequent categories along with the frequent categories. If `None`, + there is no limit to the number of output features. + + .. versionadded:: 1.1 + Read more in the :ref:`User Guide <one_hot_encoder_infrequent_categories>`. Attributes ---------- @@ -275,9 +336,23 @@ class OneHotEncoder(_BaseEncoder): - ``drop_idx_ = None`` if all the transformed features will be retained. + If infrequent categories are enabled by setting `min_frequency` or + `max_categories` to a non-default value and `drop_idx[i]` corresponds + to a infrequent category, then the entire infrequent category is + dropped. + .. versionchanged:: 0.23 Added the possibility to contain `None` values. + infrequent_categories_ : list of ndarray + Defined only if infrequent categories are enabled by setting + `min_frequency` or `max_categories` to a non-default value. + `infrequent_categories_[i]` are the infrequent categories for feature + `i`. If the feature `i` has no infrequent categories + `infrequent_categories_[i]` is None. + + .. versionadded:: 1.1 + n_features_in_ : int Number of features seen during :term:`fit`. @@ -342,6 +417,17 @@ class OneHotEncoder(_BaseEncoder): >>> drop_binary_enc.transform([['Female', 1], ['Male', 2]]).toarray() array([[0., 1., 0., 0.], [1., 0., 1., 0.]]) + + Infrequent categories are enabled by setting `max_categories` or `min_frequency`. + + >>> import numpy as np + >>> X = np.array([["a"] * 5 + ["b"] * 20 + ["c"] * 10 + ["d"] * 3], dtype=object).T + >>> ohe = OneHotEncoder(max_categories=3, sparse=False).fit(X) + >>> ohe.infrequent_categories_ + [array(['a', 'd'], dtype=object)] + >>> ohe.transform([["a"], ["b"]]) + array([[0., 0., 1.], + [1., 0., 0.]]) """ def __init__( @@ -352,31 +438,113 @@ def __init__( sparse=True, dtype=np.float64, handle_unknown="error", + min_frequency=None, + max_categories=None, ): self.categories = categories self.sparse = sparse self.dtype = dtype self.handle_unknown = handle_unknown self.drop = drop + self.min_frequency = min_frequency + self.max_categories = max_categories + + @property + def infrequent_categories_(self): + """Infrequent categories for each feature.""" + # raises an AttributeError if `_infrequent_indices` is not defined + infrequent_indices = self._infrequent_indices + return [ + None if indices is None else category[indices] + for category, indices in zip(self.categories_, infrequent_indices) + ] def _validate_keywords(self): - if self.handle_unknown not in ("error", "ignore"): + + if self.handle_unknown not in {"error", "ignore", "infrequent_if_exist"}: msg = ( - "handle_unknown should be either 'error' or 'ignore', got {0}.".format( - self.handle_unknown - ) + "handle_unknown should be one of 'error', 'ignore', " + f"'infrequent_if_exist' got {self.handle_unknown}." ) raise ValueError(msg) + if self.max_categories is not None and self.max_categories < 1: + raise ValueError("max_categories must be greater than 1") + + if isinstance(self.min_frequency, numbers.Integral): + if not self.min_frequency >= 1: + raise ValueError( + "min_frequency must be an integer at least " + "1 or a float in (0.0, 1.0); got the " + f"integer {self.min_frequency}" + ) + elif isinstance(self.min_frequency, numbers.Real): + if not (0.0 < self.min_frequency < 1.0): + raise ValueError( + "min_frequency must be an integer at least " + "1 or a float in (0.0, 1.0); got the " + f"float {self.min_frequency}" + ) + + self._infrequent_enabled = ( + self.max_categories is not None and self.max_categories >= 1 + ) or self.min_frequency is not None + + def _map_drop_idx_to_infrequent(self, feature_idx, drop_idx): + """Convert `drop_idx` into the index for infrequent categories. + + If there are no infrequent categories, then `drop_idx` is + returned. This method is called in `_compute_drop_idx` when the `drop` + parameter is an array-like. + """ + if not self._infrequent_enabled: + return drop_idx + + default_to_infrequent = self._default_to_infrequent_mappings[feature_idx] + if default_to_infrequent is None: + return drop_idx + + # Raise error when explicitly dropping a category that is infrequent + infrequent_indices = self._infrequent_indices[feature_idx] + if infrequent_indices is not None and drop_idx in infrequent_indices: + categories = self.categories_[feature_idx] + raise ValueError( + f"Unable to drop category {categories[drop_idx]!r} from feature" + f" {feature_idx} because it is infrequent" + ) + return default_to_infrequent[drop_idx] + def _compute_drop_idx(self): + """Compute the drop indices associated with `self.categories_`. + + If `self.drop` is: + - `None`, returns `None`. + - `'first'`, returns all zeros to drop the first category. + - `'if_binary'`, returns zero if the category is binary and `None` + otherwise. + - array-like, returns the indices of the categories that match the + categories in `self.drop`. If the dropped category is an infrequent + category, then the index for the infrequent category is used. This + means that the entire infrequent category is dropped. + """ if self.drop is None: return None elif isinstance(self.drop, str): if self.drop == "first": return np.zeros(len(self.categories_), dtype=object) elif self.drop == "if_binary": + n_features_out_no_drop = [len(cat) for cat in self.categories_] + if self._infrequent_enabled: + for i, infreq_idx in enumerate(self._infrequent_indices): + if infreq_idx is None: + continue + n_features_out_no_drop[i] -= infreq_idx.size - 1 + return np.array( - [0 if len(cats) == 2 else None for cats in self.categories_], + [ + 0 if n_features_out == 2 else None + for n_features_out in n_features_out_no_drop + ], dtype=object, ) else: @@ -404,24 +572,28 @@ def _compute_drop_idx(self): raise ValueError(msg.format(len(self.categories_), droplen)) missing_drops = [] drop_indices = [] - for col_idx, (val, cat_list) in enumerate( + for feature_idx, (drop_val, cat_list) in enumerate( zip(drop_array, self.categories_) ): - if not is_scalar_nan(val): - drop_idx = np.where(cat_list == val)[0] + if not is_scalar_nan(drop_val): + drop_idx = np.where(cat_list == drop_val)[0] if drop_idx.size: # found drop idx - drop_indices.append(drop_idx[0]) + drop_indices.append( + self._map_drop_idx_to_infrequent(feature_idx, drop_idx[0]) + ) else: - missing_drops.append((col_idx, val)) + missing_drops.append((feature_idx, drop_val)) continue - # val is nan, find nan in categories manually + # drop_val is nan, find nan in categories manually for cat_idx, cat in enumerate(cat_list): if is_scalar_nan(cat): - drop_indices.append(cat_idx) + drop_indices.append( + self._map_drop_idx_to_infrequent(feature_idx, cat_idx) + ) break else: # loop did not break thus drop is missing - missing_drops.append((col_idx, val)) + missing_drops.append((feature_idx, drop_val)) if any(missing_drops): msg = ( @@ -439,6 +611,191 @@ def _compute_drop_idx(self): raise ValueError(msg) return np.array(drop_indices, dtype=object) + def _identify_infrequent(self, category_count, n_samples, col_idx): + """Compute the infrequent indices. + + Parameters + ---------- + category_count : ndarray of shape (n_cardinality,) + Category counts. + + n_samples : int + Number of samples. + + col_idx : int + Index of the current category. Only used for the error message. + + Returns + ------- + output : ndarray of shape (n_infrequent_categories,) or None + If there are infrequent categories, indices of infrequent + categories. Otherwise None. + """ + if isinstance(self.min_frequency, numbers.Integral): + infrequent_mask = category_count < self.min_frequency + elif isinstance(self.min_frequency, numbers.Real): + min_frequency_abs = n_samples * self.min_frequency + infrequent_mask = category_count < min_frequency_abs + else: + infrequent_mask = np.zeros(category_count.shape[0], dtype=bool) + + n_current_features = category_count.size - infrequent_mask.sum() + 1 + if self.max_categories is not None and self.max_categories < n_current_features: + # stable sort to preserve original count order + smallest_levels = np.argsort(category_count, kind="mergesort")[ + : -self.max_categories + 1 + ] + infrequent_mask[smallest_levels] = True + + output = np.flatnonzero(infrequent_mask) + return output if output.size > 0 else None + + def _fit_infrequent_category_mapping(self, n_samples, category_counts): + """Fit infrequent categories. + + Defines the private attribute: `_default_to_infrequent_mappings`. For + feature `i`, `_default_to_infrequent_mappings[i]` defines the mapping + from the integer encoding returned by `super().transform()` into + infrequent categories. If `_default_to_infrequent_mappings[i]` is None, + there were no infrequent categories in the training set. + + For example if categories 0, 2 and 4 were frequent, while categories + 1, 3, 5 were infrequent for feature 7, then these categories are mapped + to a single output: + `_default_to_infrequent_mappings[7] = array([0, 3, 1, 3, 2, 3])` + + Defines private attrite: `_infrequent_indices`. `_infrequent_indices[i]` + is an array of indices such that + `categories_[i][_infrequent_indices[i]]` are all the infrequent category + labels. If the feature `i` has no infrequent categories + `_infrequent_indices[i]` is None. + + .. versionadded:: 1.1 + + Parameters + ---------- + n_samples : int + Number of samples in training set. + category_counts: list of ndarray + `category_counts[i]` is the category counts corresponding to + `self.categories_[i]`. + """ + self._infrequent_indices = [ + self._identify_infrequent(category_count, n_samples, col_idx) + for col_idx, category_count in enumerate(category_counts) + ] + + # compute mapping from default mapping to infrequent mapping + self._default_to_infrequent_mappings = [] + + for cats, infreq_idx in zip(self.categories_, self._infrequent_indices): + # no infrequent categories + if infreq_idx is None: + self._default_to_infrequent_mappings.append(None) + continue + + n_cats = len(cats) + # infrequent indices exist + mapping = np.empty(n_cats, dtype=np.int64) + n_infrequent_cats = infreq_idx.size + + # infrequent categories are mapped to the last element. + n_frequent_cats = n_cats - n_infrequent_cats + mapping[infreq_idx] = n_frequent_cats + + frequent_indices = np.setdiff1d(np.arange(n_cats), infreq_idx) + mapping[frequent_indices] = np.arange(n_frequent_cats) + + self._default_to_infrequent_mappings.append(mapping) + + def _map_infrequent_categories(self, X_int, X_mask): + """Map infrequent categories to integer representing the infrequent category. + + This modifies X_int in-place. Values that were invalid based on `X_mask` + are mapped to the infrequent category if there was an infrequent + category for that feature. + + Parameters + ---------- + X_int: ndarray of shape (n_samples, n_features) + Integer encoded categories. + + X_mask: ndarray of shape (n_samples, n_features) + Bool mask for valid values in `X_int`. + """ + if not self._infrequent_enabled: + return + + for col_idx in range(X_int.shape[1]): + infrequent_idx = self._infrequent_indices[col_idx] + if infrequent_idx is None: + continue + + X_int[~X_mask[:, col_idx], col_idx] = infrequent_idx[0] + if self.handle_unknown == "infrequent_if_exist": + # All the unknown values are now mapped to the + # infrequent_idx[0], which makes the unknown values valid + # This is needed in `transform` when the encoding is formed + # using `X_mask`. + X_mask[:, col_idx] = True + + # Remaps encoding in `X_int` where the infrequent categories are + # grouped together. + for i, mapping in enumerate(self._default_to_infrequent_mappings): + if mapping is None: + continue + X_int[:, i] = np.take(mapping, X_int[:, i]) + + def _compute_transformed_categories(self, i, remove_dropped=True): + """Compute the transformed categories used for column `i`. + + 1. If there are infrequent categories, the category is named + 'infrequent_sklearn'. + 2. Dropped columns are removed when remove_dropped=True. + """ + cats = self.categories_[i] + + if self._infrequent_enabled: + infreq_map = self._default_to_infrequent_mappings[i] + if infreq_map is not None: + frequent_mask = infreq_map < infreq_map.max() + infrequent_cat = "infrequent_sklearn" + # infrequent category is always at the end + cats = np.concatenate( + (cats[frequent_mask], np.array([infrequent_cat], dtype=object)) + ) + + if remove_dropped: + cats = self._remove_dropped_categories(cats, i) + return cats + + def _remove_dropped_categories(self, categories, i): + """Remove dropped categories.""" + if self.drop_idx_ is not None and self.drop_idx_[i] is not None: + return np.delete(categories, self.drop_idx_[i]) + return categories + + def _compute_n_features_outs(self): + """Compute the n_features_out for each input feature.""" + output = [len(cats) for cats in self.categories_] + + if self.drop_idx_ is not None: + for i, drop_idx in enumerate(self.drop_idx_): + if drop_idx is not None: + output[i] -= 1 + + if not self._infrequent_enabled: + return output + + # infrequent is enabled, the number of features out are reduced + # because the infrequent categories are grouped together + for i, infreq_idx in enumerate(self._infrequent_indices): + if infreq_idx is None: + continue + output[i] -= infreq_idx.size - 1 + + return output + def fit(self, X, y=None): """ Fit OneHotEncoder to X. @@ -458,8 +815,18 @@ def fit(self, X, y=None): Fitted encoder. """ self._validate_keywords() - self._fit(X, handle_unknown=self.handle_unknown, force_all_finite="allow-nan") + fit_results = self._fit( + X, + handle_unknown=self.handle_unknown, + force_all_finite="allow-nan", + return_counts=self._infrequent_enabled, + ) + if self._infrequent_enabled: + self._fit_infrequent_category_mapping( + fit_results["n_samples"], fit_results["category_counts"] + ) self.drop_idx_ = self._compute_drop_idx() + self._n_features_outs = self._compute_n_features_outs() return self def fit_transform(self, X, y=None): @@ -491,6 +858,9 @@ def transform(self, X): """ Transform X using one-hot encoding. + If there are infrequent categories for a feature, the infrequent + categories will be grouped into a single category. + Parameters ---------- X : array-like of shape (n_samples, n_features) @@ -505,13 +875,17 @@ def transform(self, X): """ check_is_fitted(self) # validation of X happens in _check_X called by _transform - warn_on_unknown = self.handle_unknown == "ignore" and self.drop is not None + warn_on_unknown = self.drop is not None and self.handle_unknown in { + "ignore", + "infrequent_if_exist", + } X_int, X_mask = self._transform( X, handle_unknown=self.handle_unknown, force_all_finite="allow-nan", warn_on_unknown=warn_on_unknown, ) + self._map_infrequent_categories(X_int, X_mask) n_samples, n_features = X_int.shape @@ -520,26 +894,18 @@ def transform(self, X): # We remove all the dropped categories from mask, and decrement all # categories that occur after them to avoid an empty column. keep_cells = X_int != to_drop - n_values = [] for i, cats in enumerate(self.categories_): - n_cats = len(cats) - # drop='if_binary' but feature isn't binary if to_drop[i] is None: # set to cardinality to not drop from X_int - to_drop[i] = n_cats - n_values.append(n_cats) - else: # dropped - n_values.append(n_cats - 1) + to_drop[i] = len(cats) to_drop = to_drop.reshape(1, -1) X_int[X_int > to_drop] -= 1 X_mask &= keep_cells - else: - n_values = [len(cats) for cats in self.categories_] mask = X_mask.ravel() - feature_indices = np.cumsum([0] + n_values) + feature_indices = np.cumsum([0] + self._n_features_outs) indices = (X_int + feature_indices[:-1]).ravel()[mask] indptr = np.empty(n_samples + 1, dtype=int) @@ -567,6 +933,9 @@ def inverse_transform(self, X): feature with the unknown category has a dropped category, the dropped category will be its inverse. + For a given input feature, if there is an infrequent category, + 'infrequent_sklearn' will be used to represent the infrequent category. + Parameters ---------- X : {array-like, sparse matrix} of shape \ @@ -583,34 +952,38 @@ def inverse_transform(self, X): n_samples, _ = X.shape n_features = len(self.categories_) - if self.drop_idx_ is None: - n_transformed_features = sum(len(cats) for cats in self.categories_) - else: - n_transformed_features = sum( - len(cats) - 1 if to_drop is not None else len(cats) - for cats, to_drop in zip(self.categories_, self.drop_idx_) - ) + + n_features_out = np.sum(self._n_features_outs) # validate shape of passed X msg = ( "Shape of the passed X data is not correct. Expected {0} columns, got {1}." ) - if X.shape[1] != n_transformed_features: - raise ValueError(msg.format(n_transformed_features, X.shape[1])) + if X.shape[1] != n_features_out: + raise ValueError(msg.format(n_features_out, X.shape[1])) + + transformed_features = [ + self._compute_transformed_categories(i, remove_dropped=False) + for i, _ in enumerate(self.categories_) + ] # create resulting array of appropriate dtype - dt = np.find_common_type([cat.dtype for cat in self.categories_], []) + dt = np.find_common_type([cat.dtype for cat in transformed_features], []) X_tr = np.empty((n_samples, n_features), dtype=dt) j = 0 found_unknown = {} + if self._infrequent_enabled: + infrequent_indices = self._infrequent_indices + else: + infrequent_indices = [None] * n_features + for i in range(n_features): - if self.drop_idx_ is None or self.drop_idx_[i] is None: - cats = self.categories_[i] - else: - cats = np.delete(self.categories_[i], self.drop_idx_[i]) - n_categories = len(cats) + cats_wo_dropped = self._remove_dropped_categories( + transformed_features[i], i + ) + n_categories = cats_wo_dropped.shape[0] # Only happens if there was a column with a unique # category. In this case we just fill the column with this @@ -622,8 +995,12 @@ def inverse_transform(self, X): sub = X[:, j : j + n_categories] # for sparse X argmax returns 2D matrix, ensure 1D array labels = np.asarray(sub.argmax(axis=1)).flatten() - X_tr[:, i] = cats[labels] - if self.handle_unknown == "ignore": + X_tr[:, i] = cats_wo_dropped[labels] + + if self.handle_unknown == "ignore" or ( + self.handle_unknown == "infrequent_if_exist" + and infrequent_indices[i] is None + ): unknown = np.asarray(sub.sum(axis=1) == 0).flatten() # ignored unknown categories: we have a row of all zero if unknown.any(): @@ -645,7 +1022,8 @@ def inverse_transform(self, X): ) # we can safely assume that all of the nulls in each column # are the dropped value - X_tr[dropped, i] = self.categories_[i][self.drop_idx_[i]] + drop_idx = self.drop_idx_[i] + X_tr[dropped, i] = transformed_features[i][drop_idx] j += n_categories @@ -667,6 +1045,9 @@ def inverse_transform(self, X): def get_feature_names(self, input_features=None): """Return feature names for output features. + For a given input feature, if there is an infrequent category, the most + 'infrequent_sklearn' will be used as a feature name. + Parameters ---------- input_features : list of str of shape (n_features,) @@ -679,22 +1060,21 @@ def get_feature_names(self, input_features=None): Array of feature names. """ check_is_fitted(self) - cats = self.categories_ + cats = [ + self._compute_transformed_categories(i) + for i, _ in enumerate(self.categories_) + ] if input_features is None: input_features = ["x%d" % i for i in range(len(cats))] - elif len(input_features) != len(self.categories_): + elif len(input_features) != len(cats): raise ValueError( "input_features should have length equal to number of " - "features ({}), got {}".format( - len(self.categories_), len(input_features) - ) + "features ({}), got {}".format(len(cats), len(input_features)) ) feature_names = [] for i in range(len(cats)): names = [input_features[i] + "_" + str(t) for t in cats[i]] - if self.drop_idx_ is not None and self.drop_idx_[i] is not None: - names.pop(self.drop_idx_[i]) feature_names.extend(names) return np.array(feature_names, dtype=object) @@ -719,16 +1099,18 @@ def get_feature_names_out(self, input_features=None): Transformed feature names. """ check_is_fitted(self) - cats = self.categories_ input_features = _check_feature_names_in(self, input_features) + cats = [ + self._compute_transformed_categories(i) + for i, _ in enumerate(self.categories_) + ] feature_names = [] for i in range(len(cats)): names = [input_features[i] + "_" + str(t) for t in cats[i]] - if self.drop_idx_ is not None and self.drop_idx_[i] is not None: - names.pop(self.drop_idx_[i]) feature_names.extend(names) - return np.asarray(feature_names, dtype=object) + + return np.array(feature_names, dtype=object) class OrdinalEncoder(_OneToOneFeatureMixin, _BaseEncoder): diff --git a/sklearn/utils/_encode.py b/sklearn/utils/_encode.py index ab907cd781a32..8224cb87a4c75 100644 --- a/sklearn/utils/_encode.py +++ b/sklearn/utils/_encode.py @@ -1,10 +1,12 @@ +from contextlib import suppress +from collections import Counter from typing import NamedTuple import numpy as np from . import is_scalar_nan -def _unique(values, *, return_inverse=False): +def _unique(values, *, return_inverse=False, return_counts=False): """Helper function to find unique values with support for python objects. Uses pure python method for object dtype, and numpy method for @@ -18,6 +20,10 @@ def _unique(values, *, return_inverse=False): return_inverse : bool, default=False If True, also return the indices of the unique values. + return_counts : bool, default=False + If True, also return the number of times each unique item appears in + values. + Returns ------- unique : ndarray @@ -26,16 +32,38 @@ def _unique(values, *, return_inverse=False): unique_inverse : ndarray The indices to reconstruct the original array from the unique array. Only provided if `return_inverse` is True. + + unique_counts : ndarray + The number of times each of the unique values comes up in the original + array. Only provided if `return_counts` is True. """ if values.dtype == object: - return _unique_python(values, return_inverse=return_inverse) + return _unique_python( + values, return_inverse=return_inverse, return_counts=return_counts + ) # numerical - out = np.unique(values, return_inverse=return_inverse) + return _unique_np( + values, return_inverse=return_inverse, return_counts=return_counts + ) + + +def _unique_np(values, return_inverse=False, return_counts=False): + """Helper function to find unique values for numpy arrays that correctly + accounts for nans. See `_unique` documentation for details.""" + uniques = np.unique( + values, return_inverse=return_inverse, return_counts=return_counts + ) + + inverse, counts = None, None + + if return_counts: + *uniques, counts = uniques if return_inverse: - uniques, inverse = out - else: - uniques = out + *uniques, inverse = uniques + + if return_counts or return_inverse: + uniques = uniques[0] # np.unique will have duplicate missing values at the end of `uniques` # here we clip the nans and remove it from uniques @@ -45,9 +73,19 @@ def _unique(values, *, return_inverse=False): if return_inverse: inverse[inverse > nan_idx] = nan_idx + if return_counts: + counts[nan_idx] = np.sum(counts[nan_idx:]) + counts = counts[: nan_idx + 1] + + ret = (uniques,) + if return_inverse: - return uniques, inverse - return uniques + ret += (inverse,) + + if return_counts: + ret += (counts,) + + return ret[0] if len(ret) == 1 else ret class MissingValues(NamedTuple): @@ -126,7 +164,7 @@ def _map_to_integer(values, uniques): return np.array([table[v] for v in values]) -def _unique_python(values, *, return_inverse): +def _unique_python(values, *, return_inverse, return_counts): # Only used in `_uniques`, see docstring there for details try: uniques_set = set(values) @@ -141,11 +179,15 @@ def _unique_python(values, *, return_inverse): "Encoders require their input to be uniformly " f"strings or numbers. Got {types}" ) + ret = (uniques,) if return_inverse: - return uniques, _map_to_integer(values, uniques) + ret += (_map_to_integer(values, uniques),) + + if return_counts: + ret += (_get_counts(values, uniques),) - return uniques + return ret[0] if len(ret) == 1 else ret def _encode(values, *, uniques, check_unknown=True): @@ -273,3 +315,52 @@ def is_valid(value): if return_mask: return diff, valid_mask return diff + + +class _NaNCounter(Counter): + """Counter with support for nan values.""" + + def __init__(self, items): + super().__init__(self._generate_items(items)) + + def _generate_items(self, items): + """Generate items without nans. Stores the nan counts seperately.""" + for item in items: + if not is_scalar_nan(item): + yield item + continue + if not hasattr(self, "nan_count"): + self.nan_count = 0 + self.nan_count += 1 + + def __missing__(self, key): + if hasattr(self, "nan_count") and is_scalar_nan(key): + return self.nan_count + raise KeyError(key) + + +def _get_counts(values, uniques): + """Get the count of each of the `uniques` in `values`. + + The counts will use the order passed in by `uniques`. For non-object dtypes, + `uniques` is assumed to be sorted and `np.nan` is at the end. + """ + if values.dtype.kind in "OU": + counter = _NaNCounter(values) + output = np.zeros(len(uniques), dtype=np.int64) + for i, item in enumerate(uniques): + with suppress(KeyError): + output[i] = counter[item] + return output + + unique_values, counts = _unique_np(values, return_counts=True) + + # Recorder unique_values based on input: `uniques` + uniques_in_values = np.isin(uniques, unique_values, assume_unique=True) + if np.isnan(unique_values[-1]) and np.isnan(uniques[-1]): + uniques_in_values[-1] = True + + unique_valid_indices = np.searchsorted(unique_values, uniques[uniques_in_values]) + output = np.zeros_like(uniques, dtype=np.int64) + output[uniques_in_values] = counts[unique_valid_indices] + return output
diff --git a/sklearn/preprocessing/tests/test_encoders.py b/sklearn/preprocessing/tests/test_encoders.py index 54ed48fa115c8..96bd9c2c5b9ff 100644 --- a/sklearn/preprocessing/tests/test_encoders.py +++ b/sklearn/preprocessing/tests/test_encoders.py @@ -39,7 +39,8 @@ def test_one_hot_encoder_sparse_dense(): assert_array_equal(X_trans_sparse.toarray(), X_trans_dense) -def test_one_hot_encoder_handle_unknown(): [email protected]("handle_unknown", ["ignore", "infrequent_if_exist"]) +def test_one_hot_encoder_handle_unknown(handle_unknown): X = np.array([[0, 2, 1], [1, 0, 3], [1, 0, 2]]) X2 = np.array([[4, 1, 1]]) @@ -51,7 +52,7 @@ def test_one_hot_encoder_handle_unknown(): oh.transform(X2) # Test the ignore option, ignores unknown features (giving all 0's) - oh = OneHotEncoder(handle_unknown="ignore") + oh = OneHotEncoder(handle_unknown=handle_unknown) oh.fit(X) X2_passed = X2.copy() assert_array_equal( @@ -63,7 +64,7 @@ def test_one_hot_encoder_handle_unknown(): # Raise error if handle_unknown is neither ignore or error. oh = OneHotEncoder(handle_unknown="42") - with pytest.raises(ValueError, match="handle_unknown should be either"): + with pytest.raises(ValueError, match="handle_unknown should be one of"): oh.fit(X) @@ -79,14 +80,15 @@ def test_one_hot_encoder_not_fitted(): enc.transform(X) -def test_one_hot_encoder_handle_unknown_strings(): [email protected]("handle_unknown", ["ignore", "infrequent_if_exist"]) +def test_one_hot_encoder_handle_unknown_strings(handle_unknown): X = np.array(["11111111", "22", "333", "4444"]).reshape((-1, 1)) X2 = np.array(["55555", "22"]).reshape((-1, 1)) # Non Regression test for the issue #12470 # Test the ignore option, when categories are numpy string dtype # particularly when the known category strings are larger # than the unknown category strings - oh = OneHotEncoder(handle_unknown="ignore") + oh = OneHotEncoder(handle_unknown=handle_unknown) oh.fit(X) X2_passed = X2.copy() assert_array_equal( @@ -267,9 +269,10 @@ def test_one_hot_encoder(X): assert_allclose(Xtr.toarray(), [[0, 1, 1, 0, 1], [1, 0, 0, 1, 1]]) [email protected]("handle_unknown", ["ignore", "infrequent_if_exist"]) @pytest.mark.parametrize("sparse_", [False, True]) @pytest.mark.parametrize("drop", [None, "first"]) -def test_one_hot_encoder_inverse(sparse_, drop): +def test_one_hot_encoder_inverse(handle_unknown, sparse_, drop): X = [["abc", 2, 55], ["def", 1, 55], ["abc", 3, 55]] enc = OneHotEncoder(sparse=sparse_, drop=drop) X_tr = enc.fit_transform(X) @@ -288,7 +291,7 @@ def test_one_hot_encoder_inverse(sparse_, drop): X = [["abc", 2, 55], ["def", 1, 55], ["abc", 3, 55]] enc = OneHotEncoder( sparse=sparse_, - handle_unknown="ignore", + handle_unknown=handle_unknown, categories=[["abc", "def"], [1, 2], [54, 55, 56]], ) X_tr = enc.fit_transform(X) @@ -299,7 +302,7 @@ def test_one_hot_encoder_inverse(sparse_, drop): # with an otherwise numerical output, still object if unknown X = [[2, 55], [1, 55], [3, 55]] enc = OneHotEncoder( - sparse=sparse_, categories=[[1, 2], [54, 56]], handle_unknown="ignore" + sparse=sparse_, categories=[[1, 2], [54, 56]], handle_unknown=handle_unknown ) X_tr = enc.fit_transform(X) exp = np.array(X, dtype=object) @@ -442,6 +445,7 @@ def test_one_hot_encoder_categories(X, cat_exp, cat_dtype): assert np.issubdtype(res.dtype, cat_dtype) [email protected]("handle_unknown", ["ignore", "infrequent_if_exist"]) @pytest.mark.parametrize( "X, X2, cats, cat_dtype", [ @@ -498,7 +502,7 @@ def test_one_hot_encoder_categories(X, cat_exp, cat_dtype): "object-nan-and-None", ], ) -def test_one_hot_encoder_specified_categories(X, X2, cats, cat_dtype): +def test_one_hot_encoder_specified_categories(X, X2, cats, cat_dtype, handle_unknown): enc = OneHotEncoder(categories=cats) exp = np.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]) assert_array_equal(enc.fit_transform(X).toarray(), exp) @@ -513,7 +517,7 @@ def test_one_hot_encoder_specified_categories(X, X2, cats, cat_dtype): enc = OneHotEncoder(categories=cats) with pytest.raises(ValueError, match="Found unknown categories"): enc.fit(X2) - enc = OneHotEncoder(categories=cats, handle_unknown="ignore") + enc = OneHotEncoder(categories=cats, handle_unknown=handle_unknown) exp = np.array([[1.0, 0.0, 0.0], [0.0, 0.0, 0.0]]) assert_array_equal(enc.fit(X2).transform(X2).toarray(), exp) @@ -943,6 +947,510 @@ def test_encoders_has_categorical_tags(Encoder): assert "categorical" in Encoder()._get_tags()["X_types"] +# TODO(1.2): Remove filterwarning when get_feature_names is removed. [email protected]("ignore::FutureWarning:sklearn") [email protected]( + "kwargs", + [ + {"max_categories": 2}, + {"min_frequency": 11}, + {"min_frequency": 0.29}, + {"max_categories": 2, "min_frequency": 6}, + {"max_categories": 4, "min_frequency": 12}, + ], +) [email protected]("categories", ["auto", [["a", "b", "c", "d"]]]) +def test_ohe_infrequent_two_levels(kwargs, categories): + """Test that different parameters for combine 'a', 'c', and 'd' into + the infrequent category works as expected.""" + + X_train = np.array([["a"] * 5 + ["b"] * 20 + ["c"] * 10 + ["d"] * 3]).T + ohe = OneHotEncoder( + categories=categories, + handle_unknown="infrequent_if_exist", + sparse=False, + **kwargs, + ).fit(X_train) + assert_array_equal(ohe.infrequent_categories_, [["a", "c", "d"]]) + + X_test = [["b"], ["a"], ["c"], ["d"], ["e"]] + expected = np.array([[1, 0], [0, 1], [0, 1], [0, 1], [0, 1]]) + + X_trans = ohe.transform(X_test) + assert_allclose(expected, X_trans) + + expected_inv = [[col] for col in ["b"] + ["infrequent_sklearn"] * 4] + X_inv = ohe.inverse_transform(X_trans) + assert_array_equal(expected_inv, X_inv) + + # TODO(1.2) Remove when get_feature_names is removed + feature_names = ohe.get_feature_names() + assert_array_equal(["x0_b", "x0_infrequent_sklearn"], feature_names) + + feature_names = ohe.get_feature_names_out() + assert_array_equal(["x0_b", "x0_infrequent_sklearn"], feature_names) + + +# TODO(1.2): Remove filterwarning when get_feature_names is removed. [email protected]("ignore::FutureWarning:sklearn") [email protected]("drop", ["if_binary", "first", ["b"]]) +def test_ohe_infrequent_two_levels_drop_frequent(drop): + """Test two levels and dropping the frequent category.""" + + X_train = np.array([["a"] * 5 + ["b"] * 20 + ["c"] * 10 + ["d"] * 3]).T + ohe = OneHotEncoder( + handle_unknown="infrequent_if_exist", sparse=False, max_categories=2, drop=drop + ).fit(X_train) + assert_array_equal(ohe.drop_idx_, [0]) + + X_test = np.array([["b"], ["c"]]) + X_trans = ohe.transform(X_test) + assert_allclose([[0], [1]], X_trans) + + # TODO(1.2) Remove when get_feature_names is removed + feature_names = ohe.get_feature_names() + assert_array_equal(["x0_infrequent_sklearn"], feature_names) + + feature_names = ohe.get_feature_names_out() + assert_array_equal(["x0_infrequent_sklearn"], feature_names) + + X_inverse = ohe.inverse_transform(X_trans) + assert_array_equal([["b"], ["infrequent_sklearn"]], X_inverse) + + [email protected]("drop", [["a"], ["d"]]) +def test_ohe_infrequent_two_levels_drop_infrequent_errors(drop): + """Test two levels and dropping any infrequent category removes the + whole infrequent category.""" + + X_train = np.array([["a"] * 5 + ["b"] * 20 + ["c"] * 10 + ["d"] * 3]).T + ohe = OneHotEncoder( + handle_unknown="infrequent_if_exist", sparse=False, max_categories=2, drop=drop + ) + + msg = f"Unable to drop category {drop[0]!r} from feature 0 because it is infrequent" + with pytest.raises(ValueError, match=msg): + ohe.fit(X_train) + + +# TODO(1.2): Remove filterwarning when get_feature_names is removed. [email protected]("ignore::FutureWarning:sklearn") [email protected]( + "kwargs", + [ + {"max_categories": 3}, + {"min_frequency": 6}, + {"min_frequency": 9}, + {"min_frequency": 0.24}, + {"min_frequency": 0.16}, + {"max_categories": 3, "min_frequency": 8}, + {"max_categories": 4, "min_frequency": 6}, + ], +) +def test_ohe_infrequent_three_levels(kwargs): + """Test that different parameters for combing 'a', and 'd' into + the infrequent category works as expected.""" + + X_train = np.array([["a"] * 5 + ["b"] * 20 + ["c"] * 10 + ["d"] * 3]).T + ohe = OneHotEncoder( + handle_unknown="infrequent_if_exist", sparse=False, **kwargs + ).fit(X_train) + assert_array_equal(ohe.infrequent_categories_, [["a", "d"]]) + + X_test = [["b"], ["a"], ["c"], ["d"], ["e"]] + expected = np.array([[1, 0, 0], [0, 0, 1], [0, 1, 0], [0, 0, 1], [0, 0, 1]]) + + X_trans = ohe.transform(X_test) + assert_allclose(expected, X_trans) + + expected_inv = [ + ["b"], + ["infrequent_sklearn"], + ["c"], + ["infrequent_sklearn"], + ["infrequent_sklearn"], + ] + X_inv = ohe.inverse_transform(X_trans) + assert_array_equal(expected_inv, X_inv) + + # TODO(1.2): Remove get_feature_names is removed. + feature_names = ohe.get_feature_names() + assert_array_equal(["x0_b", "x0_c", "x0_infrequent_sklearn"], feature_names) + + feature_names = ohe.get_feature_names_out() + assert_array_equal(["x0_b", "x0_c", "x0_infrequent_sklearn"], feature_names) + + [email protected]("drop", ["first", ["b"]]) +def test_ohe_infrequent_three_levels_drop_frequent(drop): + """Test three levels and dropping the frequent category.""" + + X_train = np.array([["a"] * 5 + ["b"] * 20 + ["c"] * 10 + ["d"] * 3]).T + ohe = OneHotEncoder( + handle_unknown="infrequent_if_exist", sparse=False, max_categories=3, drop=drop + ).fit(X_train) + + X_test = np.array([["b"], ["c"], ["d"]]) + assert_allclose([[0, 0], [1, 0], [0, 1]], ohe.transform(X_test)) + + # Check handle_unknown="ignore" + ohe.set_params(handle_unknown="ignore").fit(X_train) + msg = "Found unknown categories" + with pytest.warns(UserWarning, match=msg): + X_trans = ohe.transform([["b"], ["e"]]) + + assert_allclose([[0, 0], [0, 0]], X_trans) + + [email protected]("drop", [["a"], ["d"]]) +def test_ohe_infrequent_three_levels_drop_infrequent_errors(drop): + """Test three levels and dropping the infrequent category.""" + X_train = np.array([["a"] * 5 + ["b"] * 20 + ["c"] * 10 + ["d"] * 3]).T + ohe = OneHotEncoder( + handle_unknown="infrequent_if_exist", sparse=False, max_categories=3, drop=drop + ) + + msg = f"Unable to drop category {drop[0]!r} from feature 0 because it is infrequent" + with pytest.raises(ValueError, match=msg): + ohe.fit(X_train) + + +def test_ohe_infrequent_handle_unknown_error(): + """Test that different parameters for combining 'a', and 'd' into + the infrequent category works as expected.""" + + X_train = np.array([["a"] * 5 + ["b"] * 20 + ["c"] * 10 + ["d"] * 3]).T + ohe = OneHotEncoder(handle_unknown="error", sparse=False, max_categories=3).fit( + X_train + ) + assert_array_equal(ohe.infrequent_categories_, [["a", "d"]]) + + # all categories are known + X_test = [["b"], ["a"], ["c"], ["d"]] + expected = np.array([[1, 0, 0], [0, 0, 1], [0, 1, 0], [0, 0, 1]]) + + X_trans = ohe.transform(X_test) + assert_allclose(expected, X_trans) + + # 'bad' is not known and will error + X_test = [["bad"]] + msg = r"Found unknown categories \['bad'\] in column 0" + with pytest.raises(ValueError, match=msg): + ohe.transform(X_test) + + [email protected]( + "kwargs", [{"max_categories": 3, "min_frequency": 1}, {"min_frequency": 4}] +) +def test_ohe_infrequent_two_levels_user_cats_one_frequent(kwargs): + """'a' is the only frequent category, all other categories are infrequent.""" + + X_train = np.array([["a"] * 5 + ["e"] * 30], dtype=object).T + ohe = OneHotEncoder( + categories=[["c", "d", "a", "b"]], + sparse=False, + handle_unknown="infrequent_if_exist", + **kwargs, + ).fit(X_train) + + X_test = [["a"], ["b"], ["c"], ["d"], ["e"]] + expected = np.array([[1, 0], [0, 1], [0, 1], [0, 1], [0, 1]]) + + X_trans = ohe.transform(X_test) + assert_allclose(expected, X_trans) + + # 'a' is dropped + drops = ["first", "if_binary", ["a"]] + X_test = [["a"], ["c"]] + for drop in drops: + ohe.set_params(drop=drop).fit(X_train) + assert_allclose([[0], [1]], ohe.transform(X_test)) + + +def test_ohe_infrequent_two_levels_user_cats(): + """Test that the order of the categories provided by a user is respected.""" + X_train = np.array( + [["a"] * 5 + ["b"] * 20 + ["c"] * 10 + ["d"] * 3], dtype=object + ).T + ohe = OneHotEncoder( + categories=[["c", "d", "a", "b"]], + sparse=False, + handle_unknown="infrequent_if_exist", + max_categories=2, + ).fit(X_train) + + assert_array_equal(ohe.infrequent_categories_, [["c", "d", "a"]]) + + X_test = [["b"], ["a"], ["c"], ["d"], ["e"]] + expected = np.array([[1, 0], [0, 1], [0, 1], [0, 1], [0, 1]]) + + X_trans = ohe.transform(X_test) + assert_allclose(expected, X_trans) + + # 'infrequent' is used to denote the infrequent categories for + # `inverse_transform` + expected_inv = [[col] for col in ["b"] + ["infrequent_sklearn"] * 4] + X_inv = ohe.inverse_transform(X_trans) + assert_array_equal(expected_inv, X_inv) + + +def test_ohe_infrequent_three_levels_user_cats(): + """Test that the order of the categories provided by a user is respected. + In this case 'c' is encoded as the first category and 'b' is encoded + as the second one.""" + + X_train = np.array( + [["a"] * 5 + ["b"] * 20 + ["c"] * 10 + ["d"] * 3], dtype=object + ).T + ohe = OneHotEncoder( + categories=[["c", "d", "b", "a"]], + sparse=False, + handle_unknown="infrequent_if_exist", + max_categories=3, + ).fit(X_train) + + assert_array_equal(ohe.infrequent_categories_, [["d", "a"]]) + + X_test = [["b"], ["a"], ["c"], ["d"], ["e"]] + expected = np.array([[0, 1, 0], [0, 0, 1], [1, 0, 0], [0, 0, 1], [0, 0, 1]]) + + X_trans = ohe.transform(X_test) + assert_allclose(expected, X_trans) + + # 'infrequent' is used to denote the infrequent categories for + # `inverse_transform` + expected_inv = [ + ["b"], + ["infrequent_sklearn"], + ["c"], + ["infrequent_sklearn"], + ["infrequent_sklearn"], + ] + X_inv = ohe.inverse_transform(X_trans) + assert_array_equal(expected_inv, X_inv) + + +def test_ohe_infrequent_mixed(): + """Test infrequent categories where feature 0 has infrequent categories, + and feature 1 does not.""" + + # X[:, 0] 1 and 2 are infrequent + # X[:, 1] nothing is infrequent + X = np.c_[[0, 1, 3, 3, 3, 3, 2, 0, 3], [0, 0, 0, 0, 1, 1, 1, 1, 1]] + + ohe = OneHotEncoder(max_categories=3, drop="if_binary", sparse=False) + ohe.fit(X) + + X_test = [[3, 0], [1, 1]] + X_trans = ohe.transform(X_test) + + # feature 1 is binary so it drops a category 0 + assert_allclose(X_trans, [[0, 1, 0, 0], [0, 0, 1, 1]]) + + +# TODO(1.2): Remove filterwarning when get_feature_names is removed. [email protected]("ignore::FutureWarning:sklearn") +def test_ohe_infrequent_multiple_categories(): + """Test infrequent categories with feature matrix with 3 features.""" + + X = np.c_[ + [0, 1, 3, 3, 3, 3, 2, 0, 3], + [0, 0, 5, 1, 1, 10, 5, 5, 0], + [1, 0, 1, 0, 1, 0, 1, 0, 1], + ] + + ohe = OneHotEncoder( + categories="auto", max_categories=3, handle_unknown="infrequent_if_exist" + ) + # X[:, 0] 1 and 2 are infrequent + # X[:, 1] 1 and 10 are infrequent + # X[:, 2] nothing is infrequent + + X_trans = ohe.fit_transform(X).toarray() + assert_array_equal(ohe.infrequent_categories_[0], [1, 2]) + assert_array_equal(ohe.infrequent_categories_[1], [1, 10]) + assert_array_equal(ohe.infrequent_categories_[2], None) + + # 'infrequent' is used to denote the infrequent categories + # For the first column, 1 and 2 have the same frequency. In this case, + # 1 will be chosen to be the feature name because is smaller lexiconically + for get_names in ["get_feature_names", "get_feature_names_out"]: + feature_names = getattr(ohe, get_names)() + assert_array_equal( + [ + "x0_0", + "x0_3", + "x0_infrequent_sklearn", + "x1_0", + "x1_5", + "x1_infrequent_sklearn", + "x2_0", + "x2_1", + ], + feature_names, + ) + + expected = [ + [1, 0, 0, 1, 0, 0, 0, 1], + [0, 0, 1, 1, 0, 0, 1, 0], + [0, 1, 0, 0, 1, 0, 0, 1], + [0, 1, 0, 0, 0, 1, 1, 0], + [0, 1, 0, 0, 0, 1, 0, 1], + [0, 1, 0, 0, 0, 1, 1, 0], + [0, 0, 1, 0, 1, 0, 0, 1], + [1, 0, 0, 0, 1, 0, 1, 0], + [0, 1, 0, 1, 0, 0, 0, 1], + ] + + assert_allclose(expected, X_trans) + + X_test = [[3, 1, 2], [4, 0, 3]] + + X_test_trans = ohe.transform(X_test) + + # X[:, 2] does not have an infrequent category, thus it is encoded as all + # zeros + expected = [[0, 1, 0, 0, 0, 1, 0, 0], [0, 0, 1, 1, 0, 0, 0, 0]] + assert_allclose(expected, X_test_trans.toarray()) + + X_inv = ohe.inverse_transform(X_test_trans) + expected_inv = np.array( + [[3, "infrequent_sklearn", None], ["infrequent_sklearn", 0, None]], dtype=object + ) + assert_array_equal(expected_inv, X_inv) + + # error for unknown categories + ohe = OneHotEncoder( + categories="auto", max_categories=3, handle_unknown="error" + ).fit(X) + with pytest.raises(ValueError, match="Found unknown categories"): + ohe.transform(X_test) + + # only infrequent or known categories + X_test = [[1, 1, 1], [3, 10, 0]] + X_test_trans = ohe.transform(X_test) + + expected = [[0, 0, 1, 0, 0, 1, 0, 1], [0, 1, 0, 0, 0, 1, 1, 0]] + assert_allclose(expected, X_test_trans.toarray()) + + X_inv = ohe.inverse_transform(X_test_trans) + + expected_inv = np.array( + [["infrequent_sklearn", "infrequent_sklearn", 1], [3, "infrequent_sklearn", 0]], + dtype=object, + ) + assert_array_equal(expected_inv, X_inv) + + +def test_ohe_infrequent_multiple_categories_dtypes(): + """Test infrequent categories with a pandas dataframe with multiple dtypes.""" + + pd = pytest.importorskip("pandas") + X = pd.DataFrame( + { + "str": ["a", "f", "c", "f", "f", "a", "c", "b", "b"], + "int": [5, 3, 0, 10, 10, 12, 0, 3, 5], + }, + columns=["str", "int"], + ) + + ohe = OneHotEncoder( + categories="auto", max_categories=3, handle_unknown="infrequent_if_exist" + ) + # X[:, 0] 'a', 'b', 'c' have the same frequency. 'a' and 'b' will be + # considered infrequent because they are greater + + # X[:, 1] 0, 3, 5, 10 has frequency 2 and 12 has frequency 1. + # 0, 3, 12 will be considered infrequent + + X_trans = ohe.fit_transform(X).toarray() + assert_array_equal(ohe.infrequent_categories_[0], ["a", "b"]) + assert_array_equal(ohe.infrequent_categories_[1], [0, 3, 12]) + + expected = [ + [0, 0, 1, 1, 0, 0], + [0, 1, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 1], + [0, 1, 0, 0, 1, 0], + [0, 1, 0, 0, 1, 0], + [0, 0, 1, 0, 0, 1], + [1, 0, 0, 0, 0, 1], + [0, 0, 1, 0, 0, 1], + [0, 0, 1, 1, 0, 0], + ] + + assert_allclose(expected, X_trans) + + X_test = pd.DataFrame({"str": ["b", "f"], "int": [14, 12]}, columns=["str", "int"]) + + expected = [[0, 0, 1, 0, 0, 1], [0, 1, 0, 0, 0, 1]] + X_test_trans = ohe.transform(X_test) + assert_allclose(expected, X_test_trans.toarray()) + + X_inv = ohe.inverse_transform(X_test_trans) + expected_inv = np.array( + [["infrequent_sklearn", "infrequent_sklearn"], ["f", "infrequent_sklearn"]], + dtype=object, + ) + assert_array_equal(expected_inv, X_inv) + + # only infrequent or known categories + X_test = pd.DataFrame({"str": ["c", "b"], "int": [12, 5]}, columns=["str", "int"]) + X_test_trans = ohe.transform(X_test).toarray() + expected = [[1, 0, 0, 0, 0, 1], [0, 0, 1, 1, 0, 0]] + assert_allclose(expected, X_test_trans) + + X_inv = ohe.inverse_transform(X_test_trans) + expected_inv = np.array( + [["c", "infrequent_sklearn"], ["infrequent_sklearn", 5]], dtype=object + ) + assert_array_equal(expected_inv, X_inv) + + [email protected]("kwargs", [{"min_frequency": 21, "max_categories": 1}]) +def test_ohe_infrequent_one_level_errors(kwargs): + """All user provided categories are infrequent.""" + X_train = np.array([["a"] * 5 + ["b"] * 20 + ["c"] * 10 + ["d"] * 2]).T + + ohe = OneHotEncoder(handle_unknown="infrequent_if_exist", sparse=False, **kwargs) + ohe.fit(X_train) + + X_trans = ohe.transform([["a"]]) + assert_allclose(X_trans, [[1]]) + + [email protected]("kwargs", [{"min_frequency": 2, "max_categories": 3}]) +def test_ohe_infrequent_user_cats_unknown_training_errors(kwargs): + """All user provided categories are infrequent.""" + + X_train = np.array([["e"] * 3], dtype=object).T + ohe = OneHotEncoder( + categories=[["c", "d", "a", "b"]], + sparse=False, + handle_unknown="infrequent_if_exist", + **kwargs, + ).fit(X_train) + + X_trans = ohe.transform([["a"], ["e"]]) + assert_allclose(X_trans, [[1], [1]]) + + [email protected]( + "kwargs, error_msg", + [ + ({"max_categories": -2}, "max_categories must be greater than 1"), + ({"min_frequency": -1}, "min_frequency must be an integer at least"), + ({"min_frequency": 1.1}, "min_frequency must be an integer at least"), + ], +) +def test_ohe_infrequent_invalid_parameters_error(kwargs, error_msg): + X_train = np.array([["a"] * 5 + ["b"] * 20 + ["c"] * 10 + ["d"] * 2]).T + + ohe = OneHotEncoder(handle_unknown="infrequent_if_exist", **kwargs) + with pytest.raises(ValueError, match=error_msg): + ohe.fit(X_train) + + # TODO: Remove in 1.2 when get_feature_names is removed def test_one_hot_encoder_get_feature_names_deprecated(): X = np.array([["cat", "dog"]], dtype=object).T @@ -1020,8 +1528,9 @@ def test_ohe_missing_value_support_pandas(): assert_allclose(Xtr, expected_df_trans) [email protected]("handle_unknown", ["infrequent_if_exist", "ignore"]) @pytest.mark.parametrize("pd_nan_type", ["pd.NA", "np.nan"]) -def test_ohe_missing_value_support_pandas_categorical(pd_nan_type): +def test_ohe_missing_value_support_pandas_categorical(pd_nan_type, handle_unknown): # checks pandas dataframe with categorical features pd = pytest.importorskip("pandas") @@ -1042,7 +1551,7 @@ def test_ohe_missing_value_support_pandas_categorical(pd_nan_type): ] ) - ohe = OneHotEncoder(sparse=False, handle_unknown="ignore") + ohe = OneHotEncoder(sparse=False, handle_unknown=handle_unknown) df_trans = ohe.fit_transform(df) assert_allclose(expected_df_trans, df_trans) @@ -1051,11 +1560,13 @@ def test_ohe_missing_value_support_pandas_categorical(pd_nan_type): assert np.isnan(ohe.categories_[0][-1]) -def test_ohe_drop_first_handle_unknown_ignore_warns(): - """Check drop='first' and handle_unknown='ignore' during transform.""" [email protected]("handle_unknown", ["ignore", "infrequent_if_exist"]) +def test_ohe_drop_first_handle_unknown_ignore_warns(handle_unknown): + """Check drop='first' and handle_unknown='ignore'/'infrequent_if_exist' + during transform.""" X = [["a", 0], ["b", 2], ["b", 1]] - ohe = OneHotEncoder(drop="first", sparse=False, handle_unknown="ignore") + ohe = OneHotEncoder(drop="first", sparse=False, handle_unknown=handle_unknown) X_trans = ohe.fit_transform(X) X_expected = np.array( @@ -1085,11 +1596,12 @@ def test_ohe_drop_first_handle_unknown_ignore_warns(): assert_array_equal(X_inv, np.array([["a", 0]], dtype=object)) -def test_ohe_drop_if_binary_handle_unknown_ignore_warns(): [email protected]("handle_unknown", ["ignore", "infrequent_if_exist"]) +def test_ohe_drop_if_binary_handle_unknown_ignore_warns(handle_unknown): """Check drop='if_binary' and handle_unknown='ignore' during transform.""" X = [["a", 0], ["b", 2], ["b", 1]] - ohe = OneHotEncoder(drop="if_binary", sparse=False, handle_unknown="ignore") + ohe = OneHotEncoder(drop="if_binary", sparse=False, handle_unknown=handle_unknown) X_trans = ohe.fit_transform(X) X_expected = np.array( @@ -1119,16 +1631,17 @@ def test_ohe_drop_if_binary_handle_unknown_ignore_warns(): assert_array_equal(X_inv, np.array([["a", None]], dtype=object)) -def test_ohe_drop_first_explicit_categories(): - """Check drop='first' and handle_unknown='ignore' during fit with - categories passed in.""" [email protected]("handle_unknown", ["ignore", "infrequent_if_exist"]) +def test_ohe_drop_first_explicit_categories(handle_unknown): + """Check drop='first' and handle_unknown='ignore'/'infrequent_if_exist' + during fit with categories passed in.""" X = [["a", 0], ["b", 2], ["b", 1]] ohe = OneHotEncoder( drop="first", sparse=False, - handle_unknown="ignore", + handle_unknown=handle_unknown, categories=[["b", "a"], [1, 2]], ) ohe.fit(X) diff --git a/sklearn/utils/tests/test_encode.py b/sklearn/utils/tests/test_encode.py index a430db37d6ad9..083db25b7ca80 100644 --- a/sklearn/utils/tests/test_encode.py +++ b/sklearn/utils/tests/test_encode.py @@ -7,26 +7,49 @@ from sklearn.utils._encode import _unique from sklearn.utils._encode import _encode from sklearn.utils._encode import _check_unknown +from sklearn.utils._encode import _get_counts @pytest.mark.parametrize( "values, expected", [ (np.array([2, 1, 3, 1, 3], dtype="int64"), np.array([1, 2, 3], dtype="int64")), + ( + np.array([2, 1, np.nan, 1, np.nan], dtype="float32"), + np.array([1, 2, np.nan], dtype="float32"), + ), ( np.array(["b", "a", "c", "a", "c"], dtype=object), np.array(["a", "b", "c"], dtype=object), ), + ( + np.array(["b", "a", None, "a", None], dtype=object), + np.array(["a", "b", None], dtype=object), + ), (np.array(["b", "a", "c", "a", "c"]), np.array(["a", "b", "c"])), ], - ids=["int64", "object", "str"], + ids=["int64", "float32-nan", "object", "object-None", "str"], ) def test_encode_util(values, expected): uniques = _unique(values) assert_array_equal(uniques, expected) + + result, encoded = _unique(values, return_inverse=True) + assert_array_equal(result, expected) + assert_array_equal(encoded, np.array([1, 0, 2, 0, 2])) + encoded = _encode(values, uniques=uniques) assert_array_equal(encoded, np.array([1, 0, 2, 0, 2])) + result, counts = _unique(values, return_counts=True) + assert_array_equal(result, expected) + assert_array_equal(counts, np.array([2, 1, 2])) + + result, encoded, counts = _unique(values, return_inverse=True, return_counts=True) + assert_array_equal(result, expected) + assert_array_equal(encoded, np.array([1, 0, 2, 0, 2])) + assert_array_equal(counts, np.array([2, 1, 2])) + def test_encode_with_check_unknown(): # test for the check_unknown parameter of _encode() @@ -211,3 +234,44 @@ def test_check_unknown_with_both_missing_values(): assert diff[0] is None assert np.isnan(diff[1]) assert_array_equal(valid_mask, [False, True, True, True, False, False, False]) + + [email protected]( + "values, uniques, expected_counts", + [ + (np.array([1] * 10 + [2] * 4 + [3] * 15), np.array([1, 2, 3]), [10, 4, 15]), + ( + np.array([1] * 10 + [2] * 4 + [3] * 15), + np.array([1, 2, 3, 5]), + [10, 4, 15, 0], + ), + ( + np.array([np.nan] * 10 + [2] * 4 + [3] * 15), + np.array([2, 3, np.nan]), + [4, 15, 10], + ), + ( + np.array(["b"] * 4 + ["a"] * 16 + ["c"] * 20, dtype=object), + ["a", "b", "c"], + [16, 4, 20], + ), + ( + np.array(["b"] * 4 + ["a"] * 16 + ["c"] * 20, dtype=object), + ["c", "b", "a"], + [20, 4, 16], + ), + ( + np.array([np.nan] * 4 + ["a"] * 16 + ["c"] * 20, dtype=object), + ["c", np.nan, "a"], + [20, 4, 16], + ), + ( + np.array(["b"] * 4 + ["a"] * 16 + ["c"] * 20, dtype=object), + ["a", "b", "c", "e"], + [16, 4, 20, 0], + ), + ], +) +def test_get_counts(values, uniques, expected_counts): + counts = _get_counts(values, uniques) + assert_array_equal(counts, expected_counts)
[ { "path": "doc/modules/preprocessing.rst", "old_path": "a/doc/modules/preprocessing.rst", "new_path": "b/doc/modules/preprocessing.rst", "metadata": "diff --git a/doc/modules/preprocessing.rst b/doc/modules/preprocessing.rst\nindex 035f2b90203ca..997bccf66782d 100644\n--- a/doc/modules/preprocessing.rst\n+++ b/doc/modules/preprocessing.rst\n@@ -594,17 +594,19 @@ dataset::\n array([[1., 0., 0., 1., 0., 0., 1., 0., 0., 0.]])\n \n If there is a possibility that the training data might have missing categorical\n-features, it can often be better to specify ``handle_unknown='ignore'`` instead\n-of setting the ``categories`` manually as above. When\n-``handle_unknown='ignore'`` is specified and unknown categories are encountered\n-during transform, no error will be raised but the resulting one-hot encoded\n-columns for this feature will be all zeros\n-(``handle_unknown='ignore'`` is only supported for one-hot encoding)::\n-\n- >>> enc = preprocessing.OneHotEncoder(handle_unknown='ignore')\n+features, it can often be better to specify\n+`handle_unknown='infrequent_if_exist'` instead of setting the `categories`\n+manually as above. When `handle_unknown='infrequent_if_exist'` is specified\n+and unknown categories are encountered during transform, no error will be\n+raised but the resulting one-hot encoded columns for this feature will be all\n+zeros or considered as an infrequent category if enabled.\n+(`handle_unknown='infrequent_if_exist'` is only supported for one-hot\n+encoding)::\n+\n+ >>> enc = preprocessing.OneHotEncoder(handle_unknown='infrequent_if_exist')\n >>> X = [['male', 'from US', 'uses Safari'], ['female', 'from Europe', 'uses Firefox']]\n >>> enc.fit(X)\n- OneHotEncoder(handle_unknown='ignore')\n+ OneHotEncoder(handle_unknown='infrequent_if_exist')\n >>> enc.transform([['female', 'from Asia', 'uses Chrome']]).toarray()\n array([[1., 0., 0., 0., 0., 0.]])\n \n@@ -621,7 +623,8 @@ since co-linearity would cause the covariance matrix to be non-invertible::\n ... ['female', 'from Europe', 'uses Firefox']]\n >>> drop_enc = preprocessing.OneHotEncoder(drop='first').fit(X)\n >>> drop_enc.categories_\n- [array(['female', 'male'], dtype=object), array(['from Europe', 'from US'], dtype=object), array(['uses Firefox', 'uses Safari'], dtype=object)]\n+ [array(['female', 'male'], dtype=object), array(['from Europe', 'from US'], dtype=object),\n+ array(['uses Firefox', 'uses Safari'], dtype=object)]\n >>> drop_enc.transform(X).toarray()\n array([[1., 1., 1.],\n [0., 0., 0.]])\n@@ -634,7 +637,8 @@ categories. In this case, you can set the parameter `drop='if_binary'`.\n ... ['female', 'Asia', 'Chrome']]\n >>> drop_enc = preprocessing.OneHotEncoder(drop='if_binary').fit(X)\n >>> drop_enc.categories_\n- [array(['female', 'male'], dtype=object), array(['Asia', 'Europe', 'US'], dtype=object), array(['Chrome', 'Firefox', 'Safari'], dtype=object)]\n+ [array(['female', 'male'], dtype=object), array(['Asia', 'Europe', 'US'], dtype=object),\n+ array(['Chrome', 'Firefox', 'Safari'], dtype=object)]\n >>> drop_enc.transform(X).toarray()\n array([[1., 0., 0., 1., 0., 0., 1.],\n [0., 0., 1., 0., 0., 1., 0.],\n@@ -699,6 +703,107 @@ separate categories::\n See :ref:`dict_feature_extraction` for categorical features that are\n represented as a dict, not as scalars.\n \n+.. _one_hot_encoder_infrequent_categories:\n+\n+Infrequent categories\n+---------------------\n+\n+:class:`OneHotEncoder` supports aggregating infrequent categories into a single\n+output for each feature. The parameters to enable the gathering of infrequent\n+categories are `min_frequency` and `max_categories`.\n+\n+1. `min_frequency` is either an integer greater or equal to 1, or a float in\n+ the interval `(0.0, 1.0)`. If `min_frequency` is an integer, categories with\n+ a cardinality smaller than `min_frequency` will be considered infrequent.\n+ If `min_frequency` is a float, categories with a cardinality smaller than\n+ this fraction of the total number of samples will be considered infrequent.\n+ The default value is 1, which means every category is encoded separately.\n+\n+2. `max_categories` is either `None` or any integer greater than 1. This\n+ parameter sets an upper limit to the number of output features for each\n+ input feature. `max_categories` includes the feature that combines\n+ infrequent categories.\n+\n+In the following example, the categories, `'dog', 'snake'` are considered\n+infrequent::\n+\n+ >>> X = np.array([['dog'] * 5 + ['cat'] * 20 + ['rabbit'] * 10 +\n+ ... ['snake'] * 3], dtype=object).T\n+ >>> enc = preprocessing.OneHotEncoder(min_frequency=6, sparse=False).fit(X)\n+ >>> enc.infrequent_categories_\n+ [array(['dog', 'snake'], dtype=object)]\n+ >>> enc.transform(np.array([['dog'], ['cat'], ['rabbit'], ['snake']]))\n+ array([[0., 0., 1.],\n+ [1., 0., 0.],\n+ [0., 1., 0.],\n+ [0., 0., 1.]])\n+\n+By setting handle_unknown to `'infrequent_if_exist'`, unknown categories will\n+be considered infrequent::\n+\n+ >>> enc = preprocessing.OneHotEncoder(\n+ ... handle_unknown='infrequent_if_exist', sparse=False, min_frequency=6)\n+ >>> enc = enc.fit(X)\n+ >>> enc.transform(np.array([['dragon']]))\n+ array([[0., 0., 1.]])\n+\n+:meth:`OneHotEncoder.get_feature_names_out` uses 'infrequent' as the infrequent\n+feature name::\n+\n+ >>> enc.get_feature_names_out()\n+ array(['x0_cat', 'x0_rabbit', 'x0_infrequent_sklearn'], dtype=object)\n+\n+When `'handle_unknown'` is set to `'infrequent_if_exist'` and an unknown\n+category is encountered in transform:\n+\n+1. If infrequent category support was not configured or there was no\n+ infrequent category during training, the resulting one-hot encoded columns\n+ for this feature will be all zeros. In the inverse transform, an unknown\n+ category will be denoted as `None`.\n+\n+2. If there is an infrequent category during training, the unknown category\n+ will be considered infrequent. In the inverse transform, 'infrequent_sklearn'\n+ will be used to represent the infrequent category.\n+\n+Infrequent categories can also be configured using `max_categories`. In the\n+following example, we set `max_categories=2` to limit the number of features in\n+the output. This will result in all but the `'cat'` category to be considered\n+infrequent, leading to two features, one for `'cat'` and one for infrequent\n+categories - which are all the others::\n+\n+ >>> enc = preprocessing.OneHotEncoder(max_categories=2, sparse=False)\n+ >>> enc = enc.fit(X)\n+ >>> enc.transform([['dog'], ['cat'], ['rabbit'], ['snake']])\n+ array([[0., 1.],\n+ [1., 0.],\n+ [0., 1.],\n+ [0., 1.]])\n+\n+If both `max_categories` and `min_frequency` are non-default values, then\n+categories are selected based on `min_frequency` first and `max_categories`\n+categories are kept. In the following example, `min_frequency=4` considers\n+only `snake` to be infrequent, but `max_categories=3`, forces `dog` to also be\n+infrequent::\n+\n+ >>> enc = preprocessing.OneHotEncoder(min_frequency=4, max_categories=3, sparse=False)\n+ >>> enc = enc.fit(X)\n+ >>> enc.transform([['dog'], ['cat'], ['rabbit'], ['snake']])\n+ array([[0., 0., 1.],\n+ [1., 0., 0.],\n+ [0., 1., 0.],\n+ [0., 0., 1.]])\n+\n+If there are infrequent categories with the same cardinality at the cutoff of\n+`max_categories`, then then the first `max_categories` are taken based on lexicon\n+ordering. In the following example, \"b\", \"c\", and \"d\", have the same cardinality\n+and with `max_categories=2`, \"b\" and \"c\" are infrequent because they have a higher\n+lexicon order.\n+\n+ >>> X = np.asarray([[\"a\"] * 20 + [\"b\"] * 10 + [\"c\"] * 10 + [\"d\"] * 10], dtype=object).T\n+ >>> enc = preprocessing.OneHotEncoder(max_categories=3).fit(X)\n+ >>> enc.infrequent_categories_\n+ [array(['b', 'c'], dtype=object)]\n+\n .. _preprocessing_discretization:\n \n Discretization\n@@ -981,7 +1086,7 @@ Interestingly, a :class:`SplineTransformer` of ``degree=0`` is the same as\n Penalties <10.1214/ss/1038425655>`. Statist. Sci. 11 (1996), no. 2, 89--121.\n \n * Perperoglou, A., Sauerbrei, W., Abrahamowicz, M. et al. :doi:`A review of\n- spline function procedures in R <10.1186/s12874-019-0666-3>`. \n+ spline function procedures in R <10.1186/s12874-019-0666-3>`.\n BMC Med Res Methodol 19, 46 (2019).\n \n .. _function_transformer:\n" }, { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 584dd796b5789..a0272f183bf81 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -688,6 +688,11 @@ Changelog\n :mod:`sklearn.preprocessing`\n ............................\n \n+- |Feature| :class:`preprocessing.OneHotEncoder` now supports grouping\n+ infrequent categories into a single feature. Grouping infrequent categories\n+ is enabled by specifying how to select infrequent categories with\n+ `min_frequency` or `max_categories`. :pr:`16018` by `Thomas Fan`_.\n+\n - |Enhancement| Adds a `subsample` parameter to :class:`preprocessing.KBinsDiscretizer`.\n This allows specifying a maximum number of samples to be used while fitting\n the model. The option is only available when `strategy` is set to `quantile`.\n" } ]
1.01
269bdb94898b9944b10de2db6b17fffe7b69a432
[ "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[if_binary-if_binary-get_feature_names]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse[first-False-infrequent_if_exist]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[mixed-float-nan]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse_if_binary", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[array-S-U]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_pandas", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder[mixed]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_drop_first_handle_unknown_ignore_warns[ignore]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_missing_value_support_pandas", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse[first-True-infrequent_if_exist]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[int32-float32]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[first-None-get_feature_names_out]", "sklearn/preprocessing/tests/test_encoders.py::test_X_is_not_1D[X1-fit_transform]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknown_string_dtypes[X_test2-X_train1]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categories[numeric]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse_transform_raise_error_with_unknown[X1-X_trans1-False]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_missing_value_support_pandas_categorical[np.nan]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[first-None-get_feature_names]", "sklearn/preprocessing/tests/test_encoders.py::test_encoder_dtypes_pandas", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype_pandas[float32]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[dataframe-U-U]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknown_string_dtypes[X_test1-X_train1]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_specified_categories_missing_passthrough[object-None-missing-value]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[dataframe-S-O]", "sklearn/preprocessing/tests/test_encoders.py::test_encoder_dtypes", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[numeric-ignore]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[if_binary-None-get_feature_names_out]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[dataframe-O-O]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object-string-nan-ignore]", "sklearn/preprocessing/tests/test_encoders.py::test_invalid_drop_length[drop1]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_handle_unknown_strings[ignore]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object-ignore]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object-string-none-ignore]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknown_string_dtypes[X_test1-X_train2]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[list-O-U]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_set_params", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[array-U-O]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_specified_categories_missing_passthrough[numeric-missing-value]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names[get_feature_names]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object-string-ignore]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_not_fitted", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[None-None-get_feature_names]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_manual[None]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[array-O-O]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[mixed-None]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse_transform_raise_error_with_unknown[X0-X_trans0-False]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[first-if_binary-get_feature_names_out]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[numeric]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_inverse", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[list-S-O]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[list-U-S]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_features_names_out_pandas", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[None-None-get_feature_names_out]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names[get_feature_names_out]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[dataframe-U-O]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categories[missing-float]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder[object]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_specified_categories_missing_passthrough[object-nan-missing_value]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categories[missing-float-nan-object]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names_drop[manual-get_feature_names]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[None-if_binary-get_feature_names_out]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_manual[nan0]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[if_binary-first-get_feature_names]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[array-U-S]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_raise_categories_shape", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[list-S-U]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[first-first-get_feature_names]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_get_feature_names_deprecated", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_missing_values_get_feature_names[nan-get_feature_names]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categories[object]", "sklearn/preprocessing/tests/test_encoders.py::test_invalid_drop_length[drop0]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype_pandas[int32]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_unsorted_categories", "sklearn/preprocessing/tests/test_encoders.py::test_X_is_not_1D_pandas[fit_transform]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories_mixed_columns", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[float32-float32]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categories[mixed]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[float64-float64]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse[first-True-ignore]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_nan_non_float_dtype", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[object]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_missing_values_get_feature_names[None-get_feature_names]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[float64-float32]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_missing_values_get_feature_names[nan-get_feature_names_out]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[if_binary-if_binary-get_feature_names_out]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknown_string_dtypes[X_test1-X_train0]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[None-if_binary-get_feature_names]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_missing_and_unknown[X3-expected_X_trans3-X_test3]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[int32-float64]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[if_binary-None-get_feature_names]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknown_string_dtypes[X_test0-X_train1]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_specified_categories[numeric]", "sklearn/preprocessing/tests/test_encoders.py::test_categories[first-sparse]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[int32-int32]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[if_binary-first-get_feature_names_out]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[mixed-None-nan]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_numeric[float]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_numeric[int]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_has_categorical_tags[OrdinalEncoder]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_equals_if_binary", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_passthrough_missing_values_float_errors_dtype", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse_transform_raise_error_with_unknown[X0-X_trans0-True]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[dataframe-S-S]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknown_string_dtypes[X_test2-X_train0]", "sklearn/preprocessing/tests/test_encoders.py::test_X_is_not_1D[X0-fit_transform]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_warning", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[array-S-O]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names_drop[first-get_feature_names]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknown_string_dtypes[X_test2-X_train2]", "sklearn/preprocessing/tests/test_encoders.py::test_X_is_not_1D[X0-fit]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names_drop[binary-get_feature_names_out]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_fit_with_unseen_category", "sklearn/preprocessing/tests/test_encoders.py::test_categories[first-dense]", "sklearn/preprocessing/tests/test_encoders.py::test_X_is_not_1D_pandas[fit]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[list-U-U]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[dataframe-S-U]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[array-O-U]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names_drop[manual-get_feature_names_out]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names_unicode[get_feature_names]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_invalid_params[X_fit0-params0-Wrong input for parameter `drop`]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_invalid_params[X_fit2-params2-The following categories were supposed]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknown_string_dtypes[X_test0-X_train2]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_raise[params4-ValueError-handle_unknown should be either 'error' or 'use_encoded_value', got ignore.]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_sparse", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_raise[params0-TypeError-unknown_value should be an integer or np.nan when handle_unknown is 'use_encoded_value', got None.]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[float32-int32]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse[None-True-ignore]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_raise[params1-TypeError-unknown_value should only be set when handle_unknown is 'use_encoded_value', got -2.]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[list-U-O]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknown_string_dtypes[X_test0-X_train0]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[None-first-get_feature_names_out]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object-None-and-nan-ignore]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_specified_categories[object-string-cat]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_nan", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names_drop[binary-get_feature_names]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_invalid_params[X_fit1-params1-Wrong input for parameter `drop`]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[mixed-None-float-nan]", "sklearn/preprocessing/tests/test_encoders.py::test_categories[manual-dense]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_missing_and_unknown[X1-expected_X_trans1-X_test1]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_passthrough_missing_values_float", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[list-O-O]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_raise[params3-ValueError-The used value for unknown_value (1) is one of the values already used for encoding the seen categories.]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names_unicode[get_feature_names_out]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_sparse_dense", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[array-U-U]", "sklearn/preprocessing/tests/test_encoders.py::test_categories[manual-sparse]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[first-if_binary-get_feature_names]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_missing_values_get_feature_names[None-get_feature_names_out]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_has_categorical_tags[OneHotEncoder]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_missing_value_support_pandas_categorical[pd.NA-ignore]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_missing_and_unknown[X0-expected_X_trans0-X_test0]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[mixed-nan]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder[numeric]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object-nan-and-None-ignore]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categories[string]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[dataframe-U-S]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[array-S-S]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_specified_categories[object]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_python_integer", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[list-S-S]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[dataframe-O-U]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[first-first-get_feature_names_out]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse[None-False-ignore]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_raise[params2-TypeError-unknown_value should be an integer or np.nan when handle_unknown is 'use_encoded_value', got bla.]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[None-first-get_feature_names]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_missing_value_support_pandas_categorical[np.nan-ignore]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_drop_first_explicit_categories[ignore]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_drop_if_binary_handle_unknown_ignore_warns[ignore]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_missing_value_support_pandas_categorical[pd.NA]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype_pandas[float64]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[float64-int32]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names_drop[first-get_feature_names_out]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_string", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_manual[nan1]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categories[missing-np.nan-object]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse_transform_raise_error_with_unknown[X1-X_trans1-True]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_missing_and_unknown[X2-expected_X_trans2-X_test2]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[mixed]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[float32-float64]", "sklearn/preprocessing/tests/test_encoders.py::test_X_is_not_1D[X1-fit]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse[first-False-ignore]" ]
[ "sklearn/utils/tests/test_encode.py::test_get_counts[values5-uniques5-expected_counts5]", "sklearn/utils/tests/test_encode.py::test_encode_util[float32-nan]", "sklearn/utils/tests/test_encode.py::test_check_unknown_missing_values[False-nan0]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object-string-infrequent_if_exist]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_three_levels_drop_infrequent_errors[drop0]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_two_levels[categories1-kwargs1]", "sklearn/utils/tests/test_encode.py::test_get_counts[values6-uniques6-expected_counts6]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_three_levels[kwargs6]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_two_levels[auto-kwargs1]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_two_levels[auto-kwargs2]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_drop_if_binary_handle_unknown_ignore_warns[infrequent_if_exist]", "sklearn/utils/tests/test_encode.py::test_encode_util[str]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_two_levels_drop_frequent[first]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_three_levels_user_cats", "sklearn/utils/tests/test_encode.py::test_get_counts[values4-uniques4-expected_counts4]", "sklearn/utils/tests/test_encode.py::test_get_counts[values2-uniques2-expected_counts2]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_two_levels[auto-kwargs0]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_two_levels[auto-kwargs4]", "sklearn/utils/tests/test_encode.py::test_unique_util_missing_values_objects[False-nan0]", "sklearn/utils/tests/test_encode.py::test_check_unknown[values6-uniques6-expected_diff6-expected_mask6]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_handle_unknown[infrequent_if_exist]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse[None-True-infrequent_if_exist]", "sklearn/utils/tests/test_encode.py::test_unique_util_missing_values_objects[False-None]", "sklearn/utils/tests/test_encode.py::test_encode_util[int64]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_two_levels_user_cats", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_two_levels_drop_infrequent_errors[drop1]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_two_levels[categories1-kwargs2]", "sklearn/utils/tests/test_encode.py::test_check_unknown_missing_values[True-nan1]", "sklearn/utils/tests/test_encode.py::test_unique_util_missing_values_objects[False-nan1]", "sklearn/utils/tests/test_encode.py::test_check_unknown[values7-uniques7-expected_diff7-expected_mask7]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_two_levels_drop_frequent[if_binary]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object-string-nan-infrequent_if_exist]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_drop_first_handle_unknown_ignore_warns[infrequent_if_exist]", "sklearn/utils/tests/test_encode.py::test_check_unknown_with_both_missing_values", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_three_levels_drop_frequent[drop1]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[numeric-infrequent_if_exist]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_handle_unknown_strings[infrequent_if_exist]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_one_level_errors[kwargs0]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_invalid_parameters_error[kwargs0-max_categories must be greater than 1]", "sklearn/utils/tests/test_encode.py::test_check_unknown[values8-uniques8-expected_diff8-expected_mask8]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_two_levels_drop_infrequent_errors[drop0]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_drop_first_explicit_categories[infrequent_if_exist]", "sklearn/utils/tests/test_encode.py::test_check_unknown[values5-uniques5-expected_diff5-expected_mask5]", "sklearn/utils/tests/test_encode.py::test_unique_util_missing_values_numeric", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object-infrequent_if_exist]", "sklearn/utils/tests/test_encode.py::test_unique_util_missing_values_objects[True-nan1]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse[None-False-infrequent_if_exist]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_invalid_parameters_error[kwargs2-min_frequency must be an integer at least]", "sklearn/utils/tests/test_encode.py::test_check_unknown_missing_values[False-None]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_mixed", "sklearn/utils/tests/test_encode.py::test_unique_util_with_all_missing_values", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_two_levels[categories1-kwargs3]", "sklearn/utils/tests/test_encode.py::test_check_unknown_missing_values[True-nan0]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_invalid_parameters_error[kwargs1-min_frequency must be an integer at least]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object-None-and-nan-infrequent_if_exist]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_three_levels[kwargs3]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_missing_value_support_pandas_categorical[np.nan-infrequent_if_exist]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_three_levels[kwargs5]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_two_levels[categories1-kwargs0]", "sklearn/utils/tests/test_encode.py::test_check_unknown_missing_values[True-None]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_two_levels_user_cats_one_frequent[kwargs0]", "sklearn/utils/tests/test_encode.py::test_unique_util_missing_values_objects[True-nan0]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_user_cats_unknown_training_errors[kwargs0]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_three_levels[kwargs4]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_three_levels[kwargs0]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_handle_unknown[ignore]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_multiple_categories_dtypes", "sklearn/utils/tests/test_encode.py::test_encode_util[object-None]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_three_levels_drop_frequent[first]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_two_levels[auto-kwargs3]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_two_levels[categories1-kwargs4]", "sklearn/utils/tests/test_encode.py::test_check_unknown[values3-uniques3-expected_diff3-expected_mask3]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object-string-none-infrequent_if_exist]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_missing_value_support_pandas_categorical[pd.NA-infrequent_if_exist]", "sklearn/utils/tests/test_encode.py::test_check_unknown[values0-uniques0-expected_diff0-expected_mask0]", "sklearn/utils/tests/test_encode.py::test_unique_util_missing_values_objects[True-None]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object-nan-and-None-infrequent_if_exist]", "sklearn/utils/tests/test_encode.py::test_get_counts[values0-uniques0-expected_counts0]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_two_levels_drop_frequent[drop2]", "sklearn/utils/tests/test_encode.py::test_check_unknown[values2-uniques2-expected_diff2-expected_mask2]", "sklearn/utils/tests/test_encode.py::test_check_unknown_missing_values[False-nan1]", "sklearn/utils/tests/test_encode.py::test_check_unknown[values9-uniques9-expected_diff9-expected_mask9]", "sklearn/utils/tests/test_encode.py::test_encode_with_check_unknown", "sklearn/utils/tests/test_encode.py::test_get_counts[values3-uniques3-expected_counts3]", "sklearn/utils/tests/test_encode.py::test_encode_util[object]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_three_levels[kwargs1]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_three_levels[kwargs2]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_multiple_categories", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_two_levels_user_cats_one_frequent[kwargs1]", "sklearn/utils/tests/test_encode.py::test_check_unknown[values4-uniques4-expected_diff4-expected_mask4]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_three_levels_drop_infrequent_errors[drop1]", "sklearn/utils/tests/test_encode.py::test_get_counts[values1-uniques1-expected_counts1]", "sklearn/utils/tests/test_encode.py::test_check_unknown[values1-uniques1-expected_diff1-expected_mask1]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_handle_unknown_error" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/modules/preprocessing.rst", "old_path": "a/doc/modules/preprocessing.rst", "new_path": "b/doc/modules/preprocessing.rst", "metadata": "diff --git a/doc/modules/preprocessing.rst b/doc/modules/preprocessing.rst\nindex 035f2b90203ca..997bccf66782d 100644\n--- a/doc/modules/preprocessing.rst\n+++ b/doc/modules/preprocessing.rst\n@@ -594,17 +594,19 @@ dataset::\n array([[1., 0., 0., 1., 0., 0., 1., 0., 0., 0.]])\n \n If there is a possibility that the training data might have missing categorical\n-features, it can often be better to specify ``handle_unknown='ignore'`` instead\n-of setting the ``categories`` manually as above. When\n-``handle_unknown='ignore'`` is specified and unknown categories are encountered\n-during transform, no error will be raised but the resulting one-hot encoded\n-columns for this feature will be all zeros\n-(``handle_unknown='ignore'`` is only supported for one-hot encoding)::\n-\n- >>> enc = preprocessing.OneHotEncoder(handle_unknown='ignore')\n+features, it can often be better to specify\n+`handle_unknown='infrequent_if_exist'` instead of setting the `categories`\n+manually as above. When `handle_unknown='infrequent_if_exist'` is specified\n+and unknown categories are encountered during transform, no error will be\n+raised but the resulting one-hot encoded columns for this feature will be all\n+zeros or considered as an infrequent category if enabled.\n+(`handle_unknown='infrequent_if_exist'` is only supported for one-hot\n+encoding)::\n+\n+ >>> enc = preprocessing.OneHotEncoder(handle_unknown='infrequent_if_exist')\n >>> X = [['male', 'from US', 'uses Safari'], ['female', 'from Europe', 'uses Firefox']]\n >>> enc.fit(X)\n- OneHotEncoder(handle_unknown='ignore')\n+ OneHotEncoder(handle_unknown='infrequent_if_exist')\n >>> enc.transform([['female', 'from Asia', 'uses Chrome']]).toarray()\n array([[1., 0., 0., 0., 0., 0.]])\n \n@@ -621,7 +623,8 @@ since co-linearity would cause the covariance matrix to be non-invertible::\n ... ['female', 'from Europe', 'uses Firefox']]\n >>> drop_enc = preprocessing.OneHotEncoder(drop='first').fit(X)\n >>> drop_enc.categories_\n- [array(['female', 'male'], dtype=object), array(['from Europe', 'from US'], dtype=object), array(['uses Firefox', 'uses Safari'], dtype=object)]\n+ [array(['female', 'male'], dtype=object), array(['from Europe', 'from US'], dtype=object),\n+ array(['uses Firefox', 'uses Safari'], dtype=object)]\n >>> drop_enc.transform(X).toarray()\n array([[1., 1., 1.],\n [0., 0., 0.]])\n@@ -634,7 +637,8 @@ categories. In this case, you can set the parameter `drop='if_binary'`.\n ... ['female', 'Asia', 'Chrome']]\n >>> drop_enc = preprocessing.OneHotEncoder(drop='if_binary').fit(X)\n >>> drop_enc.categories_\n- [array(['female', 'male'], dtype=object), array(['Asia', 'Europe', 'US'], dtype=object), array(['Chrome', 'Firefox', 'Safari'], dtype=object)]\n+ [array(['female', 'male'], dtype=object), array(['Asia', 'Europe', 'US'], dtype=object),\n+ array(['Chrome', 'Firefox', 'Safari'], dtype=object)]\n >>> drop_enc.transform(X).toarray()\n array([[1., 0., 0., 1., 0., 0., 1.],\n [0., 0., 1., 0., 0., 1., 0.],\n@@ -699,6 +703,107 @@ separate categories::\n See :ref:`dict_feature_extraction` for categorical features that are\n represented as a dict, not as scalars.\n \n+.. _one_hot_encoder_infrequent_categories:\n+\n+Infrequent categories\n+---------------------\n+\n+:class:`OneHotEncoder` supports aggregating infrequent categories into a single\n+output for each feature. The parameters to enable the gathering of infrequent\n+categories are `min_frequency` and `max_categories`.\n+\n+1. `min_frequency` is either an integer greater or equal to 1, or a float in\n+ the interval `(0.0, 1.0)`. If `min_frequency` is an integer, categories with\n+ a cardinality smaller than `min_frequency` will be considered infrequent.\n+ If `min_frequency` is a float, categories with a cardinality smaller than\n+ this fraction of the total number of samples will be considered infrequent.\n+ The default value is 1, which means every category is encoded separately.\n+\n+2. `max_categories` is either `None` or any integer greater than 1. This\n+ parameter sets an upper limit to the number of output features for each\n+ input feature. `max_categories` includes the feature that combines\n+ infrequent categories.\n+\n+In the following example, the categories, `'dog', 'snake'` are considered\n+infrequent::\n+\n+ >>> X = np.array([['dog'] * 5 + ['cat'] * 20 + ['rabbit'] * 10 +\n+ ... ['snake'] * 3], dtype=object).T\n+ >>> enc = preprocessing.OneHotEncoder(min_frequency=6, sparse=False).fit(X)\n+ >>> enc.infrequent_categories_\n+ [array(['dog', 'snake'], dtype=object)]\n+ >>> enc.transform(np.array([['dog'], ['cat'], ['rabbit'], ['snake']]))\n+ array([[0., 0., 1.],\n+ [1., 0., 0.],\n+ [0., 1., 0.],\n+ [0., 0., 1.]])\n+\n+By setting handle_unknown to `'infrequent_if_exist'`, unknown categories will\n+be considered infrequent::\n+\n+ >>> enc = preprocessing.OneHotEncoder(\n+ ... handle_unknown='infrequent_if_exist', sparse=False, min_frequency=6)\n+ >>> enc = enc.fit(X)\n+ >>> enc.transform(np.array([['dragon']]))\n+ array([[0., 0., 1.]])\n+\n+:meth:`OneHotEncoder.get_feature_names_out` uses 'infrequent' as the infrequent\n+feature name::\n+\n+ >>> enc.get_feature_names_out()\n+ array(['x0_cat', 'x0_rabbit', 'x0_infrequent_sklearn'], dtype=object)\n+\n+When `'handle_unknown'` is set to `'infrequent_if_exist'` and an unknown\n+category is encountered in transform:\n+\n+1. If infrequent category support was not configured or there was no\n+ infrequent category during training, the resulting one-hot encoded columns\n+ for this feature will be all zeros. In the inverse transform, an unknown\n+ category will be denoted as `None`.\n+\n+2. If there is an infrequent category during training, the unknown category\n+ will be considered infrequent. In the inverse transform, 'infrequent_sklearn'\n+ will be used to represent the infrequent category.\n+\n+Infrequent categories can also be configured using `max_categories`. In the\n+following example, we set `max_categories=2` to limit the number of features in\n+the output. This will result in all but the `'cat'` category to be considered\n+infrequent, leading to two features, one for `'cat'` and one for infrequent\n+categories - which are all the others::\n+\n+ >>> enc = preprocessing.OneHotEncoder(max_categories=2, sparse=False)\n+ >>> enc = enc.fit(X)\n+ >>> enc.transform([['dog'], ['cat'], ['rabbit'], ['snake']])\n+ array([[0., 1.],\n+ [1., 0.],\n+ [0., 1.],\n+ [0., 1.]])\n+\n+If both `max_categories` and `min_frequency` are non-default values, then\n+categories are selected based on `min_frequency` first and `max_categories`\n+categories are kept. In the following example, `min_frequency=4` considers\n+only `snake` to be infrequent, but `max_categories=3`, forces `dog` to also be\n+infrequent::\n+\n+ >>> enc = preprocessing.OneHotEncoder(min_frequency=4, max_categories=3, sparse=False)\n+ >>> enc = enc.fit(X)\n+ >>> enc.transform([['dog'], ['cat'], ['rabbit'], ['snake']])\n+ array([[0., 0., 1.],\n+ [1., 0., 0.],\n+ [0., 1., 0.],\n+ [0., 0., 1.]])\n+\n+If there are infrequent categories with the same cardinality at the cutoff of\n+`max_categories`, then then the first `max_categories` are taken based on lexicon\n+ordering. In the following example, \"b\", \"c\", and \"d\", have the same cardinality\n+and with `max_categories=2`, \"b\" and \"c\" are infrequent because they have a higher\n+lexicon order.\n+\n+ >>> X = np.asarray([[\"a\"] * 20 + [\"b\"] * 10 + [\"c\"] * 10 + [\"d\"] * 10], dtype=object).T\n+ >>> enc = preprocessing.OneHotEncoder(max_categories=3).fit(X)\n+ >>> enc.infrequent_categories_\n+ [array(['b', 'c'], dtype=object)]\n+\n .. _preprocessing_discretization:\n \n Discretization\n@@ -981,7 +1086,7 @@ Interestingly, a :class:`SplineTransformer` of ``degree=0`` is the same as\n Penalties <10.1214/ss/1038425655>`. Statist. Sci. 11 (1996), no. 2, 89--121.\n \n * Perperoglou, A., Sauerbrei, W., Abrahamowicz, M. et al. :doi:`A review of\n- spline function procedures in R <10.1186/s12874-019-0666-3>`. \n+ spline function procedures in R <10.1186/s12874-019-0666-3>`.\n BMC Med Res Methodol 19, 46 (2019).\n \n .. _function_transformer:\n" }, { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 584dd796b5789..a0272f183bf81 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -688,6 +688,11 @@ Changelog\n :mod:`sklearn.preprocessing`\n ............................\n \n+- |Feature| :class:`preprocessing.OneHotEncoder` now supports grouping\n+ infrequent categories into a single feature. Grouping infrequent categories\n+ is enabled by specifying how to select infrequent categories with\n+ `min_frequency` or `max_categories`. :pr:`<PRID>` by `<NAME>`_.\n+\n - |Enhancement| Adds a `subsample` parameter to :class:`preprocessing.KBinsDiscretizer`.\n This allows specifying a maximum number of samples to be used while fitting\n the model. The option is only available when `strategy` is set to `quantile`.\n" } ]
diff --git a/doc/modules/preprocessing.rst b/doc/modules/preprocessing.rst index 035f2b90203ca..997bccf66782d 100644 --- a/doc/modules/preprocessing.rst +++ b/doc/modules/preprocessing.rst @@ -594,17 +594,19 @@ dataset:: array([[1., 0., 0., 1., 0., 0., 1., 0., 0., 0.]]) If there is a possibility that the training data might have missing categorical -features, it can often be better to specify ``handle_unknown='ignore'`` instead -of setting the ``categories`` manually as above. When -``handle_unknown='ignore'`` is specified and unknown categories are encountered -during transform, no error will be raised but the resulting one-hot encoded -columns for this feature will be all zeros -(``handle_unknown='ignore'`` is only supported for one-hot encoding):: - - >>> enc = preprocessing.OneHotEncoder(handle_unknown='ignore') +features, it can often be better to specify +`handle_unknown='infrequent_if_exist'` instead of setting the `categories` +manually as above. When `handle_unknown='infrequent_if_exist'` is specified +and unknown categories are encountered during transform, no error will be +raised but the resulting one-hot encoded columns for this feature will be all +zeros or considered as an infrequent category if enabled. +(`handle_unknown='infrequent_if_exist'` is only supported for one-hot +encoding):: + + >>> enc = preprocessing.OneHotEncoder(handle_unknown='infrequent_if_exist') >>> X = [['male', 'from US', 'uses Safari'], ['female', 'from Europe', 'uses Firefox']] >>> enc.fit(X) - OneHotEncoder(handle_unknown='ignore') + OneHotEncoder(handle_unknown='infrequent_if_exist') >>> enc.transform([['female', 'from Asia', 'uses Chrome']]).toarray() array([[1., 0., 0., 0., 0., 0.]]) @@ -621,7 +623,8 @@ since co-linearity would cause the covariance matrix to be non-invertible:: ... ['female', 'from Europe', 'uses Firefox']] >>> drop_enc = preprocessing.OneHotEncoder(drop='first').fit(X) >>> drop_enc.categories_ - [array(['female', 'male'], dtype=object), array(['from Europe', 'from US'], dtype=object), array(['uses Firefox', 'uses Safari'], dtype=object)] + [array(['female', 'male'], dtype=object), array(['from Europe', 'from US'], dtype=object), + array(['uses Firefox', 'uses Safari'], dtype=object)] >>> drop_enc.transform(X).toarray() array([[1., 1., 1.], [0., 0., 0.]]) @@ -634,7 +637,8 @@ categories. In this case, you can set the parameter `drop='if_binary'`. ... ['female', 'Asia', 'Chrome']] >>> drop_enc = preprocessing.OneHotEncoder(drop='if_binary').fit(X) >>> drop_enc.categories_ - [array(['female', 'male'], dtype=object), array(['Asia', 'Europe', 'US'], dtype=object), array(['Chrome', 'Firefox', 'Safari'], dtype=object)] + [array(['female', 'male'], dtype=object), array(['Asia', 'Europe', 'US'], dtype=object), + array(['Chrome', 'Firefox', 'Safari'], dtype=object)] >>> drop_enc.transform(X).toarray() array([[1., 0., 0., 1., 0., 0., 1.], [0., 0., 1., 0., 0., 1., 0.], @@ -699,6 +703,107 @@ separate categories:: See :ref:`dict_feature_extraction` for categorical features that are represented as a dict, not as scalars. +.. _one_hot_encoder_infrequent_categories: + +Infrequent categories +--------------------- + +:class:`OneHotEncoder` supports aggregating infrequent categories into a single +output for each feature. The parameters to enable the gathering of infrequent +categories are `min_frequency` and `max_categories`. + +1. `min_frequency` is either an integer greater or equal to 1, or a float in + the interval `(0.0, 1.0)`. If `min_frequency` is an integer, categories with + a cardinality smaller than `min_frequency` will be considered infrequent. + If `min_frequency` is a float, categories with a cardinality smaller than + this fraction of the total number of samples will be considered infrequent. + The default value is 1, which means every category is encoded separately. + +2. `max_categories` is either `None` or any integer greater than 1. This + parameter sets an upper limit to the number of output features for each + input feature. `max_categories` includes the feature that combines + infrequent categories. + +In the following example, the categories, `'dog', 'snake'` are considered +infrequent:: + + >>> X = np.array([['dog'] * 5 + ['cat'] * 20 + ['rabbit'] * 10 + + ... ['snake'] * 3], dtype=object).T + >>> enc = preprocessing.OneHotEncoder(min_frequency=6, sparse=False).fit(X) + >>> enc.infrequent_categories_ + [array(['dog', 'snake'], dtype=object)] + >>> enc.transform(np.array([['dog'], ['cat'], ['rabbit'], ['snake']])) + array([[0., 0., 1.], + [1., 0., 0.], + [0., 1., 0.], + [0., 0., 1.]]) + +By setting handle_unknown to `'infrequent_if_exist'`, unknown categories will +be considered infrequent:: + + >>> enc = preprocessing.OneHotEncoder( + ... handle_unknown='infrequent_if_exist', sparse=False, min_frequency=6) + >>> enc = enc.fit(X) + >>> enc.transform(np.array([['dragon']])) + array([[0., 0., 1.]]) + +:meth:`OneHotEncoder.get_feature_names_out` uses 'infrequent' as the infrequent +feature name:: + + >>> enc.get_feature_names_out() + array(['x0_cat', 'x0_rabbit', 'x0_infrequent_sklearn'], dtype=object) + +When `'handle_unknown'` is set to `'infrequent_if_exist'` and an unknown +category is encountered in transform: + +1. If infrequent category support was not configured or there was no + infrequent category during training, the resulting one-hot encoded columns + for this feature will be all zeros. In the inverse transform, an unknown + category will be denoted as `None`. + +2. If there is an infrequent category during training, the unknown category + will be considered infrequent. In the inverse transform, 'infrequent_sklearn' + will be used to represent the infrequent category. + +Infrequent categories can also be configured using `max_categories`. In the +following example, we set `max_categories=2` to limit the number of features in +the output. This will result in all but the `'cat'` category to be considered +infrequent, leading to two features, one for `'cat'` and one for infrequent +categories - which are all the others:: + + >>> enc = preprocessing.OneHotEncoder(max_categories=2, sparse=False) + >>> enc = enc.fit(X) + >>> enc.transform([['dog'], ['cat'], ['rabbit'], ['snake']]) + array([[0., 1.], + [1., 0.], + [0., 1.], + [0., 1.]]) + +If both `max_categories` and `min_frequency` are non-default values, then +categories are selected based on `min_frequency` first and `max_categories` +categories are kept. In the following example, `min_frequency=4` considers +only `snake` to be infrequent, but `max_categories=3`, forces `dog` to also be +infrequent:: + + >>> enc = preprocessing.OneHotEncoder(min_frequency=4, max_categories=3, sparse=False) + >>> enc = enc.fit(X) + >>> enc.transform([['dog'], ['cat'], ['rabbit'], ['snake']]) + array([[0., 0., 1.], + [1., 0., 0.], + [0., 1., 0.], + [0., 0., 1.]]) + +If there are infrequent categories with the same cardinality at the cutoff of +`max_categories`, then then the first `max_categories` are taken based on lexicon +ordering. In the following example, "b", "c", and "d", have the same cardinality +and with `max_categories=2`, "b" and "c" are infrequent because they have a higher +lexicon order. + + >>> X = np.asarray([["a"] * 20 + ["b"] * 10 + ["c"] * 10 + ["d"] * 10], dtype=object).T + >>> enc = preprocessing.OneHotEncoder(max_categories=3).fit(X) + >>> enc.infrequent_categories_ + [array(['b', 'c'], dtype=object)] + .. _preprocessing_discretization: Discretization @@ -981,7 +1086,7 @@ Interestingly, a :class:`SplineTransformer` of ``degree=0`` is the same as Penalties <10.1214/ss/1038425655>`. Statist. Sci. 11 (1996), no. 2, 89--121. * Perperoglou, A., Sauerbrei, W., Abrahamowicz, M. et al. :doi:`A review of - spline function procedures in R <10.1186/s12874-019-0666-3>`. + spline function procedures in R <10.1186/s12874-019-0666-3>`. BMC Med Res Methodol 19, 46 (2019). .. _function_transformer: diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 584dd796b5789..a0272f183bf81 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -688,6 +688,11 @@ Changelog :mod:`sklearn.preprocessing` ............................ +- |Feature| :class:`preprocessing.OneHotEncoder` now supports grouping + infrequent categories into a single feature. Grouping infrequent categories + is enabled by specifying how to select infrequent categories with + `min_frequency` or `max_categories`. :pr:`<PRID>` by `<NAME>`_. + - |Enhancement| Adds a `subsample` parameter to :class:`preprocessing.KBinsDiscretizer`. This allows specifying a maximum number of samples to be used while fitting the model. The option is only available when `strategy` is set to `quantile`.
scikit-learn/scikit-learn
scikit-learn__scikit-learn-22150
https://github.com/scikit-learn/scikit-learn/pull/22150
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 61d5c64255f71..a30d6711812a3 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -393,6 +393,14 @@ Changelog instead of `__init__`. :pr:`21430` by :user:`Desislava Vasileva <DessyVV>` and :user:`Lucy Jimenez <LucyJimenez>`. +:mod:`sklearn.neural_network` +............................. + +- |Enhancement| :func:`neural_network.MLPClassifier` and + :func:`neural_network.MLPRegressor` show error + messages when optimizers produce non-finite parameter weights. :pr:`22150` + by :user:`Christian Ritter <chritter>` and :user:`Norbert Preining <norbusan>`. + :mod:`sklearn.pipeline` ....................... diff --git a/sklearn/neural_network/_multilayer_perceptron.py b/sklearn/neural_network/_multilayer_perceptron.py index 8c4dcdafbec83..8b60d86105cf3 100644 --- a/sklearn/neural_network/_multilayer_perceptron.py +++ b/sklearn/neural_network/_multilayer_perceptron.py @@ -10,6 +10,7 @@ from abc import ABCMeta, abstractmethod import warnings +from itertools import chain import scipy.optimize @@ -440,6 +441,15 @@ def _fit(self, X, y, incremental=False): self._fit_lbfgs( X, y, activations, deltas, coef_grads, intercept_grads, layer_units ) + + # validate parameter weights + weights = chain(self.coefs_, self.intercepts_) + if not all(np.isfinite(w).all() for w in weights): + raise ValueError( + "Solver produced non-finite parameter weights. The input data may" + " contain large values and need to be preprocessed." + ) + return self def _validate_hyperparameters(self):
diff --git a/sklearn/neural_network/tests/test_mlp.py b/sklearn/neural_network/tests/test_mlp.py index 3948a4eccc760..999983d751cc1 100644 --- a/sklearn/neural_network/tests/test_mlp.py +++ b/sklearn/neural_network/tests/test_mlp.py @@ -506,6 +506,24 @@ def test_partial_fit_errors(): assert not hasattr(MLPClassifier(solver="lbfgs"), "partial_fit") +def test_nonfinite_params(): + # Check that MLPRegressor throws ValueError when dealing with non-finite + # parameter values + rng = np.random.RandomState(0) + n_samples = 10 + fmax = np.finfo(np.float64).max + X = fmax * rng.uniform(size=(n_samples, 2)) + y = rng.standard_normal(size=n_samples) + + clf = MLPRegressor() + msg = ( + "Solver produced non-finite parameter weights. The input data may contain large" + " values and need to be preprocessed." + ) + with pytest.raises(ValueError, match=msg): + clf.fit(X, y) + + @pytest.mark.parametrize( "args", [
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 61d5c64255f71..a30d6711812a3 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -393,6 +393,14 @@ Changelog\n instead of `__init__`. :pr:`21430` by :user:`Desislava Vasileva <DessyVV>` and\n :user:`Lucy Jimenez <LucyJimenez>`.\n \n+:mod:`sklearn.neural_network`\n+.............................\n+\n+- |Enhancement| :func:`neural_network.MLPClassifier` and \n+ :func:`neural_network.MLPRegressor` show error\n+ messages when optimizers produce non-finite parameter weights. :pr:`22150`\n+ by :user:`Christian Ritter <chritter>` and :user:`Norbert Preining <norbusan>`.\n+\n :mod:`sklearn.pipeline`\n .......................\n \n" } ]
1.01
8d6217107f02d6f52d2f8c8908958fe82778c7cc
[ "sklearn/neural_network/tests/test_mlp.py::test_params_errors[args11]", "sklearn/neural_network/tests/test_mlp.py::test_params_errors[args7]", "sklearn/neural_network/tests/test_mlp.py::test_params_errors[args17]", "sklearn/neural_network/tests/test_mlp.py::test_mlp_regressor_dtypes_casting", "sklearn/neural_network/tests/test_mlp.py::test_mlp_param_dtypes[MLPClassifier-float64]", "sklearn/neural_network/tests/test_mlp.py::test_n_iter_no_change", "sklearn/neural_network/tests/test_mlp.py::test_early_stopping", "sklearn/neural_network/tests/test_mlp.py::test_n_iter_no_change_inf", "sklearn/neural_network/tests/test_mlp.py::test_tolerance", "sklearn/neural_network/tests/test_mlp.py::test_multilabel_classification", "sklearn/neural_network/tests/test_mlp.py::test_params_errors[args10]", "sklearn/neural_network/tests/test_mlp.py::test_warm_start_full_iteration[MLPClassifier]", "sklearn/neural_network/tests/test_mlp.py::test_params_errors[args0]", "sklearn/neural_network/tests/test_mlp.py::test_mlp_classifier_dtypes_casting", "sklearn/neural_network/tests/test_mlp.py::test_fit", "sklearn/neural_network/tests/test_mlp.py::test_lbfgs_classification[X0-y0]", "sklearn/neural_network/tests/test_mlp.py::test_predict_proba_binary", "sklearn/neural_network/tests/test_mlp.py::test_shuffle", "sklearn/neural_network/tests/test_mlp.py::test_params_errors[args1]", "sklearn/neural_network/tests/test_mlp.py::test_verbose_sgd", "sklearn/neural_network/tests/test_mlp.py::test_lbfgs_regression_maxfun[X0-y0]", "sklearn/neural_network/tests/test_mlp.py::test_params_errors[args16]", "sklearn/neural_network/tests/test_mlp.py::test_predict_proba_multilabel", "sklearn/neural_network/tests/test_mlp.py::test_partial_fit_unseen_classes", "sklearn/neural_network/tests/test_mlp.py::test_params_errors[args4]", "sklearn/neural_network/tests/test_mlp.py::test_partial_fit_regression", "sklearn/neural_network/tests/test_mlp.py::test_lbfgs_classification[X1-y1]", "sklearn/neural_network/tests/test_mlp.py::test_partial_fit_classification", "sklearn/neural_network/tests/test_mlp.py::test_params_errors[args9]", "sklearn/neural_network/tests/test_mlp.py::test_params_errors[args3]", "sklearn/neural_network/tests/test_mlp.py::test_params_errors[args14]", "sklearn/neural_network/tests/test_mlp.py::test_params_errors[args19]", "sklearn/neural_network/tests/test_mlp.py::test_mlp_loading_from_joblib_partial_fit", "sklearn/neural_network/tests/test_mlp.py::test_params_errors[args12]", "sklearn/neural_network/tests/test_mlp.py::test_lbfgs_classification_maxfun[X0-y0]", "sklearn/neural_network/tests/test_mlp.py::test_predict_proba_multiclass", "sklearn/neural_network/tests/test_mlp.py::test_lbfgs_regression[X0-y0]", "sklearn/neural_network/tests/test_mlp.py::test_mlp_param_dtypes[MLPClassifier-float32]", "sklearn/neural_network/tests/test_mlp.py::test_warm_start", "sklearn/neural_network/tests/test_mlp.py::test_sparse_matrices", "sklearn/neural_network/tests/test_mlp.py::test_params_errors[args8]", "sklearn/neural_network/tests/test_mlp.py::test_params_errors[args13]", "sklearn/neural_network/tests/test_mlp.py::test_partial_fit_errors", "sklearn/neural_network/tests/test_mlp.py::test_params_errors[args5]", "sklearn/neural_network/tests/test_mlp.py::test_alpha", "sklearn/neural_network/tests/test_mlp.py::test_warm_start_full_iteration[MLPRegressor]", "sklearn/neural_network/tests/test_mlp.py::test_partial_fit_classes_error", "sklearn/neural_network/tests/test_mlp.py::test_params_errors[args18]", "sklearn/neural_network/tests/test_mlp.py::test_params_errors[args15]", "sklearn/neural_network/tests/test_mlp.py::test_early_stopping_stratified", "sklearn/neural_network/tests/test_mlp.py::test_lbfgs_classification_maxfun[X1-y1]", "sklearn/neural_network/tests/test_mlp.py::test_multioutput_regression", "sklearn/neural_network/tests/test_mlp.py::test_adaptive_learning_rate", "sklearn/neural_network/tests/test_mlp.py::test_mlp_param_dtypes[MLPRegressor-float32]", "sklearn/neural_network/tests/test_mlp.py::test_learning_rate_warmstart", "sklearn/neural_network/tests/test_mlp.py::test_params_errors[args2]", "sklearn/neural_network/tests/test_mlp.py::test_mlp_param_dtypes[MLPRegressor-float64]", "sklearn/neural_network/tests/test_mlp.py::test_params_errors[args6]", "sklearn/neural_network/tests/test_mlp.py::test_gradient" ]
[ "sklearn/neural_network/tests/test_mlp.py::test_nonfinite_params" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 61d5c64255f71..a30d6711812a3 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -393,6 +393,14 @@ Changelog\n instead of `__init__`. :pr:`<PRID>` by :user:`<NAME>` and\n :user:`<NAME>`.\n \n+:mod:`sklearn.neural_network`\n+.............................\n+\n+- |Enhancement| :func:`neural_network.MLPClassifier` and \n+ :func:`neural_network.MLPRegressor` show error\n+ messages when optimizers produce non-finite parameter weights. :pr:`<PRID>`\n+ by :user:`<NAME>` and :user:`<NAME>`.\n+\n :mod:`sklearn.pipeline`\n .......................\n \n" } ]
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 61d5c64255f71..a30d6711812a3 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -393,6 +393,14 @@ Changelog instead of `__init__`. :pr:`<PRID>` by :user:`<NAME>` and :user:`<NAME>`. +:mod:`sklearn.neural_network` +............................. + +- |Enhancement| :func:`neural_network.MLPClassifier` and + :func:`neural_network.MLPRegressor` show error + messages when optimizers produce non-finite parameter weights. :pr:`<PRID>` + by :user:`<NAME>` and :user:`<NAME>`. + :mod:`sklearn.pipeline` .......................
scikit-learn/scikit-learn
scikit-learn__scikit-learn-21569
https://github.com/scikit-learn/scikit-learn/pull/21569
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 6a5b2d226cabe..5e67916888511 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -237,6 +237,15 @@ Changelog instead of `__init__`. :pr:`21434` by :user:`Krum Arnaudov <krumeto>`. +- |Enhancement| Added the `get_feature_names_out` method and a new parameter + `feature_names_out` to :class:`preprocessing.FunctionTransformer`. You can set + `feature_names_out` to 'one-to-one' to use the input features names as the + output feature names, or you can set it to a callable that returns the output + feature names. This is especially useful when the transformer changes the + number of features. If `feature_names_out` is None (which is the default), + then `get_output_feature_names` is not defined. + :pr:`21569` by :user:`Aurélien Geron <ageron>`. + :mod:`sklearn.svm` .................. diff --git a/sklearn/preprocessing/_function_transformer.py b/sklearn/preprocessing/_function_transformer.py index 595ca0e0bbc1b..cea720aeb6a67 100644 --- a/sklearn/preprocessing/_function_transformer.py +++ b/sklearn/preprocessing/_function_transformer.py @@ -1,7 +1,14 @@ import warnings +import numpy as np + from ..base import BaseEstimator, TransformerMixin -from ..utils.validation import _allclose_dense_sparse, check_array +from ..utils.metaestimators import available_if +from ..utils.validation import ( + _allclose_dense_sparse, + _check_feature_names_in, + check_array, +) def _identity(X): @@ -61,6 +68,20 @@ class FunctionTransformer(TransformerMixin, BaseEstimator): .. versionadded:: 0.20 + feature_names_out : callable, 'one-to-one' or None, default=None + Determines the list of feature names that will be returned by the + `get_feature_names_out` method. If it is 'one-to-one', then the output + feature names will be equal to the input feature names. If it is a + callable, then it must take two positional arguments: this + `FunctionTransformer` (`self`) and an array-like of input feature names + (`input_features`). It must return an array-like of output feature + names. The `get_feature_names_out` method is only defined if + `feature_names_out` is not None. + + See ``get_feature_names_out`` for more details. + + .. versionadded:: 1.1 + kw_args : dict, default=None Dictionary of additional keyword arguments to pass to func. @@ -113,6 +134,7 @@ def __init__( validate=False, accept_sparse=False, check_inverse=True, + feature_names_out=None, kw_args=None, inv_kw_args=None, ): @@ -121,6 +143,7 @@ def __init__( self.validate = validate self.accept_sparse = accept_sparse self.check_inverse = check_inverse + self.feature_names_out = feature_names_out self.kw_args = kw_args self.inv_kw_args = inv_kw_args @@ -198,6 +221,63 @@ def inverse_transform(self, X): X = check_array(X, accept_sparse=self.accept_sparse) return self._transform(X, func=self.inverse_func, kw_args=self.inv_kw_args) + @available_if(lambda self: self.feature_names_out is not None) + def get_feature_names_out(self, input_features=None): + """Get output feature names for transformation. + + This method is only defined if `feature_names_out` is not None. + + Parameters + ---------- + input_features : array-like of str or None, default=None + Input feature names. + + - If `input_features` is None, then `feature_names_in_` is + used as the input feature names. If `feature_names_in_` is not + defined, then names are generated: + `[x0, x1, ..., x(n_features_in_)]`. + - If `input_features` is array-like, then `input_features` must + match `feature_names_in_` if `feature_names_in_` is defined. + + Returns + ------- + feature_names_out : ndarray of str objects + Transformed feature names. + + - If `feature_names_out` is 'one-to-one', the input feature names + are returned (see `input_features` above). This requires + `feature_names_in_` and/or `n_features_in_` to be defined, which + is done automatically if `validate=True`. Alternatively, you can + set them in `func`. + - If `feature_names_out` is a callable, then it is called with two + arguments, `self` and `input_features`, and its return value is + returned by this method. + """ + if hasattr(self, "n_features_in_") or input_features is not None: + input_features = _check_feature_names_in(self, input_features) + if self.feature_names_out == "one-to-one": + if input_features is None: + raise ValueError( + "When 'feature_names_out' is 'one-to-one', either " + "'input_features' must be passed, or 'feature_names_in_' " + "and/or 'n_features_in_' must be defined. If you set " + "'validate' to 'True', then they will be defined " + "automatically when 'fit' is called. Alternatively, you " + "can set them in 'func'." + ) + names_out = input_features + elif callable(self.feature_names_out): + names_out = self.feature_names_out(self, input_features) + else: + raise ValueError( + f"feature_names_out={self.feature_names_out!r} is invalid. " + 'It must either be "one-to-one" or a callable with two ' + "arguments: the function transformer and an array-like of " + "input feature names. The callable must return an array-like " + "of output feature names." + ) + return np.asarray(names_out, dtype=object) + def _transform(self, X, func=None, kw_args=None): if func is None: func = _identity
diff --git a/sklearn/preprocessing/tests/test_function_transformer.py b/sklearn/preprocessing/tests/test_function_transformer.py index b1ba9ebe6b762..525accf4568de 100644 --- a/sklearn/preprocessing/tests/test_function_transformer.py +++ b/sklearn/preprocessing/tests/test_function_transformer.py @@ -176,6 +176,158 @@ def test_function_transformer_frame(): assert hasattr(X_df_trans, "loc") [email protected]( + "X, feature_names_out, input_features, expected", + [ + ( + # NumPy inputs, default behavior: generate names + np.random.rand(100, 3), + "one-to-one", + None, + ("x0", "x1", "x2"), + ), + ( + # Pandas input, default behavior: use input feature names + {"a": np.random.rand(100), "b": np.random.rand(100)}, + "one-to-one", + None, + ("a", "b"), + ), + ( + # NumPy input, feature_names_out=callable + np.random.rand(100, 3), + lambda transformer, input_features: ("a", "b"), + None, + ("a", "b"), + ), + ( + # Pandas input, feature_names_out=callable + {"a": np.random.rand(100), "b": np.random.rand(100)}, + lambda transformer, input_features: ("c", "d", "e"), + None, + ("c", "d", "e"), + ), + ( + # NumPy input, feature_names_out=callable – default input_features + np.random.rand(100, 3), + lambda transformer, input_features: tuple(input_features) + ("a",), + None, + ("x0", "x1", "x2", "a"), + ), + ( + # Pandas input, feature_names_out=callable – default input_features + {"a": np.random.rand(100), "b": np.random.rand(100)}, + lambda transformer, input_features: tuple(input_features) + ("c",), + None, + ("a", "b", "c"), + ), + ( + # NumPy input, input_features=list of names + np.random.rand(100, 3), + "one-to-one", + ("a", "b", "c"), + ("a", "b", "c"), + ), + ( + # Pandas input, input_features=list of names + {"a": np.random.rand(100), "b": np.random.rand(100)}, + "one-to-one", + ("a", "b"), # must match feature_names_in_ + ("a", "b"), + ), + ( + # NumPy input, feature_names_out=callable, input_features=list + np.random.rand(100, 3), + lambda transformer, input_features: tuple(input_features) + ("d",), + ("a", "b", "c"), + ("a", "b", "c", "d"), + ), + ( + # Pandas input, feature_names_out=callable, input_features=list + {"a": np.random.rand(100), "b": np.random.rand(100)}, + lambda transformer, input_features: tuple(input_features) + ("c",), + ("a", "b"), # must match feature_names_in_ + ("a", "b", "c"), + ), + ], +) +def test_function_transformer_get_feature_names_out( + X, feature_names_out, input_features, expected +): + if isinstance(X, dict): + pd = pytest.importorskip("pandas") + X = pd.DataFrame(X) + + transformer = FunctionTransformer( + feature_names_out=feature_names_out, validate=True + ) + transformer.fit_transform(X) + names = transformer.get_feature_names_out(input_features) + assert isinstance(names, np.ndarray) + assert names.dtype == object + assert_array_equal(names, expected) + + +def test_function_transformer_get_feature_names_out_without_validation(): + transformer = FunctionTransformer(feature_names_out="one-to-one", validate=False) + X = np.random.rand(100, 2) + transformer.fit_transform(X) + + msg = "When 'feature_names_out' is 'one-to-one', either" + with pytest.raises(ValueError, match=msg): + transformer.get_feature_names_out() + + names = transformer.get_feature_names_out(("a", "b")) + assert isinstance(names, np.ndarray) + assert names.dtype == object + assert_array_equal(names, ("a", "b")) + + [email protected]("feature_names_out", ["x0", ["x0"], ("x0",)]) +def test_function_transformer_feature_names_out_string(feature_names_out): + transformer = FunctionTransformer(feature_names_out=feature_names_out) + X = np.random.rand(100, 2) + transformer.fit_transform(X) + + msg = """must either be "one-to-one" or a callable""" + with pytest.raises(ValueError, match=msg): + transformer.get_feature_names_out() + + +def test_function_transformer_feature_names_out_is_None(): + transformer = FunctionTransformer() + X = np.random.rand(100, 2) + transformer.fit_transform(X) + + msg = "This 'FunctionTransformer' has no attribute 'get_feature_names_out'" + with pytest.raises(AttributeError, match=msg): + transformer.get_feature_names_out() + + +def test_function_transformer_feature_names_out_uses_estimator(): + def add_n_random_features(X, n): + return np.concatenate([X, np.random.rand(len(X), n)], axis=1) + + def feature_names_out(transformer, input_features): + n = transformer.kw_args["n"] + return list(input_features) + [f"rnd{i}" for i in range(n)] + + transformer = FunctionTransformer( + func=add_n_random_features, + feature_names_out=feature_names_out, + kw_args=dict(n=3), + validate=True, + ) + pd = pytest.importorskip("pandas") + df = pd.DataFrame({"a": np.random.rand(100), "b": np.random.rand(100)}) + transformer.fit_transform(df) + names = transformer.get_feature_names_out() + + assert isinstance(names, np.ndarray) + assert names.dtype == object + assert_array_equal(names, ("a", "b", "rnd0", "rnd1", "rnd2")) + + def test_function_transformer_validate_inverse(): """Test that function transformer does not reset estimator in `inverse_transform`."""
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 6a5b2d226cabe..5e67916888511 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -237,6 +237,15 @@ Changelog\n instead of `__init__`.\n :pr:`21434` by :user:`Krum Arnaudov <krumeto>`.\n \n+- |Enhancement| Added the `get_feature_names_out` method and a new parameter\n+ `feature_names_out` to :class:`preprocessing.FunctionTransformer`. You can set\n+ `feature_names_out` to 'one-to-one' to use the input features names as the\n+ output feature names, or you can set it to a callable that returns the output\n+ feature names. This is especially useful when the transformer changes the\n+ number of features. If `feature_names_out` is None (which is the default),\n+ then `get_output_feature_names` is not defined.\n+ :pr:`21569` by :user:`Aurélien Geron <ageron>`.\n+\n :mod:`sklearn.svm`\n ..................\n \n" } ]
1.01
bacc91cf1d4531bcc91aa60893fdf7df319485ec
[ "sklearn/preprocessing/tests/test_function_transformer.py::test_kw_arg_reset", "sklearn/preprocessing/tests/test_function_transformer.py::test_kw_arg", "sklearn/preprocessing/tests/test_function_transformer.py::test_function_transformer_frame", "sklearn/preprocessing/tests/test_function_transformer.py::test_delegate_to_func", "sklearn/preprocessing/tests/test_function_transformer.py::test_kw_arg_update", "sklearn/preprocessing/tests/test_function_transformer.py::test_function_transformer_validate_inverse", "sklearn/preprocessing/tests/test_function_transformer.py::test_np_log", "sklearn/preprocessing/tests/test_function_transformer.py::test_inverse_transform" ]
[ "sklearn/preprocessing/tests/test_function_transformer.py::test_function_transformer_get_feature_names_out[X6-one-to-one-input_features6-expected6]", "sklearn/preprocessing/tests/test_function_transformer.py::test_function_transformer_get_feature_names_out[X5-<lambda>-None-expected5]", "sklearn/preprocessing/tests/test_function_transformer.py::test_function_transformer_get_feature_names_out[X1-one-to-one-None-expected1]", "sklearn/preprocessing/tests/test_function_transformer.py::test_function_transformer_get_feature_names_out[X8-<lambda>-input_features8-expected8]", "sklearn/preprocessing/tests/test_function_transformer.py::test_function_transformer_get_feature_names_out[X0-one-to-one-None-expected0]", "sklearn/preprocessing/tests/test_function_transformer.py::test_function_transformer_get_feature_names_out[X2-<lambda>-None-expected2]", "sklearn/preprocessing/tests/test_function_transformer.py::test_function_transformer_get_feature_names_out[X3-<lambda>-None-expected3]", "sklearn/preprocessing/tests/test_function_transformer.py::test_function_transformer_get_feature_names_out[X7-one-to-one-input_features7-expected7]", "sklearn/preprocessing/tests/test_function_transformer.py::test_function_transformer_feature_names_out_string[x0]", "sklearn/preprocessing/tests/test_function_transformer.py::test_function_transformer_feature_names_out_is_None", "sklearn/preprocessing/tests/test_function_transformer.py::test_function_transformer_feature_names_out_string[feature_names_out1]", "sklearn/preprocessing/tests/test_function_transformer.py::test_function_transformer_feature_names_out_uses_estimator", "sklearn/preprocessing/tests/test_function_transformer.py::test_function_transformer_feature_names_out_string[feature_names_out2]", "sklearn/preprocessing/tests/test_function_transformer.py::test_function_transformer_get_feature_names_out_without_validation", "sklearn/preprocessing/tests/test_function_transformer.py::test_function_transformer_get_feature_names_out[X4-<lambda>-None-expected4]", "sklearn/preprocessing/tests/test_function_transformer.py::test_function_transformer_get_feature_names_out[X9-<lambda>-input_features9-expected9]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 6a5b2d226cabe..5e67916888511 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -237,6 +237,15 @@ Changelog\n instead of `__init__`.\n :pr:`<PRID>` by :user:`<NAME>`.\n \n+- |Enhancement| Added the `get_feature_names_out` method and a new parameter\n+ `feature_names_out` to :class:`preprocessing.FunctionTransformer`. You can set\n+ `feature_names_out` to 'one-to-one' to use the input features names as the\n+ output feature names, or you can set it to a callable that returns the output\n+ feature names. This is especially useful when the transformer changes the\n+ number of features. If `feature_names_out` is None (which is the default),\n+ then `get_output_feature_names` is not defined.\n+ :pr:`<PRID>` by :user:`<NAME>`.\n+\n :mod:`sklearn.svm`\n ..................\n \n" } ]
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 6a5b2d226cabe..5e67916888511 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -237,6 +237,15 @@ Changelog instead of `__init__`. :pr:`<PRID>` by :user:`<NAME>`. +- |Enhancement| Added the `get_feature_names_out` method and a new parameter + `feature_names_out` to :class:`preprocessing.FunctionTransformer`. You can set + `feature_names_out` to 'one-to-one' to use the input features names as the + output feature names, or you can set it to a callable that returns the output + feature names. This is especially useful when the transformer changes the + number of features. If `feature_names_out` is None (which is the default), + then `get_output_feature_names` is not defined. + :pr:`<PRID>` by :user:`<NAME>`. + :mod:`sklearn.svm` ..................
scikit-learn/scikit-learn
scikit-learn__scikit-learn-21988
https://github.com/scikit-learn/scikit-learn/pull/21988
diff --git a/doc/modules/preprocessing.rst b/doc/modules/preprocessing.rst index 997bccf66782d..beb91d8780de8 100644 --- a/doc/modules/preprocessing.rst +++ b/doc/modules/preprocessing.rst @@ -537,8 +537,8 @@ scikit-learn estimators, as these expect continuous input, and would interpret the categories as being ordered, which is often not desired (i.e. the set of browsers was ordered arbitrarily). -:class:`OrdinalEncoder` will also passthrough missing values that are -indicated by `np.nan`. +By default, :class:`OrdinalEncoder` will also passthrough missing values that +are indicated by `np.nan`. >>> enc = preprocessing.OrdinalEncoder() >>> X = [['male'], ['female'], [np.nan], ['female']] @@ -548,6 +548,32 @@ indicated by `np.nan`. [nan], [ 0.]]) +:class:`OrdinalEncoder` provides a parameter `encoded_missing_value` to encode +the missing values without the need to create a pipeline and using +:class:`~sklearn.impute.SimpleImputer`. + + >>> enc = preprocessing.OrdinalEncoder(encoded_missing_value=-1) + >>> X = [['male'], ['female'], [np.nan], ['female']] + >>> enc.fit_transform(X) + array([[ 1.], + [ 0.], + [-1.], + [ 0.]]) + +The above processing is equivalent to the following pipeline:: + + >>> from sklearn.pipeline import Pipeline + >>> from sklearn.impute import SimpleImputer + >>> enc = Pipeline(steps=[ + ... ("encoder", preprocessing.OrdinalEncoder()), + ... ("imputer", SimpleImputer(strategy="constant", fill_value=-1)), + ... ]) + >>> enc.fit_transform(X) + array([[ 1.], + [ 0.], + [-1.], + [ 0.]]) + Another possibility to convert categorical features to features that can be used with scikit-learn estimators is to use a one-of-K, also known as one-hot or dummy encoding. diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index b62ad01cdacc4..b432673704d71 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -803,6 +803,9 @@ Changelog the model. The option is only available when `strategy` is set to `quantile`. :pr:`21445` by :user:`Felipe Bidu <fbidu>` and :user:`Amanda Dsouza <amy12xx>`. +- |Enhancement| Adds `encoded_missing_value` to :class:`preprocessing.OrdinalEncoder` + to configure the encoded value for missing data. :pr:`21988` by `Thomas Fan`_. + - |Enhancement| Added the `get_feature_names_out` method and a new parameter `feature_names_out` to :class:`preprocessing.FunctionTransformer`. You can set `feature_names_out` to 'one-to-one' to use the input features names as the diff --git a/sklearn/preprocessing/_encoders.py b/sklearn/preprocessing/_encoders.py index ada054811f41c..d4cc642a18562 100644 --- a/sklearn/preprocessing/_encoders.py +++ b/sklearn/preprocessing/_encoders.py @@ -1160,6 +1160,12 @@ class OrdinalEncoder(_OneToOneFeatureMixin, _BaseEncoder): .. versionadded:: 0.24 + encoded_missing_value : int or np.nan, default=np.nan + Encoded value of missing categories. If set to `np.nan`, then the `dtype` + parameter must be a float dtype. + + .. versionadded:: 1.1 + Attributes ---------- categories_ : list of arrays @@ -1203,6 +1209,23 @@ class OrdinalEncoder(_OneToOneFeatureMixin, _BaseEncoder): >>> enc.inverse_transform([[1, 0], [0, 1]]) array([['Male', 1], ['Female', 2]], dtype=object) + + By default, :class:`OrdinalEncoder` is lenient towards missing values by + propagating them. + + >>> import numpy as np + >>> X = [['Male', 1], ['Female', 3], ['Female', np.nan]] + >>> enc.fit_transform(X) + array([[ 1., 0.], + [ 0., 1.], + [ 0., nan]]) + + You can use the parameter `encoded_missing_value` to encode missing values. + + >>> enc.set_params(encoded_missing_value=-1).fit_transform(X) + array([[ 1., 0.], + [ 0., 1.], + [ 0., -1.]]) """ def __init__( @@ -1212,11 +1235,13 @@ def __init__( dtype=np.float64, handle_unknown="error", unknown_value=None, + encoded_missing_value=np.nan, ): self.categories = categories self.dtype = dtype self.handle_unknown = handle_unknown self.unknown_value = unknown_value + self.encoded_missing_value = encoded_missing_value def fit(self, X, y=None): """ @@ -1286,13 +1311,38 @@ def fit(self, X, y=None): self._missing_indices[cat_idx] = i continue - if np.dtype(self.dtype).kind != "f" and self._missing_indices: - raise ValueError( - "There are missing values in features " - f"{list(self._missing_indices)}. For OrdinalEncoder to " - "passthrough missing values, the dtype parameter must be a " - "float" - ) + if self._missing_indices: + if np.dtype(self.dtype).kind != "f" and is_scalar_nan( + self.encoded_missing_value + ): + raise ValueError( + "There are missing values in features " + f"{list(self._missing_indices)}. For OrdinalEncoder to " + f"encode missing values with dtype: {self.dtype}, set " + "encoded_missing_value to a non-nan value, or " + "set dtype to a float" + ) + + if not is_scalar_nan(self.encoded_missing_value): + # Features are invalid when they contain a missing category + # and encoded_missing_value was already used to encode a + # known category + invalid_features = [ + cat_idx + for cat_idx, categories_for_idx in enumerate(self.categories_) + if cat_idx in self._missing_indices + and 0 <= self.encoded_missing_value < len(categories_for_idx) + ] + + if invalid_features: + # Use feature names if they are avaliable + if hasattr(self, "feature_names_in_"): + invalid_features = self.feature_names_in_[invalid_features] + raise ValueError( + f"encoded_missing_value ({self.encoded_missing_value}) " + "is already used to encode a known category in features: " + f"{invalid_features}" + ) return self @@ -1317,7 +1367,7 @@ def transform(self, X): for cat_idx, missing_idx in self._missing_indices.items(): X_missing_mask = X_int[:, cat_idx] == missing_idx - X_trans[X_missing_mask, cat_idx] = np.nan + X_trans[X_missing_mask, cat_idx] = self.encoded_missing_value # create separate category for unknown values if self.handle_unknown == "use_encoded_value": @@ -1362,7 +1412,7 @@ def inverse_transform(self, X): # replace values of X[:, i] that were nan with actual indices if i in self._missing_indices: - X_i_mask = _get_mask(X[:, i], np.nan) + X_i_mask = _get_mask(X[:, i], self.encoded_missing_value) labels[X_i_mask] = self._missing_indices[i] if self.handle_unknown == "use_encoded_value":
diff --git a/sklearn/preprocessing/tests/test_encoders.py b/sklearn/preprocessing/tests/test_encoders.py index a96786419816d..ea32de22cd2f0 100644 --- a/sklearn/preprocessing/tests/test_encoders.py +++ b/sklearn/preprocessing/tests/test_encoders.py @@ -1664,31 +1664,35 @@ def test_ordinal_encoder_passthrough_missing_values_float_errors_dtype(): msg = ( r"There are missing values in features \[0\]. For OrdinalEncoder " - "to passthrough missing values, the dtype parameter must be a " - "float" + f"to encode missing values with dtype: {np.int32}" ) with pytest.raises(ValueError, match=msg): oe.fit(X) -def test_ordinal_encoder_passthrough_missing_values_float(): [email protected]("encoded_missing_value", [np.nan, -2]) +def test_ordinal_encoder_passthrough_missing_values_float(encoded_missing_value): """Test ordinal encoder with nan on float dtypes.""" X = np.array([[np.nan, 3.0, 1.0, 3.0]], dtype=np.float64).T - oe = OrdinalEncoder().fit(X) + oe = OrdinalEncoder(encoded_missing_value=encoded_missing_value).fit(X) assert len(oe.categories_) == 1 + assert_allclose(oe.categories_[0], [1.0, 3.0, np.nan]) X_trans = oe.transform(X) - assert_allclose(X_trans, [[np.nan], [1.0], [0.0], [1.0]]) + assert_allclose(X_trans, [[encoded_missing_value], [1.0], [0.0], [1.0]]) X_inverse = oe.inverse_transform(X_trans) assert_allclose(X_inverse, X) @pytest.mark.parametrize("pd_nan_type", ["pd.NA", "np.nan"]) -def test_ordinal_encoder_missing_value_support_pandas_categorical(pd_nan_type): [email protected]("encoded_missing_value", [np.nan, -2]) +def test_ordinal_encoder_missing_value_support_pandas_categorical( + pd_nan_type, encoded_missing_value +): """Check ordinal encoder is compatible with pandas.""" # checks pandas dataframe with categorical features pd = pytest.importorskip("pandas") @@ -1701,14 +1705,14 @@ def test_ordinal_encoder_missing_value_support_pandas_categorical(pd_nan_type): } ) - oe = OrdinalEncoder().fit(df) + oe = OrdinalEncoder(encoded_missing_value=encoded_missing_value).fit(df) assert len(oe.categories_) == 1 assert_array_equal(oe.categories_[0][:3], ["a", "b", "c"]) assert np.isnan(oe.categories_[0][-1]) df_trans = oe.transform(df) - assert_allclose(df_trans, [[2.0], [0.0], [np.nan], [1.0], [0.0]]) + assert_allclose(df_trans, [[2.0], [0.0], [encoded_missing_value], [1.0], [0.0]]) X_inverse = oe.inverse_transform(df_trans) assert X_inverse.shape == (5, 1) @@ -1902,3 +1906,50 @@ def test_ordinal_encoder_features_names_out_pandas(): feature_names_out = enc.get_feature_names_out() assert_array_equal(names, feature_names_out) + + +def test_ordinal_encoder_unknown_missing_interaction(): + """Check interactions between encode_unknown and missing value encoding.""" + + X = np.array([["a"], ["b"], [np.nan]], dtype=object) + + oe = OrdinalEncoder( + handle_unknown="use_encoded_value", + unknown_value=np.nan, + encoded_missing_value=-3, + ).fit(X) + + X_trans = oe.transform(X) + assert_allclose(X_trans, [[0], [1], [-3]]) + + # "c" is unknown and is mapped to np.nan + # "None" is a missing value and is set to -3 + X_test = np.array([["c"], [np.nan]], dtype=object) + X_test_trans = oe.transform(X_test) + assert_allclose(X_test_trans, [[np.nan], [-3]]) + + [email protected]("with_pandas", [True, False]) +def test_ordinal_encoder_encoded_missing_value_error(with_pandas): + """Check OrdinalEncoder errors when encoded_missing_value is used by + an known category.""" + X = np.array([["a", "dog"], ["b", "cat"], ["c", np.nan]], dtype=object) + + # The 0-th feature has no missing values so it is not included in the list of + # features + error_msg = ( + r"encoded_missing_value \(1\) is already used to encode a known category " + r"in features: " + ) + + if with_pandas: + pd = pytest.importorskip("pandas") + X = pd.DataFrame(X, columns=["letter", "pet"]) + error_msg = error_msg + r"\['pet'\]" + else: + error_msg = error_msg + r"\[1\]" + + oe = OrdinalEncoder(encoded_missing_value=1) + + with pytest.raises(ValueError, match=error_msg): + oe.fit(X)
[ { "path": "doc/modules/preprocessing.rst", "old_path": "a/doc/modules/preprocessing.rst", "new_path": "b/doc/modules/preprocessing.rst", "metadata": "diff --git a/doc/modules/preprocessing.rst b/doc/modules/preprocessing.rst\nindex 997bccf66782d..beb91d8780de8 100644\n--- a/doc/modules/preprocessing.rst\n+++ b/doc/modules/preprocessing.rst\n@@ -537,8 +537,8 @@ scikit-learn estimators, as these expect continuous input, and would interpret\n the categories as being ordered, which is often not desired (i.e. the set of\n browsers was ordered arbitrarily).\n \n-:class:`OrdinalEncoder` will also passthrough missing values that are\n-indicated by `np.nan`.\n+By default, :class:`OrdinalEncoder` will also passthrough missing values that\n+are indicated by `np.nan`.\n \n >>> enc = preprocessing.OrdinalEncoder()\n >>> X = [['male'], ['female'], [np.nan], ['female']]\n@@ -548,6 +548,32 @@ indicated by `np.nan`.\n [nan],\n [ 0.]])\n \n+:class:`OrdinalEncoder` provides a parameter `encoded_missing_value` to encode\n+the missing values without the need to create a pipeline and using\n+:class:`~sklearn.impute.SimpleImputer`.\n+\n+ >>> enc = preprocessing.OrdinalEncoder(encoded_missing_value=-1)\n+ >>> X = [['male'], ['female'], [np.nan], ['female']]\n+ >>> enc.fit_transform(X)\n+ array([[ 1.],\n+ [ 0.],\n+ [-1.],\n+ [ 0.]])\n+\n+The above processing is equivalent to the following pipeline::\n+\n+ >>> from sklearn.pipeline import Pipeline\n+ >>> from sklearn.impute import SimpleImputer\n+ >>> enc = Pipeline(steps=[\n+ ... (\"encoder\", preprocessing.OrdinalEncoder()),\n+ ... (\"imputer\", SimpleImputer(strategy=\"constant\", fill_value=-1)),\n+ ... ])\n+ >>> enc.fit_transform(X)\n+ array([[ 1.],\n+ [ 0.],\n+ [-1.],\n+ [ 0.]])\n+\n Another possibility to convert categorical features to features that can be used\n with scikit-learn estimators is to use a one-of-K, also known as one-hot or\n dummy encoding.\n" }, { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex b62ad01cdacc4..b432673704d71 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -803,6 +803,9 @@ Changelog\n the model. The option is only available when `strategy` is set to `quantile`.\n :pr:`21445` by :user:`Felipe Bidu <fbidu>` and :user:`Amanda Dsouza <amy12xx>`.\n \n+- |Enhancement| Adds `encoded_missing_value` to :class:`preprocessing.OrdinalEncoder`\n+ to configure the encoded value for missing data. :pr:`21988` by `Thomas Fan`_.\n+\n - |Enhancement| Added the `get_feature_names_out` method and a new parameter\n `feature_names_out` to :class:`preprocessing.FunctionTransformer`. You can set\n `feature_names_out` to 'one-to-one' to use the input features names as the\n" } ]
1.01
26eedbd1f453435b7d8f62d151ba23c22a567d88
[ "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[if_binary-if_binary-get_feature_names]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse[first-False-infrequent_if_exist]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[mixed-float-nan]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse_if_binary", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[array-S-U]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_pandas", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder[mixed]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_drop_first_handle_unknown_ignore_warns[ignore]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_missing_value_support_pandas", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse[first-True-infrequent_if_exist]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[int32-float32]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[first-None-get_feature_names_out]", "sklearn/preprocessing/tests/test_encoders.py::test_X_is_not_1D[X1-fit_transform]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknown_string_dtypes[X_test2-X_train1]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categories[numeric]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse_transform_raise_error_with_unknown[X1-X_trans1-False]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[first-None-get_feature_names]", "sklearn/preprocessing/tests/test_encoders.py::test_encoder_dtypes_pandas", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype_pandas[float32]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[dataframe-U-U]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknown_string_dtypes[X_test1-X_train1]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object-string-infrequent_if_exist]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_three_levels_drop_infrequent_errors[drop0]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_specified_categories_missing_passthrough[object-None-missing-value]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_two_levels[categories1-kwargs1]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[dataframe-S-O]", "sklearn/preprocessing/tests/test_encoders.py::test_encoder_dtypes", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_three_levels[kwargs6]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_two_levels[auto-kwargs1]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_two_levels[auto-kwargs2]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_drop_if_binary_handle_unknown_ignore_warns[infrequent_if_exist]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[numeric-ignore]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_two_levels_drop_frequent[first]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_three_levels_user_cats", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[if_binary-None-get_feature_names_out]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_two_levels[auto-kwargs0]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_two_levels[auto-kwargs4]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[dataframe-O-O]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object-string-nan-ignore]", "sklearn/preprocessing/tests/test_encoders.py::test_invalid_drop_length[drop1]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_handle_unknown_strings[ignore]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object-ignore]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object-string-none-ignore]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknown_string_dtypes[X_test1-X_train2]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_handle_unknown[infrequent_if_exist]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse[None-True-infrequent_if_exist]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[list-O-U]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_set_params", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[array-U-O]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_specified_categories_missing_passthrough[numeric-missing-value]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names[get_feature_names]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object-string-ignore]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_two_levels_user_cats", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_not_fitted", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_two_levels_drop_infrequent_errors[drop1]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_two_levels[categories1-kwargs2]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[None-None-get_feature_names]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_two_levels_drop_frequent[if_binary]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_manual[None]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object-string-nan-infrequent_if_exist]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_drop_first_handle_unknown_ignore_warns[infrequent_if_exist]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_three_levels_drop_frequent[drop1]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[array-O-O]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[mixed-None]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse_transform_raise_error_with_unknown[X0-X_trans0-False]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[first-if_binary-get_feature_names_out]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[numeric]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_inverse", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[numeric-infrequent_if_exist]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[list-S-O]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[list-U-S]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_features_names_out_pandas", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_handle_unknown_strings[infrequent_if_exist]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[None-None-get_feature_names_out]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names[get_feature_names_out]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[dataframe-U-O]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categories[missing-float]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_one_level_errors[kwargs0]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_invalid_parameters_error[kwargs0-max_categories must be greater than 1]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder[object]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_specified_categories_missing_passthrough[object-nan-missing_value]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categories[missing-float-nan-object]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_two_levels_drop_infrequent_errors[drop0]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names_drop[manual-get_feature_names]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[None-if_binary-get_feature_names_out]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_drop_first_explicit_categories[infrequent_if_exist]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_manual[nan0]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object-infrequent_if_exist]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[if_binary-first-get_feature_names]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[array-U-S]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_raise_categories_shape", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[list-S-U]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse[None-False-infrequent_if_exist]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[first-first-get_feature_names]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_invalid_parameters_error[kwargs2-min_frequency must be an integer at least]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_get_feature_names_deprecated", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_missing_values_get_feature_names[nan-get_feature_names]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_mixed", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categories[object]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_two_levels[categories1-kwargs3]", "sklearn/preprocessing/tests/test_encoders.py::test_invalid_drop_length[drop0]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype_pandas[int32]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_unsorted_categories", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_invalid_parameters_error[kwargs1-min_frequency must be an integer at least]", "sklearn/preprocessing/tests/test_encoders.py::test_X_is_not_1D_pandas[fit_transform]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object-None-and-nan-infrequent_if_exist]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_three_levels[kwargs3]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories_mixed_columns", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_missing_value_support_pandas_categorical[np.nan-infrequent_if_exist]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[float32-float32]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categories[mixed]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[float64-float64]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse[first-True-ignore]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_nan_non_float_dtype", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_three_levels[kwargs5]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[object]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_missing_values_get_feature_names[None-get_feature_names]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_two_levels[categories1-kwargs0]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[float64-float32]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_missing_values_get_feature_names[nan-get_feature_names_out]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[if_binary-if_binary-get_feature_names_out]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknown_string_dtypes[X_test1-X_train0]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[None-if_binary-get_feature_names]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_missing_and_unknown[X3-expected_X_trans3-X_test3]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_two_levels_user_cats_one_frequent[kwargs0]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[int32-float64]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[if_binary-None-get_feature_names]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknown_string_dtypes[X_test0-X_train1]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_specified_categories[numeric]", "sklearn/preprocessing/tests/test_encoders.py::test_categories[first-sparse]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[int32-int32]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[if_binary-first-get_feature_names_out]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[mixed-None-nan]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_numeric[float]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_numeric[int]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_has_categorical_tags[OrdinalEncoder]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_user_cats_unknown_training_errors[kwargs0]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_three_levels[kwargs4]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_equals_if_binary", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse_transform_raise_error_with_unknown[X0-X_trans0-True]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_three_levels[kwargs0]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[dataframe-S-S]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknown_string_dtypes[X_test2-X_train0]", "sklearn/preprocessing/tests/test_encoders.py::test_X_is_not_1D[X0-fit_transform]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_handle_unknown[ignore]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_warning", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[array-S-O]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names_drop[first-get_feature_names]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_multiple_categories_dtypes", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknown_string_dtypes[X_test2-X_train2]", "sklearn/preprocessing/tests/test_encoders.py::test_X_is_not_1D[X0-fit]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names_drop[binary-get_feature_names_out]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_fit_with_unseen_category", "sklearn/preprocessing/tests/test_encoders.py::test_categories[first-dense]", "sklearn/preprocessing/tests/test_encoders.py::test_X_is_not_1D_pandas[fit]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[list-U-U]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[dataframe-S-U]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_three_levels_drop_frequent[first]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[array-O-U]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names_drop[manual-get_feature_names_out]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names_unicode[get_feature_names]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_invalid_params[X_fit0-params0-Wrong input for parameter `drop`]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_invalid_params[X_fit2-params2-The following categories were supposed]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_two_levels[auto-kwargs3]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknown_string_dtypes[X_test0-X_train2]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_raise[params4-ValueError-handle_unknown should be either 'error' or 'use_encoded_value', got ignore.]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_two_levels[categories1-kwargs4]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_sparse", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_raise[params0-TypeError-unknown_value should be an integer or np.nan when handle_unknown is 'use_encoded_value', got None.]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[float32-int32]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse[None-True-ignore]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_raise[params1-TypeError-unknown_value should only be set when handle_unknown is 'use_encoded_value', got -2.]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[list-U-O]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object-string-none-infrequent_if_exist]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_missing_value_support_pandas_categorical[pd.NA-infrequent_if_exist]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknown_string_dtypes[X_test0-X_train0]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[None-first-get_feature_names_out]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object-None-and-nan-ignore]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_specified_categories[object-string-cat]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_nan", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names_drop[binary-get_feature_names]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object-nan-and-None-infrequent_if_exist]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_invalid_params[X_fit1-params1-Wrong input for parameter `drop`]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[mixed-None-float-nan]", "sklearn/preprocessing/tests/test_encoders.py::test_categories[manual-dense]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_missing_and_unknown[X1-expected_X_trans1-X_test1]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[list-O-O]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_raise[params3-ValueError-The used value for unknown_value (1) is one of the values already used for encoding the seen categories.]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names_unicode[get_feature_names_out]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_sparse_dense", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_two_levels_drop_frequent[drop2]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[array-U-U]", "sklearn/preprocessing/tests/test_encoders.py::test_categories[manual-sparse]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[first-if_binary-get_feature_names]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_missing_values_get_feature_names[None-get_feature_names_out]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_has_categorical_tags[OneHotEncoder]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_three_levels[kwargs1]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_missing_value_support_pandas_categorical[pd.NA-ignore]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_missing_and_unknown[X0-expected_X_trans0-X_test0]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_three_levels[kwargs2]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[mixed-nan]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder[numeric]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object-nan-and-None-ignore]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categories[string]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[dataframe-U-S]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[array-S-S]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_specified_categories[object]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_python_integer", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[list-S-S]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[dataframe-O-U]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[first-first-get_feature_names_out]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_multiple_categories", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse[None-False-ignore]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_raise[params2-TypeError-unknown_value should be an integer or np.nan when handle_unknown is 'use_encoded_value', got bla.]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[None-first-get_feature_names]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_two_levels_user_cats_one_frequent[kwargs1]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_missing_value_support_pandas_categorical[np.nan-ignore]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_drop_first_explicit_categories[ignore]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_drop_if_binary_handle_unknown_ignore_warns[ignore]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype_pandas[float64]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[float64-int32]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names_drop[first-get_feature_names_out]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_string", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_manual[nan1]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categories[missing-np.nan-object]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse_transform_raise_error_with_unknown[X1-X_trans1-True]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_three_levels_drop_infrequent_errors[drop1]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_missing_and_unknown[X2-expected_X_trans2-X_test2]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[mixed]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[float32-float64]", "sklearn/preprocessing/tests/test_encoders.py::test_X_is_not_1D[X1-fit]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_infrequent_handle_unknown_error", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse[first-False-ignore]" ]
[ "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_encoded_missing_value_error[False]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_passthrough_missing_values_float[-2]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_unknown_missing_interaction", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_missing_value_support_pandas_categorical[nan-np.nan]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_missing_value_support_pandas_categorical[-2-np.nan]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_missing_value_support_pandas_categorical[nan-pd.NA]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_passthrough_missing_values_float_errors_dtype", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_encoded_missing_value_error[True]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_missing_value_support_pandas_categorical[-2-pd.NA]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_passthrough_missing_values_float[nan]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/modules/preprocessing.rst", "old_path": "a/doc/modules/preprocessing.rst", "new_path": "b/doc/modules/preprocessing.rst", "metadata": "diff --git a/doc/modules/preprocessing.rst b/doc/modules/preprocessing.rst\nindex 997bccf66782d..beb91d8780de8 100644\n--- a/doc/modules/preprocessing.rst\n+++ b/doc/modules/preprocessing.rst\n@@ -537,8 +537,8 @@ scikit-learn estimators, as these expect continuous input, and would interpret\n the categories as being ordered, which is often not desired (i.e. the set of\n browsers was ordered arbitrarily).\n \n-:class:`OrdinalEncoder` will also passthrough missing values that are\n-indicated by `np.nan`.\n+By default, :class:`OrdinalEncoder` will also passthrough missing values that\n+are indicated by `np.nan`.\n \n >>> enc = preprocessing.OrdinalEncoder()\n >>> X = [['male'], ['female'], [np.nan], ['female']]\n@@ -548,6 +548,32 @@ indicated by `np.nan`.\n [nan],\n [ 0.]])\n \n+:class:`OrdinalEncoder` provides a parameter `encoded_missing_value` to encode\n+the missing values without the need to create a pipeline and using\n+:class:`~sklearn.impute.SimpleImputer`.\n+\n+ >>> enc = preprocessing.OrdinalEncoder(encoded_missing_value=-1)\n+ >>> X = [['male'], ['female'], [np.nan], ['female']]\n+ >>> enc.fit_transform(X)\n+ array([[ 1.],\n+ [ 0.],\n+ [-1.],\n+ [ 0.]])\n+\n+The above processing is equivalent to the following pipeline::\n+\n+ >>> from sklearn.pipeline import Pipeline\n+ >>> from sklearn.impute import SimpleImputer\n+ >>> enc = Pipeline(steps=[\n+ ... (\"encoder\", preprocessing.OrdinalEncoder()),\n+ ... (\"imputer\", SimpleImputer(strategy=\"constant\", fill_value=-1)),\n+ ... ])\n+ >>> enc.fit_transform(X)\n+ array([[ 1.],\n+ [ 0.],\n+ [-1.],\n+ [ 0.]])\n+\n Another possibility to convert categorical features to features that can be used\n with scikit-learn estimators is to use a one-of-K, also known as one-hot or\n dummy encoding.\n" }, { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex b62ad01cdacc4..b432673704d71 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -803,6 +803,9 @@ Changelog\n the model. The option is only available when `strategy` is set to `quantile`.\n :pr:`<PRID>` by :user:`<NAME>` and :user:`<NAME>`.\n \n+- |Enhancement| Adds `encoded_missing_value` to :class:`preprocessing.OrdinalEncoder`\n+ to configure the encoded value for missing data. :pr:`<PRID>` by `<NAME>`_.\n+\n - |Enhancement| Added the `get_feature_names_out` method and a new parameter\n `feature_names_out` to :class:`preprocessing.FunctionTransformer`. You can set\n `feature_names_out` to 'one-to-one' to use the input features names as the\n" } ]
diff --git a/doc/modules/preprocessing.rst b/doc/modules/preprocessing.rst index 997bccf66782d..beb91d8780de8 100644 --- a/doc/modules/preprocessing.rst +++ b/doc/modules/preprocessing.rst @@ -537,8 +537,8 @@ scikit-learn estimators, as these expect continuous input, and would interpret the categories as being ordered, which is often not desired (i.e. the set of browsers was ordered arbitrarily). -:class:`OrdinalEncoder` will also passthrough missing values that are -indicated by `np.nan`. +By default, :class:`OrdinalEncoder` will also passthrough missing values that +are indicated by `np.nan`. >>> enc = preprocessing.OrdinalEncoder() >>> X = [['male'], ['female'], [np.nan], ['female']] @@ -548,6 +548,32 @@ indicated by `np.nan`. [nan], [ 0.]]) +:class:`OrdinalEncoder` provides a parameter `encoded_missing_value` to encode +the missing values without the need to create a pipeline and using +:class:`~sklearn.impute.SimpleImputer`. + + >>> enc = preprocessing.OrdinalEncoder(encoded_missing_value=-1) + >>> X = [['male'], ['female'], [np.nan], ['female']] + >>> enc.fit_transform(X) + array([[ 1.], + [ 0.], + [-1.], + [ 0.]]) + +The above processing is equivalent to the following pipeline:: + + >>> from sklearn.pipeline import Pipeline + >>> from sklearn.impute import SimpleImputer + >>> enc = Pipeline(steps=[ + ... ("encoder", preprocessing.OrdinalEncoder()), + ... ("imputer", SimpleImputer(strategy="constant", fill_value=-1)), + ... ]) + >>> enc.fit_transform(X) + array([[ 1.], + [ 0.], + [-1.], + [ 0.]]) + Another possibility to convert categorical features to features that can be used with scikit-learn estimators is to use a one-of-K, also known as one-hot or dummy encoding. diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index b62ad01cdacc4..b432673704d71 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -803,6 +803,9 @@ Changelog the model. The option is only available when `strategy` is set to `quantile`. :pr:`<PRID>` by :user:`<NAME>` and :user:`<NAME>`. +- |Enhancement| Adds `encoded_missing_value` to :class:`preprocessing.OrdinalEncoder` + to configure the encoded value for missing data. :pr:`<PRID>` by `<NAME>`_. + - |Enhancement| Added the `get_feature_names_out` method and a new parameter `feature_names_out` to :class:`preprocessing.FunctionTransformer`. You can set `feature_names_out` to 'one-to-one' to use the input features names as the
scikit-learn/scikit-learn
scikit-learn__scikit-learn-21701
https://github.com/scikit-learn/scikit-learn/pull/21701
diff --git a/doc/modules/random_projection.rst b/doc/modules/random_projection.rst index adb2d53bd14d6..7d3341f0244bb 100644 --- a/doc/modules/random_projection.rst +++ b/doc/modules/random_projection.rst @@ -160,3 +160,42 @@ projection transformer:: In Proceedings of the 12th ACM SIGKDD international conference on Knowledge discovery and data mining (KDD '06). ACM, New York, NY, USA, 287-296. + + +.. _random_projection_inverse_transform: + +Inverse Transform +================= +The random projection transformers have ``compute_inverse_components`` parameter. When +set to True, after creating the random ``components_`` matrix during fitting, +the transformer computes the pseudo-inverse of this matrix and stores it as +``inverse_components_``. The ``inverse_components_`` matrix has shape +:math:`n_{features} \times n_{components}`, and it is always a dense matrix, +regardless of whether the components matrix is sparse or dense. So depending on +the number of features and components, it may use a lot of memory. + +When the ``inverse_transform`` method is called, it computes the product of the +input ``X`` and the transpose of the inverse components. If the inverse components have +been computed during fit, they are reused at each call to ``inverse_transform``. +Otherwise they are recomputed each time, which can be costly. The result is always +dense, even if ``X`` is sparse. + +Here a small code example which illustrates how to use the inverse transform +feature:: + + >>> import numpy as np + >>> from sklearn.random_projection import SparseRandomProjection + >>> X = np.random.rand(100, 10000) + >>> transformer = SparseRandomProjection( + ... compute_inverse_components=True + ... ) + ... + >>> X_new = transformer.fit_transform(X) + >>> X_new.shape + (100, 3947) + >>> X_new_inversed = transformer.inverse_transform(X_new) + >>> X_new_inversed.shape + (100, 10000) + >>> X_new_again = transformer.transform(X_new_inversed) + >>> np.allclose(X_new, X_new_again) + True diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 5030ed8faa4a1..e66640cfd2d21 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -791,6 +791,14 @@ Changelog :class:`random_projection.GaussianRandomProjection` preserves dtype for `numpy.float32`. :pr:`22114` by :user:`Takeshi Oura <takoika>`. +- |Enhancement| Adds an :meth:`inverse_transform` method and a + `compute_inverse_transform` parameter to all transformers in the + :mod:`~sklearn.random_projection` module: + :class:`~sklearn.random_projection.GaussianRandomProjection` and + :class:`~sklearn.random_projection.SparseRandomProjection`. When the parameter is set + to True, the pseudo-inverse of the components is computed during `fit` and stored as + `inverse_components_`. :pr:`21701` by `Aurélien Geron <ageron>`. + - |API| Adds :term:`get_feature_names_out` to all transformers in the :mod:`~sklearn.random_projection` module: :class:`~sklearn.random_projection.GaussianRandomProjection` and diff --git a/sklearn/random_projection.py b/sklearn/random_projection.py index 31ebfdddd8928..000eca478553e 100644 --- a/sklearn/random_projection.py +++ b/sklearn/random_projection.py @@ -31,6 +31,7 @@ from abc import ABCMeta, abstractmethod import numpy as np +from scipy import linalg import scipy.sparse as sp from .base import BaseEstimator, TransformerMixin @@ -39,10 +40,9 @@ from .utils import check_random_state from .utils.extmath import safe_sparse_dot from .utils.random import sample_without_replacement -from .utils.validation import check_is_fitted +from .utils.validation import check_array, check_is_fitted from .exceptions import DataDimensionalityWarning - __all__ = [ "SparseRandomProjection", "GaussianRandomProjection", @@ -302,11 +302,18 @@ class BaseRandomProjection( @abstractmethod def __init__( - self, n_components="auto", *, eps=0.1, dense_output=False, random_state=None + self, + n_components="auto", + *, + eps=0.1, + dense_output=False, + compute_inverse_components=False, + random_state=None, ): self.n_components = n_components self.eps = eps self.dense_output = dense_output + self.compute_inverse_components = compute_inverse_components self.random_state = random_state @abstractmethod @@ -323,12 +330,18 @@ def _make_random_matrix(self, n_components, n_features): Returns ------- - components : {ndarray, sparse matrix} of shape \ - (n_components, n_features) + components : {ndarray, sparse matrix} of shape (n_components, n_features) The generated random matrix. Sparse matrix will be of CSR format. """ + def _compute_inverse_components(self): + """Compute the pseudo-inverse of the (densified) components.""" + components = self.components_ + if sp.issparse(components): + components = components.toarray() + return linalg.pinv(components, check_finite=False) + def fit(self, X, y=None): """Generate a sparse random projection matrix. @@ -399,6 +412,9 @@ def fit(self, X, y=None): " not the proper shape." ) + if self.compute_inverse_components: + self.inverse_components_ = self._compute_inverse_components() + return self def transform(self, X): @@ -437,6 +453,35 @@ def _n_features_out(self): """ return self.n_components + def inverse_transform(self, X): + """Project data back to its original space. + + Returns an array X_original whose transform would be X. Note that even + if X is sparse, X_original is dense: this may use a lot of RAM. + + If `compute_inverse_components` is False, the inverse of the components is + computed during each call to `inverse_transform` which can be costly. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_components) + Data to be transformed back. + + Returns + ------- + X_original : ndarray of shape (n_samples, n_features) + Reconstructed data. + """ + check_is_fitted(self) + + X = check_array(X, dtype=[np.float64, np.float32], accept_sparse=("csr", "csc")) + + if self.compute_inverse_components: + return X @ self.inverse_components_.T + + inverse_components = self._compute_inverse_components() + return X @ inverse_components.T + def _more_tags(self): return { "preserves_dtype": [np.float64, np.float32], @@ -474,6 +519,11 @@ class GaussianRandomProjection(BaseRandomProjection): Smaller values lead to better embedding and higher number of dimensions (n_components) in the target projection space. + compute_inverse_components : bool, default=False + Learn the inverse transform by computing the pseudo-inverse of the + components during fit. Note that computing the pseudo-inverse does not + scale well to large matrices. + random_state : int, RandomState instance or None, default=None Controls the pseudo random number generator used to generate the projection matrix at fit time. @@ -488,6 +538,12 @@ class GaussianRandomProjection(BaseRandomProjection): components_ : ndarray of shape (n_components, n_features) Random matrix used for the projection. + inverse_components_ : ndarray of shape (n_features, n_components) + Pseudo-inverse of the components, only computed if + `compute_inverse_components` is True. + + .. versionadded:: 1.1 + n_features_in_ : int Number of features seen during :term:`fit`. @@ -516,11 +572,19 @@ class GaussianRandomProjection(BaseRandomProjection): (25, 2759) """ - def __init__(self, n_components="auto", *, eps=0.1, random_state=None): + def __init__( + self, + n_components="auto", + *, + eps=0.1, + compute_inverse_components=False, + random_state=None, + ): super().__init__( n_components=n_components, eps=eps, dense_output=True, + compute_inverse_components=compute_inverse_components, random_state=random_state, ) @@ -610,6 +674,14 @@ class SparseRandomProjection(BaseRandomProjection): If False, the projected data uses a sparse representation if the input is sparse. + compute_inverse_components : bool, default=False + Learn the inverse transform by computing the pseudo-inverse of the + components during fit. Note that the pseudo-inverse is always a dense + array, even if the training data was sparse. This means that it might be + necessary to call `inverse_transform` on a small batch of samples at a + time to avoid exhausting the available memory on the host. Moreover, + computing the pseudo-inverse does not scale well to large matrices. + random_state : int, RandomState instance or None, default=None Controls the pseudo random number generator used to generate the projection matrix at fit time. @@ -625,6 +697,12 @@ class SparseRandomProjection(BaseRandomProjection): Random matrix used for the projection. Sparse matrix will be of CSR format. + inverse_components_ : ndarray of shape (n_features, n_components) + Pseudo-inverse of the components, only computed if + `compute_inverse_components` is True. + + .. versionadded:: 1.1 + density_ : float in range 0.0 - 1.0 Concrete density computed from when density = "auto". @@ -676,12 +754,14 @@ def __init__( density="auto", eps=0.1, dense_output=False, + compute_inverse_components=False, random_state=None, ): super().__init__( n_components=n_components, eps=eps, dense_output=dense_output, + compute_inverse_components=compute_inverse_components, random_state=random_state, )
diff --git a/sklearn/tests/test_random_projection.py b/sklearn/tests/test_random_projection.py index a3a6b1ae2a49f..4d21090a3e6fb 100644 --- a/sklearn/tests/test_random_projection.py +++ b/sklearn/tests/test_random_projection.py @@ -1,5 +1,6 @@ import functools from typing import List, Any +import warnings import numpy as np import scipy.sparse as sp @@ -31,8 +32,8 @@ # Make some random data with uniformly located non zero entries with # Gaussian distributed values -def make_sparse_random_data(n_samples, n_features, n_nonzeros): - rng = np.random.RandomState(0) +def make_sparse_random_data(n_samples, n_features, n_nonzeros, random_state=0): + rng = np.random.RandomState(random_state) data_coo = sp.coo_matrix( ( rng.randn(n_nonzeros), @@ -377,6 +378,57 @@ def test_random_projection_feature_names_out(random_projection_cls): assert_array_equal(names_out, expected_names_out) [email protected]("n_samples", (2, 9, 10, 11, 1000)) [email protected]("n_features", (2, 9, 10, 11, 1000)) [email protected]("random_projection_cls", all_RandomProjection) [email protected]("compute_inverse_components", [True, False]) +def test_inverse_transform( + n_samples, + n_features, + random_projection_cls, + compute_inverse_components, + global_random_seed, +): + n_components = 10 + + random_projection = random_projection_cls( + n_components=n_components, + compute_inverse_components=compute_inverse_components, + random_state=global_random_seed, + ) + + X_dense, X_csr = make_sparse_random_data( + n_samples, + n_features, + n_samples * n_features // 100 + 1, + random_state=global_random_seed, + ) + + for X in [X_dense, X_csr]: + with warnings.catch_warnings(): + warnings.filterwarnings( + "ignore", + message=( + "The number of components is higher than the number of features" + ), + category=DataDimensionalityWarning, + ) + projected = random_projection.fit_transform(X) + + if compute_inverse_components: + assert hasattr(random_projection, "inverse_components_") + inv_components = random_projection.inverse_components_ + assert inv_components.shape == (n_features, n_components) + + projected_back = random_projection.inverse_transform(projected) + assert projected_back.shape == X.shape + + projected_again = random_projection.transform(projected_back) + if hasattr(projected, "toarray"): + projected = projected.toarray() + assert_allclose(projected, projected_again, rtol=1e-7, atol=1e-10) + + @pytest.mark.parametrize("random_projection_cls", all_RandomProjection) @pytest.mark.parametrize( "input_dtype, expected_dtype",
[ { "path": "doc/modules/random_projection.rst", "old_path": "a/doc/modules/random_projection.rst", "new_path": "b/doc/modules/random_projection.rst", "metadata": "diff --git a/doc/modules/random_projection.rst b/doc/modules/random_projection.rst\nindex adb2d53bd14d6..7d3341f0244bb 100644\n--- a/doc/modules/random_projection.rst\n+++ b/doc/modules/random_projection.rst\n@@ -160,3 +160,42 @@ projection transformer::\n In Proceedings of the 12th ACM SIGKDD international conference on\n Knowledge discovery and data mining (KDD '06). ACM, New York, NY, USA,\n 287-296.\n+\n+\n+.. _random_projection_inverse_transform:\n+\n+Inverse Transform\n+=================\n+The random projection transformers have ``compute_inverse_components`` parameter. When\n+set to True, after creating the random ``components_`` matrix during fitting,\n+the transformer computes the pseudo-inverse of this matrix and stores it as\n+``inverse_components_``. The ``inverse_components_`` matrix has shape\n+:math:`n_{features} \\times n_{components}`, and it is always a dense matrix,\n+regardless of whether the components matrix is sparse or dense. So depending on\n+the number of features and components, it may use a lot of memory.\n+\n+When the ``inverse_transform`` method is called, it computes the product of the\n+input ``X`` and the transpose of the inverse components. If the inverse components have\n+been computed during fit, they are reused at each call to ``inverse_transform``.\n+Otherwise they are recomputed each time, which can be costly. The result is always\n+dense, even if ``X`` is sparse.\n+\n+Here a small code example which illustrates how to use the inverse transform\n+feature::\n+\n+ >>> import numpy as np\n+ >>> from sklearn.random_projection import SparseRandomProjection\n+ >>> X = np.random.rand(100, 10000)\n+ >>> transformer = SparseRandomProjection(\n+ ... compute_inverse_components=True\n+ ... )\n+ ...\n+ >>> X_new = transformer.fit_transform(X)\n+ >>> X_new.shape\n+ (100, 3947)\n+ >>> X_new_inversed = transformer.inverse_transform(X_new)\n+ >>> X_new_inversed.shape\n+ (100, 10000)\n+ >>> X_new_again = transformer.transform(X_new_inversed)\n+ >>> np.allclose(X_new, X_new_again)\n+ True\n" }, { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 5030ed8faa4a1..e66640cfd2d21 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -791,6 +791,14 @@ Changelog\n :class:`random_projection.GaussianRandomProjection` preserves dtype for\n `numpy.float32`. :pr:`22114` by :user:`Takeshi Oura <takoika>`.\n \n+- |Enhancement| Adds an :meth:`inverse_transform` method and a\n+ `compute_inverse_transform` parameter to all transformers in the\n+ :mod:`~sklearn.random_projection` module:\n+ :class:`~sklearn.random_projection.GaussianRandomProjection` and\n+ :class:`~sklearn.random_projection.SparseRandomProjection`. When the parameter is set\n+ to True, the pseudo-inverse of the components is computed during `fit` and stored as\n+ `inverse_components_`. :pr:`21701` by `Aurélien Geron <ageron>`.\n+\n - |API| Adds :term:`get_feature_names_out` to all transformers in the\n :mod:`~sklearn.random_projection` module:\n :class:`~sklearn.random_projection.GaussianRandomProjection` and\n" } ]
1.01
a794c58692a1f3e7a85a42d8c7f7ddd5fcf18baa
[ "sklearn/tests/test_random_projection.py::test_sparse_random_projection_transformer_invalid_density[0]", "sklearn/tests/test_random_projection.py::test_random_projection_feature_names_out[GaussianRandomProjection]", "sklearn/tests/test_random_projection.py::test_try_to_transform_before_fit", "sklearn/tests/test_random_projection.py::test_warning_n_components_greater_than_n_features", "sklearn/tests/test_random_projection.py::test_random_projection_numerical_consistency[SparseRandomProjection]", "sklearn/tests/test_random_projection.py::test_random_projection_dtype_match[float32-float32-SparseRandomProjection]", "sklearn/tests/test_random_projection.py::test_too_many_samples_to_find_a_safe_embedding", "sklearn/tests/test_random_projection.py::test_random_projection_dtype_match[int32-float64-SparseRandomProjection]", "sklearn/tests/test_random_projection.py::test_sparse_random_projection_transformer_invalid_density[1.1]", "sklearn/tests/test_random_projection.py::test_invalid_jl_domain[0-0.5]", "sklearn/tests/test_random_projection.py::test_basic_property_of_random_matrix[_gaussian_random_matrix]", "sklearn/tests/test_random_projection.py::test_invalid_jl_domain[100--0.1]", "sklearn/tests/test_random_projection.py::test_random_projection_numerical_consistency[GaussianRandomProjection]", "sklearn/tests/test_random_projection.py::test_random_projection_dtype_match[float64-float64-SparseRandomProjection]", "sklearn/tests/test_random_projection.py::test_random_projection_dtype_match[float32-float32-GaussianRandomProjection]", "sklearn/tests/test_random_projection.py::test_random_projection_dtype_match[int32-float64-GaussianRandomProjection]", "sklearn/tests/test_random_projection.py::test_johnson_lindenstrauss_min_dim", "sklearn/tests/test_random_projection.py::test_random_projection_dtype_match[int64-float64-GaussianRandomProjection]", "sklearn/tests/test_random_projection.py::test_invalid_jl_domain[100-1.1]", "sklearn/tests/test_random_projection.py::test_basic_property_of_sparse_random_matrix[_sparse_random_matrix]", "sklearn/tests/test_random_projection.py::test_input_size_jl_min_dim", "sklearn/tests/test_random_projection.py::test_random_projection_transformer_invalid_input[auto-fit_data0]", "sklearn/tests/test_random_projection.py::test_sparse_random_matrix", "sklearn/tests/test_random_projection.py::test_random_projection_dtype_match[int64-float64-SparseRandomProjection]", "sklearn/tests/test_random_projection.py::test_invalid_jl_domain[100-0.0]", "sklearn/tests/test_random_projection.py::test_random_projection_transformer_invalid_input[-10-fit_data1]", "sklearn/tests/test_random_projection.py::test_correct_RandomProjection_dimensions_embedding", "sklearn/tests/test_random_projection.py::test_random_projection_dtype_match[float64-float64-GaussianRandomProjection]", "sklearn/tests/test_random_projection.py::test_random_projection_feature_names_out[SparseRandomProjection]", "sklearn/tests/test_random_projection.py::test_works_with_sparse_data", "sklearn/tests/test_random_projection.py::test_random_projection_embedding_quality", "sklearn/tests/test_random_projection.py::test_SparseRandomProj_output_representation", "sklearn/tests/test_random_projection.py::test_sparse_random_projection_transformer_invalid_density[-0.1]", "sklearn/tests/test_random_projection.py::test_gaussian_random_matrix", "sklearn/tests/test_random_projection.py::test_basic_property_of_random_matrix[_sparse_random_matrix]" ]
[ "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-1000-9]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-9-2]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-9-9]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-2-2]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-10-2]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-1000-11]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-9-10]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-1000-10]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-10-1000]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-9-11]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-1000-11]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-2-10]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-11-1000]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-2-11]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-2-1000]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-11-1000]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-1000-9]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-11-11]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-2-9]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-10-10]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-10-10]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-1000-10]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-2-11]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-9-1000]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-2-10]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-10-11]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-2-9]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-2-9]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-11-10]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-1000-2]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-1000-1000]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-10-2]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-9-1000]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-9-10]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-9-11]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-10-10]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-1000-2]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-10-2]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-9-11]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-10-9]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-1000-2]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-2-11]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-11-2]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-10-11]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-11-1000]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-2-10]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-9-9]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-10-10]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-10-2]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-11-10]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-1000-9]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-1000-11]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-11-10]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-10-11]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-9-2]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-11-1000]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-10-1000]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-2-1000]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-2-2]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-10-1000]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-2-2]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-2-2]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-2-10]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-9-10]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-9-9]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-11-9]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-11-11]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-10-9]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-11-9]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-2-1000]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-10-1000]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-11-9]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-1000-10]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-9-11]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-9-2]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-1000-1000]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-10-9]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-11-2]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-9-9]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-1000-10]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-2-1000]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-1000-1000]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-11-11]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-1000-9]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-11-2]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-9-10]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-1000-11]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-11-11]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-11-10]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-11-2]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-10-9]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-2-9]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-11-9]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-1000-2]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-9-1000]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-9-2]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-10-11]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-2-11]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-1000-1000]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-9-1000]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/modules/random_projection.rst", "old_path": "a/doc/modules/random_projection.rst", "new_path": "b/doc/modules/random_projection.rst", "metadata": "diff --git a/doc/modules/random_projection.rst b/doc/modules/random_projection.rst\nindex adb2d53bd14d6..7d3341f0244bb 100644\n--- a/doc/modules/random_projection.rst\n+++ b/doc/modules/random_projection.rst\n@@ -160,3 +160,42 @@ projection transformer::\n In Proceedings of the 12th ACM SIGKDD international conference on\n Knowledge discovery and data mining (KDD '06). ACM, New York, NY, USA,\n 287-296.\n+\n+\n+.. _random_projection_inverse_transform:\n+\n+Inverse Transform\n+=================\n+The random projection transformers have ``compute_inverse_components`` parameter. When\n+set to True, after creating the random ``components_`` matrix during fitting,\n+the transformer computes the pseudo-inverse of this matrix and stores it as\n+``inverse_components_``. The ``inverse_components_`` matrix has shape\n+:math:`n_{features} \\times n_{components}`, and it is always a dense matrix,\n+regardless of whether the components matrix is sparse or dense. So depending on\n+the number of features and components, it may use a lot of memory.\n+\n+When the ``inverse_transform`` method is called, it computes the product of the\n+input ``X`` and the transpose of the inverse components. If the inverse components have\n+been computed during fit, they are reused at each call to ``inverse_transform``.\n+Otherwise they are recomputed each time, which can be costly. The result is always\n+dense, even if ``X`` is sparse.\n+\n+Here a small code example which illustrates how to use the inverse transform\n+feature::\n+\n+ >>> import numpy as np\n+ >>> from sklearn.random_projection import SparseRandomProjection\n+ >>> X = np.random.rand(100, 10000)\n+ >>> transformer = SparseRandomProjection(\n+ ... compute_inverse_components=True\n+ ... )\n+ ...\n+ >>> X_new = transformer.fit_transform(X)\n+ >>> X_new.shape\n+ (100, 3947)\n+ >>> X_new_inversed = transformer.inverse_transform(X_new)\n+ >>> X_new_inversed.shape\n+ (100, 10000)\n+ >>> X_new_again = transformer.transform(X_new_inversed)\n+ >>> np.allclose(X_new, X_new_again)\n+ True\n" }, { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 5030ed8faa4a1..e66640cfd2d21 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -791,6 +791,14 @@ Changelog\n :class:`random_projection.GaussianRandomProjection` preserves dtype for\n `numpy.float32`. :pr:`<PRID>` by :user:`<NAME>`.\n \n+- |Enhancement| Adds an :meth:`inverse_transform` method and a\n+ `compute_inverse_transform` parameter to all transformers in the\n+ :mod:`~sklearn.random_projection` module:\n+ :class:`~sklearn.random_projection.GaussianRandomProjection` and\n+ :class:`~sklearn.random_projection.SparseRandomProjection`. When the parameter is set\n+ to True, the pseudo-inverse of the components is computed during `fit` and stored as\n+ `inverse_components_`. :pr:`<PRID>` by `Aurélien Geron <ageron>`.\n+\n - |API| Adds :term:`get_feature_names_out` to all transformers in the\n :mod:`~sklearn.random_projection` module:\n :class:`~sklearn.random_projection.GaussianRandomProjection` and\n" } ]
diff --git a/doc/modules/random_projection.rst b/doc/modules/random_projection.rst index adb2d53bd14d6..7d3341f0244bb 100644 --- a/doc/modules/random_projection.rst +++ b/doc/modules/random_projection.rst @@ -160,3 +160,42 @@ projection transformer:: In Proceedings of the 12th ACM SIGKDD international conference on Knowledge discovery and data mining (KDD '06). ACM, New York, NY, USA, 287-296. + + +.. _random_projection_inverse_transform: + +Inverse Transform +================= +The random projection transformers have ``compute_inverse_components`` parameter. When +set to True, after creating the random ``components_`` matrix during fitting, +the transformer computes the pseudo-inverse of this matrix and stores it as +``inverse_components_``. The ``inverse_components_`` matrix has shape +:math:`n_{features} \times n_{components}`, and it is always a dense matrix, +regardless of whether the components matrix is sparse or dense. So depending on +the number of features and components, it may use a lot of memory. + +When the ``inverse_transform`` method is called, it computes the product of the +input ``X`` and the transpose of the inverse components. If the inverse components have +been computed during fit, they are reused at each call to ``inverse_transform``. +Otherwise they are recomputed each time, which can be costly. The result is always +dense, even if ``X`` is sparse. + +Here a small code example which illustrates how to use the inverse transform +feature:: + + >>> import numpy as np + >>> from sklearn.random_projection import SparseRandomProjection + >>> X = np.random.rand(100, 10000) + >>> transformer = SparseRandomProjection( + ... compute_inverse_components=True + ... ) + ... + >>> X_new = transformer.fit_transform(X) + >>> X_new.shape + (100, 3947) + >>> X_new_inversed = transformer.inverse_transform(X_new) + >>> X_new_inversed.shape + (100, 10000) + >>> X_new_again = transformer.transform(X_new_inversed) + >>> np.allclose(X_new, X_new_again) + True diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 5030ed8faa4a1..e66640cfd2d21 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -791,6 +791,14 @@ Changelog :class:`random_projection.GaussianRandomProjection` preserves dtype for `numpy.float32`. :pr:`<PRID>` by :user:`<NAME>`. +- |Enhancement| Adds an :meth:`inverse_transform` method and a + `compute_inverse_transform` parameter to all transformers in the + :mod:`~sklearn.random_projection` module: + :class:`~sklearn.random_projection.GaussianRandomProjection` and + :class:`~sklearn.random_projection.SparseRandomProjection`. When the parameter is set + to True, the pseudo-inverse of the components is computed during `fit` and stored as + `inverse_components_`. :pr:`<PRID>` by `Aurélien Geron <ageron>`. + - |API| Adds :term:`get_feature_names_out` to all transformers in the :mod:`~sklearn.random_projection` module: :class:`~sklearn.random_projection.GaussianRandomProjection` and
scikit-learn/scikit-learn
scikit-learn__scikit-learn-21026
https://github.com/scikit-learn/scikit-learn/pull/21026
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 9d9cf3c95b450..87ffc36d342fa 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -53,6 +53,19 @@ Changelog message when the solver does not support sparse matrices with int64 indices. :pr:`21093` by `Tom Dupre la Tour`_. +:mod:`sklearn.model_selection` +.............................. + +- |Enhancement| raise an error during cross-validation when the fits for all the + splits failed. Similarly raise an error during grid-search when the fits for + all the models and all the splits failed. :pr:`21026` by :user:`Loïc Estève <lesteve>`. + +:mod:`sklearn.pipeline` +....................... + +- |Enhancement| Added support for "passthrough" in :class:`FeatureUnion`. + Setting a transformer to "passthrough" will pass the features unchanged. + :pr:`20860` by :user:`Shubhraneel Pal <shubhraneel>`. :mod:`sklearn.utils` .................... @@ -69,13 +82,6 @@ Changelog :pr:`20880` by :user:`Guillaume Lemaitre <glemaitre>` and :user:`András Simon <simonandras>`. -:mod:`sklearn.pipeline` -....................... - -- |Enhancement| Added support for "passthrough" in :class:`FeatureUnion`. - Setting a transformer to "passthrough" will pass the features unchanged. - :pr:`20860` by :user:`Shubhraneel Pal <shubhraneel>`. - Code and Documentation Contributors ----------------------------------- diff --git a/sklearn/model_selection/_search.py b/sklearn/model_selection/_search.py index c13e5b6643ce1..b5e0a52e238fc 100644 --- a/sklearn/model_selection/_search.py +++ b/sklearn/model_selection/_search.py @@ -31,7 +31,7 @@ from ._validation import _aggregate_score_dicts from ._validation import _insert_error_scores from ._validation import _normalize_score_results -from ._validation import _warn_about_fit_failures +from ._validation import _warn_or_raise_about_fit_failures from ..exceptions import NotFittedError from joblib import Parallel from ..utils import check_random_state @@ -865,7 +865,7 @@ def evaluate_candidates(candidate_params, cv=None, more_results=None): "splits, got {}".format(n_splits, len(out) // n_candidates) ) - _warn_about_fit_failures(out, self.error_score) + _warn_or_raise_about_fit_failures(out, self.error_score) # For callable self.scoring, the return type is only know after # calling. If the return type is a dictionary, the error scores diff --git a/sklearn/model_selection/_validation.py b/sklearn/model_selection/_validation.py index 760418b7d8f54..2f8566d80533e 100644 --- a/sklearn/model_selection/_validation.py +++ b/sklearn/model_selection/_validation.py @@ -30,7 +30,7 @@ from ..utils.metaestimators import _safe_split from ..metrics import check_scoring from ..metrics._scorer import _check_multimetric_scoring, _MultimetricScorer -from ..exceptions import FitFailedWarning, NotFittedError +from ..exceptions import FitFailedWarning from ._split import check_cv from ..preprocessing import LabelEncoder @@ -283,7 +283,7 @@ def cross_validate( for train, test in cv.split(X, y, groups) ) - _warn_about_fit_failures(results, error_score) + _warn_or_raise_about_fit_failures(results, error_score) # For callabe scoring, the return type is only know after calling. If the # return type is a dictionary, the error scores can now be inserted with @@ -327,9 +327,6 @@ def _insert_error_scores(results, error_score): elif successful_score is None: successful_score = result["test_scores"] - if successful_score is None: - raise NotFittedError("All estimators failed to fit") - if isinstance(successful_score, dict): formatted_error = {name: error_score for name in successful_score} for i in failed_indices: @@ -347,7 +344,7 @@ def _normalize_score_results(scores, scaler_score_key="score"): return {scaler_score_key: scores} -def _warn_about_fit_failures(results, error_score): +def _warn_or_raise_about_fit_failures(results, error_score): fit_errors = [ result["fit_error"] for result in results if result["fit_error"] is not None ] @@ -361,15 +358,25 @@ def _warn_about_fit_failures(results, error_score): for error, n in fit_errors_counter.items() ) - some_fits_failed_message = ( - f"\n{num_failed_fits} fits failed out of a total of {num_fits}.\n" - "The score on these train-test partitions for these parameters" - f" will be set to {error_score}.\n" - "If these failures are not expected, you can try to debug them " - "by setting error_score='raise'.\n\n" - f"Below are more details about the failures:\n{fit_errors_summary}" - ) - warnings.warn(some_fits_failed_message, FitFailedWarning) + if num_failed_fits == num_fits: + all_fits_failed_message = ( + f"\nAll the {num_fits} fits failed.\n" + "It is is very likely that your model is misconfigured.\n" + "You can try to debug the error by setting error_score='raise'.\n\n" + f"Below are more details about the failures:\n{fit_errors_summary}" + ) + raise ValueError(all_fits_failed_message) + + else: + some_fits_failed_message = ( + f"\n{num_failed_fits} fits failed out of a total of {num_fits}.\n" + "The score on these train-test partitions for these parameters" + f" will be set to {error_score}.\n" + "If these failures are not expected, you can try to debug them " + "by setting error_score='raise'.\n\n" + f"Below are more details about the failures:\n{fit_errors_summary}" + ) + warnings.warn(some_fits_failed_message, FitFailedWarning) def cross_val_score(
diff --git a/sklearn/model_selection/tests/test_search.py b/sklearn/model_selection/tests/test_search.py index 6960a17fb629b..df54c5a51afb4 100644 --- a/sklearn/model_selection/tests/test_search.py +++ b/sklearn/model_selection/tests/test_search.py @@ -29,7 +29,6 @@ from sklearn.base import BaseEstimator, ClassifierMixin from sklearn.base import is_classifier -from sklearn.exceptions import NotFittedError from sklearn.datasets import make_classification from sklearn.datasets import make_blobs from sklearn.datasets import make_multilabel_classification @@ -1628,6 +1627,27 @@ def get_cand_scores(i): assert gs.best_index_ != clf.FAILING_PARAMETER +def test_grid_search_classifier_all_fits_fail(): + X, y = make_classification(n_samples=20, n_features=10, random_state=0) + + clf = FailingClassifier() + + gs = GridSearchCV( + clf, + [{"parameter": [FailingClassifier.FAILING_PARAMETER] * 3}], + error_score=0.0, + ) + + warning_message = re.compile( + "All the 15 fits failed.+" + "15 fits failed with the following error.+ValueError.+Failing classifier failed" + " as required", + flags=re.DOTALL, + ) + with pytest.raises(ValueError, match=warning_message): + gs.fit(X, y) + + def test_grid_search_failing_classifier_raise(): # GridSearchCV with on_error == 'raise' raises the error @@ -2130,7 +2150,7 @@ def custom_scorer(est, X, y): assert_allclose(gs.cv_results_["mean_test_acc"], [1, 1, 0.1]) -def test_callable_multimetric_clf_all_fails(): +def test_callable_multimetric_clf_all_fits_fail(): # Warns and raises when all estimator fails to fit. def custom_scorer(est, X, y): return {"acc": 1} @@ -2141,16 +2161,20 @@ def custom_scorer(est, X, y): gs = GridSearchCV( clf, - [{"parameter": [2, 2, 2]}], + [{"parameter": [FailingClassifier.FAILING_PARAMETER] * 3}], scoring=custom_scorer, refit=False, error_score=0.1, ) - with pytest.warns( - FitFailedWarning, - match="15 fits failed.+total of 15", - ), pytest.raises(NotFittedError, match="All estimators failed to fit"): + individual_fit_error_message = "ValueError: Failing classifier failed as required" + error_message = re.compile( + "All the 15 fits failed.+your model is misconfigured.+" + f"{individual_fit_error_message}", + flags=re.DOTALL, + ) + + with pytest.raises(ValueError, match=error_message): gs.fit(X, y) diff --git a/sklearn/model_selection/tests/test_split.py b/sklearn/model_selection/tests/test_split.py index af8338792ad73..765cf4eefa7de 100644 --- a/sklearn/model_selection/tests/test_split.py +++ b/sklearn/model_selection/tests/test_split.py @@ -1774,7 +1774,7 @@ def test_nested_cv(): LeaveOneOut(), GroupKFold(n_splits=3), StratifiedKFold(), - StratifiedGroupKFold(), + StratifiedGroupKFold(n_splits=3), StratifiedShuffleSplit(n_splits=3, random_state=0), ] diff --git a/sklearn/model_selection/tests/test_validation.py b/sklearn/model_selection/tests/test_validation.py index 215ceb5877669..a66c6ae653a6f 100644 --- a/sklearn/model_selection/tests/test_validation.py +++ b/sklearn/model_selection/tests/test_validation.py @@ -2130,38 +2130,66 @@ def test_fit_and_score_working(): assert result["parameters"] == fit_and_score_kwargs["parameters"] +class DataDependentFailingClassifier(BaseEstimator): + def __init__(self, max_x_value=None): + self.max_x_value = max_x_value + + def fit(self, X, y=None): + num_values_too_high = (X > self.max_x_value).sum() + if num_values_too_high: + raise ValueError( + f"Classifier fit failed with {num_values_too_high} values too high" + ) + + def score(self, X=None, Y=None): + return 0.0 + + @pytest.mark.parametrize("error_score", [np.nan, 0]) -def test_cross_validate_failing_fits_warnings(error_score): +def test_cross_validate_some_failing_fits_warning(error_score): # Create a failing classifier to deliberately fail - failing_clf = FailingClassifier(FailingClassifier.FAILING_PARAMETER) + failing_clf = DataDependentFailingClassifier(max_x_value=8) # dummy X data X = np.arange(1, 10) y = np.ones(9) - # fit_and_score_args = [failing_clf, X, None, dict(), None, None, 0, None, None] # passing error score to trigger the warning message cross_validate_args = [failing_clf, X, y] - cross_validate_kwargs = {"cv": 7, "error_score": error_score} + cross_validate_kwargs = {"cv": 3, "error_score": error_score} # check if the warning message type is as expected + + individual_fit_error_message = ( + "ValueError: Classifier fit failed with 1 values too high" + ) warning_message = re.compile( - "7 fits failed.+total of 7.+The score on these" + "2 fits failed.+total of 3.+The score on these" " train-test partitions for these parameters will be set to" - f" {cross_validate_kwargs['error_score']}.", + f" {cross_validate_kwargs['error_score']}.+{individual_fit_error_message}", flags=re.DOTALL, ) with pytest.warns(FitFailedWarning, match=warning_message): cross_validate(*cross_validate_args, **cross_validate_kwargs) - # since we're using FailingClassfier, our error will be the following - error_message = "ValueError: Failing classifier failed as required" - # check traceback is included - warning_message = re.compile( - "The score on these train-test partitions for these parameters will be set" - f" to {cross_validate_kwargs['error_score']}.+{error_message}", - re.DOTALL, [email protected]("error_score", [np.nan, 0]) +def test_cross_validate_all_failing_fits_error(error_score): + # Create a failing classifier to deliberately fail + failing_clf = FailingClassifier(FailingClassifier.FAILING_PARAMETER) + # dummy X data + X = np.arange(1, 10) + y = np.ones(9) + + cross_validate_args = [failing_clf, X, y] + cross_validate_kwargs = {"cv": 7, "error_score": error_score} + + individual_fit_error_message = "ValueError: Failing classifier failed as required" + error_message = re.compile( + "All the 7 fits failed.+your model is misconfigured.+" + f"{individual_fit_error_message}", + flags=re.DOTALL, ) - with pytest.warns(FitFailedWarning, match=warning_message): + + with pytest.raises(ValueError, match=error_message): cross_validate(*cross_validate_args, **cross_validate_kwargs)
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 9d9cf3c95b450..87ffc36d342fa 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -53,6 +53,19 @@ Changelog\n message when the solver does not support sparse matrices with int64 indices.\n :pr:`21093` by `Tom Dupre la Tour`_.\n \n+:mod:`sklearn.model_selection`\n+..............................\n+\n+- |Enhancement| raise an error during cross-validation when the fits for all the\n+ splits failed. Similarly raise an error during grid-search when the fits for\n+ all the models and all the splits failed. :pr:`21026` by :user:`Loïc Estève <lesteve>`.\n+\n+:mod:`sklearn.pipeline`\n+.......................\n+\n+- |Enhancement| Added support for \"passthrough\" in :class:`FeatureUnion`.\n+ Setting a transformer to \"passthrough\" will pass the features unchanged.\n+ :pr:`20860` by :user:`Shubhraneel Pal <shubhraneel>`.\n \n :mod:`sklearn.utils`\n ....................\n@@ -69,13 +82,6 @@ Changelog\n :pr:`20880` by :user:`Guillaume Lemaitre <glemaitre>`\n and :user:`András Simon <simonandras>`.\n \n-:mod:`sklearn.pipeline`\n-.......................\n-\n-- |Enhancement| Added support for \"passthrough\" in :class:`FeatureUnion`.\n- Setting a transformer to \"passthrough\" will pass the features unchanged.\n- :pr:`20860` by :user:`Shubhraneel Pal <shubhraneel>`.\n-\n Code and Documentation Contributors\n -----------------------------------\n \n" } ]
1.01
d152b1e6e2a02e5bf725b41ecd63884d7d957cee
[ "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedGroupKFold-6-True]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_predict_proba_shape", "sklearn/model_selection/tests/test_search.py::test_search_default_iid[GridSearchCV-specialized_params0]", "sklearn/model_selection/tests/test_search.py::test_search_cv_pairwise_property_delegated_to_base_estimator[True]", "sklearn/model_selection/tests/test_split.py::test_stratified_group_kfold_against_group_kfold[5-cls_distr2]", "sklearn/model_selection/tests/test_search.py::test_searchcv_raise_warning_with_non_finite_score[GridSearchCV-specialized_params0-False]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv20-False]", "sklearn/model_selection/tests/test_search.py::test_X_as_list", "sklearn/model_selection/tests/test_split.py::test_stratified_group_kfold_against_group_kfold[70-cls_distr2]", "sklearn/model_selection/tests/test_split.py::test_kfold_no_shuffle", "sklearn/model_selection/tests/test_search.py::test_search_cv_using_minimal_compatible_estimator[MinimalClassifier-GridSearchCV]", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[True-True-0]", "sklearn/model_selection/tests/test_split.py::test_repeated_cv_value_errors", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv21-False]", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[False-False-nan]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_default_test_size[0.8-8-2]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes1[0.8--0.2]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedKFold-4-False]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes2[-10-0.8]", "sklearn/model_selection/tests/test_search.py::test_callable_single_metric_same_as_single_string", "sklearn/model_selection/tests/test_search.py::test_pickle", "sklearn/model_selection/tests/test_split.py::test_check_cv", "sklearn/model_selection/tests/test_split.py::test_shufflesplit_errors[0.1-0.95]", "sklearn/model_selection/tests/test_split.py::test_2d_y", "sklearn/model_selection/tests/test_split.py::test_stratifiedshufflesplit_list_input", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_invalid_scoring_param", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[True-False-0]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score", "sklearn/model_selection/tests/test_validation.py::test_permutation_test_score_allow_nans", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_label_invariance[StratifiedKFold-6-True]", "sklearn/model_selection/tests/test_validation.py::test_fit_and_score_verbosity[True-scorer1-3-split_prg1-cdt_prg1-\\\\[CV 2/3\\\\] END sc1: \\\\(train=3.421, test=3.421\\\\) sc2: \\\\(train=3.421, test=3.421\\\\) total time= 0.\\\\ds]", "sklearn/model_selection/tests/test_split.py::test_time_series_gap", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv0-True]", "sklearn/model_selection/tests/test_search.py::test_no_refit", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_allow_nans", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_with_method_multilabel_ovr", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_label_invariance[StratifiedGroupKFold-6-False]", "sklearn/model_selection/tests/test_validation.py::test_cross_validate", "sklearn/model_selection/tests/test_search.py::test_param_sampler", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_label_invariance[StratifiedGroupKFold-4-True]", "sklearn/model_selection/tests/test_split.py::test_stratified_group_kfold_against_group_kfold[70-cls_distr3]", "sklearn/model_selection/tests/test_split.py::test_cross_validator_with_default_params", "sklearn/model_selection/tests/test_split.py::test_stratified_group_kfold_against_group_kfold[5-cls_distr3]", "sklearn/model_selection/tests/test_validation.py::test_callable_multimetric_confusion_matrix_cross_validate", "sklearn/model_selection/tests/test_split.py::test_stratified_group_kfold_homogeneous_groups[y1-groups1-expected1]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_decision_function_shape", "sklearn/model_selection/tests/test_split.py::test_shufflesplit_reproducible", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_incremental_learning_unsupervised", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv23-False]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv13-True]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedGroupKFold-5-False]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedGroupKFold-7-False]", "sklearn/model_selection/tests/test_split.py::test_predefinedsplit_with_kfold_split", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes1[1.0-0.8]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_label_invariance[StratifiedKFold-7-False]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_with_score_func_classification", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_label_invariance[StratifiedGroupKFold-4-False]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv26-False]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedKFold-6-False]", "sklearn/model_selection/tests/test_search.py::test_search_cv_using_minimal_compatible_estimator[MinimalClassifier-RandomizedSearchCV]", "sklearn/model_selection/tests/test_split.py::test_stratifiedkfold_balance[StratifiedGroupKFold]", "sklearn/model_selection/tests/test_validation.py::test_fit_and_score_verbosity[False-three_params_scorer-2-split_prg0-cdt_prg0-\\\\[CV\\\\] END .................................................... total time= 0.\\\\ds]", "sklearn/model_selection/tests/test_split.py::test_kfold_can_detect_dependent_samples_on_digits", "sklearn/model_selection/tests/test_split.py::test_stratified_group_kfold_against_group_kfold[30-cls_distr1]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedGroupKFold-8-True]", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_fit_params", "sklearn/model_selection/tests/test_search.py::test_grid_search_no_score", "sklearn/model_selection/tests/test_split.py::test_shuffle_split_default_test_size[None-9-1-StratifiedShuffleSplit]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_errors", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_sparse_prediction", "sklearn/model_selection/tests/test_split.py::test_shuffle_split", "sklearn/model_selection/tests/test_search.py::test_grid_search_pipeline_steps", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_incremental_learning_not_possible", "sklearn/model_selection/tests/test_split.py::test_train_test_split_32bit_overflow", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv19-False]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_unbalanced", "sklearn/model_selection/tests/test_split.py::test_random_state_shuffle_false[StratifiedKFold]", "sklearn/model_selection/tests/test_search.py::test_searchcv_raise_warning_with_non_finite_score[RandomizedSearchCV-specialized_params1-False]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv22-False]", "sklearn/model_selection/tests/test_search.py::test_search_cv_score_samples_method[search_cv1]", "sklearn/model_selection/tests/test_search.py::test_empty_cv_iterator_error", "sklearn/model_selection/tests/test_split.py::test_shuffle_kfold", "sklearn/model_selection/tests/test_split.py::test_repeated_stratified_kfold_determinstic_split", "sklearn/model_selection/tests/test_search.py::test_y_as_list", "sklearn/model_selection/tests/test_search.py::test_scalar_fit_param_compat[RandomizedSearchCV-param_search1]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_no_shuffle", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_label_invariance[StratifiedKFold-4-False]", "sklearn/model_selection/tests/test_split.py::test_group_shuffle_split_default_test_size[None-8-2]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv2-True]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedGroupKFold-6-False]", "sklearn/model_selection/tests/test_split.py::test_shuffle_kfold_stratifiedkfold_reproducibility[StratifiedGroupKFold]", "sklearn/model_selection/tests/test_search.py::test_grid_search_cv_splits_consistency", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_label_invariance[StratifiedGroupKFold-7-True]", "sklearn/model_selection/tests/test_split.py::test_shufflesplit_errors[10-None]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv6-True]", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[True-False-raise]", "sklearn/model_selection/tests/test_search.py::test_refit_callable", "sklearn/model_selection/tests/test_search.py::test_grid_search_cv_results", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_class_subset", "sklearn/model_selection/tests/test_search.py::test_transform_inverse_transform_round_trip", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes2[0.8--10]", "sklearn/model_selection/tests/test_split.py::test_shuffle_kfold_stratifiedkfold_reproducibility[KFold]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_predict_groups", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedGroupKFold-9-False]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_failing_scorer[0]", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[False-True-nan]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv29-False]", "sklearn/model_selection/tests/test_search.py::test_refit_callable_multi_metric", "sklearn/model_selection/tests/test_split.py::test_train_test_split_list_input", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_many_jobs", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_fit_params", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv5-True]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedKFold-4-True]", "sklearn/model_selection/tests/test_search.py::test_grid_search_sparse", "sklearn/model_selection/tests/test_split.py::test_train_test_split_errors", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_with_score_func_regression", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_nested_estimator", "sklearn/model_selection/tests/test_split.py::test_group_shuffle_split", "sklearn/model_selection/tests/test_search.py::test_search_default_iid[RandomizedSearchCV-specialized_params1]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv3-True]", "sklearn/model_selection/tests/test_search.py::test_gridsearch_no_predict", "sklearn/model_selection/tests/test_search.py::test_grid_search_groups", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes1[-0.2-0.8]", "sklearn/model_selection/tests/test_search.py::test_gridsearch_nd", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedKFold-5-True]", "sklearn/model_selection/tests/test_search.py::test_refit_callable_out_bound[RandomizedSearchCV--1]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_pandas", "sklearn/model_selection/tests/test_split.py::test_stratified_shuffle_split_iter", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[False-False-raise]", "sklearn/model_selection/tests/test_search.py::test_validate_parameter_input[input2-TypeError-Parameter.* value is not iterable .*\\\\(key='foo', value=0\\\\)-klass1]", "sklearn/model_selection/tests/test_search.py::test_search_cv_pairwise_property_equivalence_of_precomputed", "sklearn/model_selection/tests/test_split.py::test_stratified_group_kfold_against_group_kfold[5-cls_distr1]", "sklearn/model_selection/tests/test_split.py::test_kfold_indices", "sklearn/model_selection/tests/test_split.py::test_time_series_cv", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_with_shuffle", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedGroupKFold-10-True]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_precomputed", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes2[11-0.8]", "sklearn/model_selection/tests/test_validation.py::test_permutation_test_score_fit_params", "sklearn/model_selection/tests/test_search.py::test_SearchCV_with_fit_params[GridSearchCV]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv15-True]", "sklearn/model_selection/tests/test_split.py::test_stratified_group_kfold_trivial", "sklearn/model_selection/tests/test_search.py::test_refit_callable_out_bound[GridSearchCV--1]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_pandas", "sklearn/model_selection/tests/test_search.py::test_random_search_cv_results", "sklearn/model_selection/tests/test_search.py::test_search_train_scores_set_to_false", "sklearn/model_selection/tests/test_search.py::test_custom_run_search", "sklearn/model_selection/tests/test_search.py::test_callable_multimetric_error_failing_clf", "sklearn/model_selection/tests/test_split.py::test_random_state_shuffle_false[StratifiedGroupKFold]", "sklearn/model_selection/tests/test_search.py::test_refit_callable_out_bound[GridSearchCV-2]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_label_invariance[StratifiedKFold-7-True]", "sklearn/model_selection/tests/test_split.py::test_shuffle_split_empty_trainset[ShuffleSplit]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_mock_pandas", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes1[0.8-1.2]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv9-True]", "sklearn/model_selection/tests/test_search.py::test_grid_search_cv_results_multimetric", "sklearn/model_selection/tests/test_split.py::test_shufflesplit_errors[8-3]", "sklearn/model_selection/tests/test_search.py::test_grid_search_allows_nans", "sklearn/model_selection/tests/test_split.py::test_leave_one_p_group_out_error_on_fewer_number_of_groups", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_label_invariance[StratifiedKFold-6-False]", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_with_boolean_indices", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv8-True]", "sklearn/model_selection/tests/test_search.py::test_search_cv_pairwise_property_delegated_to_base_estimator[False]", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_some_failing_fits_warning[nan]", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[False-False-0]", "sklearn/model_selection/tests/test_split.py::test_repeated_cv_repr[RepeatedKFold]", "sklearn/model_selection/tests/test_search.py::test_search_cv_using_minimal_compatible_estimator[MinimalRegressor-GridSearchCV]", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_remove_duplicate_sample_sizes", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_failing_scorer[nan]", "sklearn/model_selection/tests/test_search.py::test_grid_search_correct_score_results", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[True-True-raise]", "sklearn/model_selection/tests/test_split.py::test_shuffle_stratifiedkfold", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[True-True-nan]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedGroupKFold-7-True]", "sklearn/model_selection/tests/test_split.py::test_train_test_split", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv14-True]", "sklearn/model_selection/tests/test_search.py::test_pandas_input", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes2[0.8-11]", "sklearn/model_selection/tests/test_search.py::test_search_cv_score_samples_error[search_cv1]", "sklearn/model_selection/tests/test_search.py::test_callable_multimetric_same_as_list_of_strings", "sklearn/model_selection/tests/test_split.py::test_stratifiedkfold_balance[StratifiedKFold]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedGroupKFold-4-False]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedKFold-9-True]", "sklearn/model_selection/tests/test_search.py::test_scalar_fit_param[GridSearchCV-param_search0]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedKFold-8-True]", "sklearn/model_selection/tests/test_split.py::test_kfold_balance", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedGroupKFold-9-True]", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_some_failing_fits_warning[0]", "sklearn/model_selection/tests/test_split.py::test_stratified_shuffle_split_respects_test_size", "sklearn/model_selection/tests/test_split.py::test_shuffle_split_empty_trainset[StratifiedShuffleSplit]", "sklearn/model_selection/tests/test_validation.py::test_validation_curve_clone_estimator", "sklearn/model_selection/tests/test_search.py::test_grid_search_error", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedKFold-8-False]", "sklearn/model_selection/tests/test_split.py::test_get_n_splits_for_repeated_stratified_kfold", "sklearn/model_selection/tests/test_split.py::test_time_series_test_size", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_pandas", "sklearn/model_selection/tests/test_split.py::test_stratified_group_kfold_against_group_kfold[30-cls_distr3]", "sklearn/model_selection/tests/test_validation.py::test_fit_and_score_verbosity[False-scorer2-10-split_prg2-cdt_prg2-\\\\[CV 2/3; 1/1\\\\] END ....... sc1: \\\\(test=3.421\\\\) sc2: \\\\(test=3.421\\\\) total time= 0.\\\\ds]", "sklearn/model_selection/tests/test_search.py::test_validate_parameter_input[input2-TypeError-Parameter.* value is not iterable .*\\\\(key='foo', value=0\\\\)-ParameterGrid]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_sparse_fit_params", "sklearn/model_selection/tests/test_search.py::test_n_features_in", "sklearn/model_selection/tests/test_search.py::test_search_cv_score_samples_error[search_cv0]", "sklearn/model_selection/tests/test_search.py::test_callable_multimetric_error_on_invalid_key", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_batch_and_incremental_learning_are_equal", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_score_func", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_failing_scorer[raise]", "sklearn/model_selection/tests/test_split.py::test_nested_cv", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_with_method", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_label_invariance[StratifiedKFold-4-True]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict", "sklearn/model_selection/tests/test_split.py::test_get_n_splits_for_repeated_kfold", "sklearn/model_selection/tests/test_search.py::test_refit_callable_out_bound[RandomizedSearchCV-2]", "sklearn/model_selection/tests/test_validation.py::test_fit_and_score_failing", "sklearn/model_selection/tests/test_search.py::test_trivial_cv_results_attr", "sklearn/model_selection/tests/test_split.py::test_shufflesplit_errors[11-None]", "sklearn/model_selection/tests/test_split.py::test_shuffle_split_default_test_size[0.8-8-2-StratifiedShuffleSplit]", "sklearn/model_selection/tests/test_search.py::test_grid_search_one_grid_point", "sklearn/model_selection/tests/test_search.py::test_search_cv__pairwise_property_delegated_to_base_estimator", "sklearn/model_selection/tests/test_split.py::test_train_test_split_default_test_size[8-8-2]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_empty_trainset", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv18-False]", "sklearn/model_selection/tests/test_validation.py::test_gridsearchcv_cross_val_predict_with_method", "sklearn/model_selection/tests/test_validation.py::test_learning_curve", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_label_invariance[StratifiedGroupKFold-7-False]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes1[0.8-0.0]", "sklearn/model_selection/tests/test_split.py::test_repeated_cv_repr[RepeatedStratifiedKFold]", "sklearn/model_selection/tests/test_search.py::test_callable_multimetric_confusion_matrix", "sklearn/model_selection/tests/test_validation.py::test_score", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv7-True]", "sklearn/model_selection/tests/test_search.py::test_scalar_fit_param[RandomizedSearchCV-param_search1]", "sklearn/model_selection/tests/test_search.py::test_refit", "sklearn/model_selection/tests/test_search.py::test_grid_search_with_multioutput_data", "sklearn/model_selection/tests/test_split.py::test_leave_group_out_changing_groups", "sklearn/model_selection/tests/test_split.py::test_build_repr", "sklearn/model_selection/tests/test_split.py::test_stratified_group_kfold_homogeneous_groups[y0-groups0-expected0]", "sklearn/model_selection/tests/test_split.py::test_stratified_group_kfold_against_group_kfold[5-cls_distr0]", "sklearn/model_selection/tests/test_search.py::test_validate_parameter_input[0-TypeError-Parameter .* is not a dict or a list \\\\(0\\\\)-ParameterGrid]", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[False-True-0]", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_incremental_learning_fit_params", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_with_method_multilabel_rf", "sklearn/model_selection/tests/test_split.py::test_time_series_max_train_size", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedGroupKFold-8-False]", "sklearn/model_selection/tests/test_search.py::test_grid_search_when_param_grid_includes_range", "sklearn/model_selection/tests/test_search.py::test_grid_search_sparse_scoring", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv12-True]", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_unsupervised", "sklearn/model_selection/tests/test_search.py::test_grid_search_failing_classifier_raise", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_input_types", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_label_invariance[StratifiedGroupKFold-6-True]", "sklearn/model_selection/tests/test_search.py::test_stochastic_gradient_loss_param", "sklearn/model_selection/tests/test_split.py::test_stratified_shuffle_split_init", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedKFold-7-True]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_mask", "sklearn/model_selection/tests/test_split.py::test_leave_one_out_empty_trainset", "sklearn/model_selection/tests/test_search.py::test_search_cv_verbose_3[False]", "sklearn/model_selection/tests/test_search.py::test_parameter_grid", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv25-False]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedKFold-10-True]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv30-False]", "sklearn/model_selection/tests/test_search.py::test_grid_search", "sklearn/model_selection/tests/test_search.py::test_searchcv_raise_warning_with_non_finite_score[GridSearchCV-specialized_params0-True]", "sklearn/model_selection/tests/test_split.py::test_group_kfold[GroupKFold]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes1[0.8-1.0]", "sklearn/model_selection/tests/test_split.py::test_group_shuffle_split_default_test_size[7-7-3]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_sparse", "sklearn/model_selection/tests/test_split.py::test_stratified_group_kfold_against_group_kfold[70-cls_distr0]", "sklearn/model_selection/tests/test_search.py::test_search_cv_results_rank_tie_breaking", "sklearn/model_selection/tests/test_split.py::test_train_test_split_default_test_size[None-7-3]", "sklearn/model_selection/tests/test_search.py::test_random_search_cv_results_multimetric", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedKFold-7-False]", "sklearn/model_selection/tests/test_search.py::test_SearchCV_with_fit_params[RandomizedSearchCV]", "sklearn/model_selection/tests/test_split.py::test_stratified_shuffle_split_overlap_train_test_bug", "sklearn/model_selection/tests/test_split.py::test_stratified_group_kfold_against_group_kfold[30-cls_distr2]", "sklearn/model_selection/tests/test_split.py::test_stratified_group_kfold_against_group_kfold[70-cls_distr1]", "sklearn/model_selection/tests/test_split.py::test_leave_one_p_group_out", "sklearn/model_selection/tests/test_validation.py::test_score_memmap", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedGroupKFold-4-True]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes1[1.2-0.8]", "sklearn/model_selection/tests/test_search.py::test_random_search_bad_cv", "sklearn/model_selection/tests/test_split.py::test_repeated_kfold_determinstic_split", "sklearn/model_selection/tests/test_split.py::test_stratified_shuffle_split_multilabel", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv27-False]", "sklearn/model_selection/tests/test_search.py::test_search_cv_using_minimal_compatible_estimator[MinimalRegressor-RandomizedSearchCV]", "sklearn/model_selection/tests/test_split.py::test_shuffle_split_empty_trainset[GroupShuffleSplit]", "sklearn/model_selection/tests/test_search.py::test_grid_search_precomputed_kernel_error_nonsquare", "sklearn/model_selection/tests/test_split.py::test_shuffle_split_default_test_size[0.8-8-2-ShuffleSplit]", "sklearn/model_selection/tests/test_search.py::test_search_cv_results_none_param", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv4-True]", "sklearn/model_selection/tests/test_search.py::test__custom_fit_no_run_search", "sklearn/model_selection/tests/test_split.py::test_shufflesplit_errors[2.0-None]", "sklearn/model_selection/tests/test_split.py::test_shuffle_split_default_test_size[8-8-2-StratifiedShuffleSplit]", "sklearn/model_selection/tests/test_search.py::test_predict_proba_disabled", "sklearn/model_selection/tests/test_validation.py::test_validation_curve_cv_splits_consistency", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_verbose", "sklearn/model_selection/tests/test_search.py::test_grid_search_bad_param_grid", "sklearn/model_selection/tests/test_search.py::test_search_cv_timing", "sklearn/model_selection/tests/test_split.py::test_cv_iterable_wrapper", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_y_none", "sklearn/model_selection/tests/test_validation.py::test_permutation_test_score_pandas", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv1-True]", "sklearn/model_selection/tests/test_split.py::test_shuffle_split_default_test_size[8-8-2-ShuffleSplit]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedKFold-6-True]", "sklearn/model_selection/tests/test_validation.py::test_fit_and_score_working", "sklearn/model_selection/tests/test_search.py::test_search_cv_verbose_3[True]", "sklearn/model_selection/tests/test_split.py::test_shuffle_kfold_stratifiedkfold_reproducibility[StratifiedKFold]", "sklearn/model_selection/tests/test_split.py::test_stratified_shuffle_split_even", "sklearn/model_selection/tests/test_split.py::test_stratified_group_kfold_against_group_kfold[30-cls_distr0]", "sklearn/model_selection/tests/test_validation.py::test_permutation_score", "sklearn/model_selection/tests/test_search.py::test_validate_parameter_input[input1-TypeError-Parameter .* is not a dict \\\\(0\\\\)-klass1]", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_n_sample_range_out_of_bounds", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_with_method_rare_class", "sklearn/model_selection/tests/test_split.py::test_shuffle_split_default_test_size[None-9-1-ShuffleSplit]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedGroupKFold-5-True]", "sklearn/model_selection/tests/test_search.py::test_searchcv_raise_warning_with_non_finite_score[RandomizedSearchCV-specialized_params1-True]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv17-False]", "sklearn/model_selection/tests/test_split.py::test_stratified_shuffle_split_multilabel_many_labels", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv10-True]", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_incremental_learning", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv24-False]", "sklearn/model_selection/tests/test_split.py::test_group_shuffle_split_default_test_size[0.7-7-3]", "sklearn/model_selection/tests/test_split.py::test_random_state_shuffle_false[KFold]", "sklearn/model_selection/tests/test_search.py::test_unsupervised_grid_search", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes2[0-0.8]", "sklearn/model_selection/tests/test_validation.py::test_validation_curve_fit_params", "sklearn/model_selection/tests/test_search.py::test_grid_search_precomputed_kernel", "sklearn/model_selection/tests/test_split.py::test_leave_p_out_empty_trainset", "sklearn/model_selection/tests/test_validation.py::test_check_is_permutation", "sklearn/model_selection/tests/test_search.py::test_validate_parameter_input[input1-TypeError-Parameter .* is not a dict \\\\(0\\\\)-ParameterGrid]", "sklearn/model_selection/tests/test_search.py::test_grid_search_failing_classifier", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedGroupKFold-10-False]", "sklearn/model_selection/tests/test_split.py::test_kfold_valueerrors", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv28-False]", "sklearn/model_selection/tests/test_search.py::test_classes__property", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_multilabel", "sklearn/model_selection/tests/test_split.py::test_shufflesplit_errors[None-1j]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedKFold-5-False]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_predict_log_proba_shape", "sklearn/model_selection/tests/test_search.py::test_scalar_fit_param_compat[GridSearchCV-param_search0]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_with_method_multilabel_rf_rare_class", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv11-True]", "sklearn/model_selection/tests/test_search.py::test_refit_callable_invalid_type", "sklearn/model_selection/tests/test_split.py::test_stratified_group_kfold_approximate", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes2[0.8-0]", "sklearn/model_selection/tests/test_search.py::test_validate_parameter_input[0-TypeError-Parameter .* is not a dict or a list \\\\(0\\\\)-klass1]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_allow_nans", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[True-False-nan]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv16-True]", "sklearn/model_selection/tests/test_split.py::test_group_kfold[StratifiedGroupKFold]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_method_checking", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[False-True-raise]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedKFold-9-False]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes1[0.0-0.8]", "sklearn/model_selection/tests/test_validation.py::test_validation_curve", "sklearn/model_selection/tests/test_split.py::test_shufflesplit_errors[1.0-None]", "sklearn/model_selection/tests/test_search.py::test_grid_search_score_method", "sklearn/model_selection/tests/test_search.py::test_search_cv_score_samples_method[search_cv0]", "sklearn/model_selection/tests/test_search.py::test_parameters_sampler_replacement", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedKFold-10-False]" ]
[ "sklearn/model_selection/tests/test_search.py::test_grid_search_classifier_all_fits_fail", "sklearn/model_selection/tests/test_search.py::test_callable_multimetric_clf_all_fits_fail", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_all_failing_fits_error[0]", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_all_failing_fits_error[nan]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 9d9cf3c95b450..87ffc36d342fa 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -53,6 +53,19 @@ Changelog\n message when the solver does not support sparse matrices with int64 indices.\n :pr:`<PRID>` by `<NAME>`_.\n \n+:mod:`sklearn.model_selection`\n+..............................\n+\n+- |Enhancement| raise an error during cross-validation when the fits for all the\n+ splits failed. Similarly raise an error during grid-search when the fits for\n+ all the models and all the splits failed. :pr:`<PRID>` by :user:`<NAME>`.\n+\n+:mod:`sklearn.pipeline`\n+.......................\n+\n+- |Enhancement| Added support for \"passthrough\" in :class:`FeatureUnion`.\n+ Setting a transformer to \"passthrough\" will pass the features unchanged.\n+ :pr:`<PRID>` by :user:`<NAME>`.\n \n :mod:`sklearn.utils`\n ....................\n@@ -69,13 +82,6 @@ Changelog\n :pr:`<PRID>` by :user:`<NAME>`\n and :user:`<NAME>`.\n \n-:mod:`sklearn.pipeline`\n-.......................\n-\n-- |Enhancement| Added support for \"passthrough\" in :class:`FeatureUnion`.\n- Setting a transformer to \"passthrough\" will pass the features unchanged.\n- :pr:`<PRID>` by :user:`<NAME>`.\n-\n Code and Documentation Contributors\n -----------------------------------\n \n" } ]
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 9d9cf3c95b450..87ffc36d342fa 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -53,6 +53,19 @@ Changelog message when the solver does not support sparse matrices with int64 indices. :pr:`<PRID>` by `<NAME>`_. +:mod:`sklearn.model_selection` +.............................. + +- |Enhancement| raise an error during cross-validation when the fits for all the + splits failed. Similarly raise an error during grid-search when the fits for + all the models and all the splits failed. :pr:`<PRID>` by :user:`<NAME>`. + +:mod:`sklearn.pipeline` +....................... + +- |Enhancement| Added support for "passthrough" in :class:`FeatureUnion`. + Setting a transformer to "passthrough" will pass the features unchanged. + :pr:`<PRID>` by :user:`<NAME>`. :mod:`sklearn.utils` .................... @@ -69,13 +82,6 @@ Changelog :pr:`<PRID>` by :user:`<NAME>` and :user:`<NAME>`. -:mod:`sklearn.pipeline` -....................... - -- |Enhancement| Added support for "passthrough" in :class:`FeatureUnion`. - Setting a transformer to "passthrough" will pass the features unchanged. - :pr:`<PRID>` by :user:`<NAME>`. - Code and Documentation Contributors -----------------------------------
scikit-learn/scikit-learn
scikit-learn__scikit-learn-22114
https://github.com/scikit-learn/scikit-learn/pull/22114
diff --git a/doc/tutorial/basic/tutorial.rst b/doc/tutorial/basic/tutorial.rst index 5199ad226243f..4375e4fb83e61 100644 --- a/doc/tutorial/basic/tutorial.rst +++ b/doc/tutorial/basic/tutorial.rst @@ -183,7 +183,7 @@ the last item from ``digits.data``:: SVC(C=100.0, gamma=0.001) Now you can *predict* new values. In this case, you'll predict using the last -image from ``digits.data``. By predicting, you'll determine the image from the +image from ``digits.data``. By predicting, you'll determine the image from the training set that best matches the last image. @@ -216,7 +216,7 @@ Type casting Unless otherwise specified, input will be cast to ``float64``:: >>> import numpy as np - >>> from sklearn import random_projection + >>> from sklearn import kernel_approximation >>> rng = np.random.RandomState(0) >>> X = rng.rand(10, 2000) @@ -224,7 +224,7 @@ Unless otherwise specified, input will be cast to ``float64``:: >>> X.dtype dtype('float32') - >>> transformer = random_projection.GaussianRandomProjection() + >>> transformer = kernel_approximation.RBFSampler() >>> X_new = transformer.fit_transform(X) >>> X_new.dtype dtype('float64') diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 5d49a6fd281c7..bab7b3e33f850 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -385,6 +385,10 @@ Changelog :mod:`sklearn.random_projection` ................................ +- |Enhancement| :class:`random_projection.SparseRandomProjection` and + :class:`random_projection.GaussianRandomProjection` preserves dtype for + `numpy.float32`. :pr:`22114` by :user:`Takeshi Oura <takoika>`. + - |API| Adds :term:`get_feature_names_out` to all transformers in the :mod:`~sklearn.random_projection` module: :class:`~sklearn.random_projection.GaussianRandomProjection` and diff --git a/sklearn/random_projection.py b/sklearn/random_projection.py index 79ebe46042379..f346cdc4630b3 100644 --- a/sklearn/random_projection.py +++ b/sklearn/random_projection.py @@ -347,7 +347,9 @@ def fit(self, X, y=None): self : object BaseRandomProjection class instance. """ - X = self._validate_data(X, accept_sparse=["csr", "csc"]) + X = self._validate_data( + X, accept_sparse=["csr", "csc"], dtype=[np.float64, np.float32] + ) n_samples, n_features = X.shape @@ -387,7 +389,9 @@ def fit(self, X, y=None): self.n_components_ = self.n_components # Generate a projection matrix of size [n_components, n_features] - self.components_ = self._make_random_matrix(self.n_components_, n_features) + self.components_ = self._make_random_matrix( + self.n_components_, n_features + ).astype(X.dtype, copy=False) # Check contract assert self.components_.shape == (self.n_components_, n_features), ( @@ -411,7 +415,9 @@ def transform(self, X): Projected array. """ check_is_fitted(self) - X = self._validate_data(X, accept_sparse=["csr", "csc"], reset=False) + X = self._validate_data( + X, accept_sparse=["csr", "csc"], reset=False, dtype=[np.float64, np.float32] + ) if X.shape[1] != self.components_.shape[1]: raise ValueError( @@ -431,6 +437,11 @@ def _n_features_out(self): """ return self.n_components + def _more_tags(self): + return { + "preserves_dtype": [np.float64, np.float32], + } + class GaussianRandomProjection(BaseRandomProjection): """Reduce dimensionality through Gaussian random projection.
diff --git a/sklearn/tests/test_random_projection.py b/sklearn/tests/test_random_projection.py index 1e894d906a3ad..a3a6b1ae2a49f 100644 --- a/sklearn/tests/test_random_projection.py +++ b/sklearn/tests/test_random_projection.py @@ -13,6 +13,8 @@ from sklearn.random_projection import SparseRandomProjection from sklearn.random_projection import GaussianRandomProjection +from sklearn.utils._testing import assert_allclose +from sklearn.utils._testing import assert_allclose_dense_sparse from sklearn.utils._testing import assert_array_equal from sklearn.utils._testing import assert_almost_equal from sklearn.utils._testing import assert_array_almost_equal @@ -373,3 +375,43 @@ def test_random_projection_feature_names_out(random_projection_cls): ) assert_array_equal(names_out, expected_names_out) + + [email protected]("random_projection_cls", all_RandomProjection) [email protected]( + "input_dtype, expected_dtype", + ( + (np.float32, np.float32), + (np.float64, np.float64), + (np.int32, np.float64), + (np.int64, np.float64), + ), +) +def test_random_projection_dtype_match( + random_projection_cls, input_dtype, expected_dtype +): + # Verify output matrix dtype + rng = np.random.RandomState(42) + X = rng.rand(25, 3000) + rp = random_projection_cls(random_state=0) + transformed = rp.fit_transform(X.astype(input_dtype)) + + assert rp.components_.dtype == expected_dtype + assert transformed.dtype == expected_dtype + + [email protected]("random_projection_cls", all_RandomProjection) +def test_random_projection_numerical_consistency(random_projection_cls): + # Verify numerical consistency among np.float32 and np.float64 + atol = 1e-5 + rng = np.random.RandomState(42) + X = rng.rand(25, 3000) + rp_32 = random_projection_cls(random_state=0) + rp_64 = random_projection_cls(random_state=0) + + projection_32 = rp_32.fit_transform(X.astype(np.float32)) + projection_64 = rp_64.fit_transform(X.astype(np.float64)) + + assert_allclose(projection_64, projection_32, atol=atol) + + assert_allclose_dense_sparse(rp_32.components_, rp_64.components_)
[ { "path": "doc/tutorial/basic/tutorial.rst", "old_path": "a/doc/tutorial/basic/tutorial.rst", "new_path": "b/doc/tutorial/basic/tutorial.rst", "metadata": "diff --git a/doc/tutorial/basic/tutorial.rst b/doc/tutorial/basic/tutorial.rst\nindex 5199ad226243f..4375e4fb83e61 100644\n--- a/doc/tutorial/basic/tutorial.rst\n+++ b/doc/tutorial/basic/tutorial.rst\n@@ -183,7 +183,7 @@ the last item from ``digits.data``::\n SVC(C=100.0, gamma=0.001)\n \n Now you can *predict* new values. In this case, you'll predict using the last\n-image from ``digits.data``. By predicting, you'll determine the image from the \n+image from ``digits.data``. By predicting, you'll determine the image from the\n training set that best matches the last image.\n \n \n@@ -216,7 +216,7 @@ Type casting\n Unless otherwise specified, input will be cast to ``float64``::\n \n >>> import numpy as np\n- >>> from sklearn import random_projection\n+ >>> from sklearn import kernel_approximation\n \n >>> rng = np.random.RandomState(0)\n >>> X = rng.rand(10, 2000)\n@@ -224,7 +224,7 @@ Unless otherwise specified, input will be cast to ``float64``::\n >>> X.dtype\n dtype('float32')\n \n- >>> transformer = random_projection.GaussianRandomProjection()\n+ >>> transformer = kernel_approximation.RBFSampler()\n >>> X_new = transformer.fit_transform(X)\n >>> X_new.dtype\n dtype('float64')\n" }, { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 5d49a6fd281c7..bab7b3e33f850 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -385,6 +385,10 @@ Changelog\n :mod:`sklearn.random_projection`\n ................................\n \n+- |Enhancement| :class:`random_projection.SparseRandomProjection` and\n+ :class:`random_projection.GaussianRandomProjection` preserves dtype for\n+ `numpy.float32`. :pr:`22114` by :user:`Takeshi Oura <takoika>`.\n+\n - |API| Adds :term:`get_feature_names_out` to all transformers in the\n :mod:`~sklearn.random_projection` module:\n :class:`~sklearn.random_projection.GaussianRandomProjection` and\n" } ]
1.01
b242b9dd200cbb3f60247e523adae43a303d8122
[ "sklearn/tests/test_random_projection.py::test_random_projection_dtype_match[float64-float64-GaussianRandomProjection]", "sklearn/tests/test_random_projection.py::test_johnson_lindenstrauss_min_dim", "sklearn/tests/test_random_projection.py::test_sparse_random_projection_transformer_invalid_density[0]", "sklearn/tests/test_random_projection.py::test_random_projection_feature_names_out[GaussianRandomProjection]", "sklearn/tests/test_random_projection.py::test_sparse_random_projection_transformer_invalid_density[1.1]", "sklearn/tests/test_random_projection.py::test_invalid_jl_domain[0-0.5]", "sklearn/tests/test_random_projection.py::test_random_projection_dtype_match[int64-float64-GaussianRandomProjection]", "sklearn/tests/test_random_projection.py::test_basic_property_of_random_matrix[_gaussian_random_matrix]", "sklearn/tests/test_random_projection.py::test_try_to_transform_before_fit", "sklearn/tests/test_random_projection.py::test_random_projection_transformer_invalid_input[-10-fit_data1]", "sklearn/tests/test_random_projection.py::test_warning_n_components_greater_than_n_features", "sklearn/tests/test_random_projection.py::test_invalid_jl_domain[100-1.1]", "sklearn/tests/test_random_projection.py::test_random_projection_feature_names_out[SparseRandomProjection]", "sklearn/tests/test_random_projection.py::test_invalid_jl_domain[100--0.1]", "sklearn/tests/test_random_projection.py::test_basic_property_of_sparse_random_matrix[_sparse_random_matrix]", "sklearn/tests/test_random_projection.py::test_input_size_jl_min_dim", "sklearn/tests/test_random_projection.py::test_random_projection_numerical_consistency[GaussianRandomProjection]", "sklearn/tests/test_random_projection.py::test_works_with_sparse_data", "sklearn/tests/test_random_projection.py::test_random_projection_dtype_match[int32-float64-SparseRandomProjection]", "sklearn/tests/test_random_projection.py::test_random_projection_embedding_quality", "sklearn/tests/test_random_projection.py::test_random_projection_transformer_invalid_input[auto-fit_data0]", "sklearn/tests/test_random_projection.py::test_random_projection_dtype_match[float64-float64-SparseRandomProjection]", "sklearn/tests/test_random_projection.py::test_random_projection_dtype_match[int32-float64-GaussianRandomProjection]", "sklearn/tests/test_random_projection.py::test_sparse_random_matrix", "sklearn/tests/test_random_projection.py::test_random_projection_numerical_consistency[SparseRandomProjection]", "sklearn/tests/test_random_projection.py::test_SparseRandomProj_output_representation", "sklearn/tests/test_random_projection.py::test_sparse_random_projection_transformer_invalid_density[-0.1]", "sklearn/tests/test_random_projection.py::test_random_projection_dtype_match[int64-float64-SparseRandomProjection]", "sklearn/tests/test_random_projection.py::test_gaussian_random_matrix", "sklearn/tests/test_random_projection.py::test_basic_property_of_random_matrix[_sparse_random_matrix]", "sklearn/tests/test_random_projection.py::test_invalid_jl_domain[100-0.0]", "sklearn/tests/test_random_projection.py::test_too_many_samples_to_find_a_safe_embedding", "sklearn/tests/test_random_projection.py::test_correct_RandomProjection_dimensions_embedding" ]
[ "sklearn/tests/test_random_projection.py::test_random_projection_dtype_match[float32-float32-GaussianRandomProjection]", "sklearn/tests/test_random_projection.py::test_random_projection_dtype_match[float32-float32-SparseRandomProjection]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/tutorial/basic/tutorial.rst", "old_path": "a/doc/tutorial/basic/tutorial.rst", "new_path": "b/doc/tutorial/basic/tutorial.rst", "metadata": "diff --git a/doc/tutorial/basic/tutorial.rst b/doc/tutorial/basic/tutorial.rst\nindex 5199ad226243f..4375e4fb83e61 100644\n--- a/doc/tutorial/basic/tutorial.rst\n+++ b/doc/tutorial/basic/tutorial.rst\n@@ -183,7 +183,7 @@ the last item from ``digits.data``::\n SVC(C=100.0, gamma=0.001)\n \n Now you can *predict* new values. In this case, you'll predict using the last\n-image from ``digits.data``. By predicting, you'll determine the image from the \n+image from ``digits.data``. By predicting, you'll determine the image from the\n training set that best matches the last image.\n \n \n@@ -216,7 +216,7 @@ Type casting\n Unless otherwise specified, input will be cast to ``float64``::\n \n >>> import numpy as np\n- >>> from sklearn import random_projection\n+ >>> from sklearn import kernel_approximation\n \n >>> rng = np.random.RandomState(0)\n >>> X = rng.rand(10, 2000)\n@@ -224,7 +224,7 @@ Unless otherwise specified, input will be cast to ``float64``::\n >>> X.dtype\n dtype('float32')\n \n- >>> transformer = random_projection.GaussianRandomProjection()\n+ >>> transformer = kernel_approximation.RBFSampler()\n >>> X_new = transformer.fit_transform(X)\n >>> X_new.dtype\n dtype('float64')\n" }, { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 5d49a6fd281c7..bab7b3e33f850 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -385,6 +385,10 @@ Changelog\n :mod:`sklearn.random_projection`\n ................................\n \n+- |Enhancement| :class:`random_projection.SparseRandomProjection` and\n+ :class:`random_projection.GaussianRandomProjection` preserves dtype for\n+ `numpy.float32`. :pr:`<PRID>` by :user:`<NAME>`.\n+\n - |API| Adds :term:`get_feature_names_out` to all transformers in the\n :mod:`~sklearn.random_projection` module:\n :class:`~sklearn.random_projection.GaussianRandomProjection` and\n" } ]
diff --git a/doc/tutorial/basic/tutorial.rst b/doc/tutorial/basic/tutorial.rst index 5199ad226243f..4375e4fb83e61 100644 --- a/doc/tutorial/basic/tutorial.rst +++ b/doc/tutorial/basic/tutorial.rst @@ -183,7 +183,7 @@ the last item from ``digits.data``:: SVC(C=100.0, gamma=0.001) Now you can *predict* new values. In this case, you'll predict using the last -image from ``digits.data``. By predicting, you'll determine the image from the +image from ``digits.data``. By predicting, you'll determine the image from the training set that best matches the last image. @@ -216,7 +216,7 @@ Type casting Unless otherwise specified, input will be cast to ``float64``:: >>> import numpy as np - >>> from sklearn import random_projection + >>> from sklearn import kernel_approximation >>> rng = np.random.RandomState(0) >>> X = rng.rand(10, 2000) @@ -224,7 +224,7 @@ Unless otherwise specified, input will be cast to ``float64``:: >>> X.dtype dtype('float32') - >>> transformer = random_projection.GaussianRandomProjection() + >>> transformer = kernel_approximation.RBFSampler() >>> X_new = transformer.fit_transform(X) >>> X_new.dtype dtype('float64') diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 5d49a6fd281c7..bab7b3e33f850 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -385,6 +385,10 @@ Changelog :mod:`sklearn.random_projection` ................................ +- |Enhancement| :class:`random_projection.SparseRandomProjection` and + :class:`random_projection.GaussianRandomProjection` preserves dtype for + `numpy.float32`. :pr:`<PRID>` by :user:`<NAME>`. + - |API| Adds :term:`get_feature_names_out` to all transformers in the :mod:`~sklearn.random_projection` module: :class:`~sklearn.random_projection.GaussianRandomProjection` and
scikit-learn/scikit-learn
scikit-learn__scikit-learn-21408
https://github.com/scikit-learn/scikit-learn/pull/21408
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 37dc4c56dc860..1438b96a8295a 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -266,6 +266,13 @@ Changelog Setting a transformer to "passthrough" will pass the features unchanged. :pr:`20860` by :user:`Shubhraneel Pal <shubhraneel>`. +:mod:`sklearn.svm` +................... + +- |Enhancement| :class:`svm.OneClassSVM`, :class:`svm.NuSVC`, + :class:`svm.NuSVR`, :class:`svm.SVC` and :class:`svm.SVR` now expose + `n_iter_`, the number of iterations of the libsvm optimization routine. + :pr:`21408` by :user:`Juan Martín Loyola <jmloyola>`. - |Fix| :class: `pipeline.Pipeline` now does not validate hyper-parameters in `__init__` but in `.fit()`. :pr:`21888` by :user:`iofall <iofall>` and :user: `Arisa Y. <arisayosh>`. diff --git a/sklearn/svm/_base.py b/sklearn/svm/_base.py index 259b1b28c29be..2c74ae153543b 100644 --- a/sklearn/svm/_base.py +++ b/sklearn/svm/_base.py @@ -274,6 +274,17 @@ def fit(self, X, y, sample_weight=None): self.intercept_ *= -1 self.dual_coef_ = -self.dual_coef_ + # Since, in the case of SVC and NuSVC, the number of models optimized by + # libSVM could be greater than one (depending on the input), `n_iter_` + # stores an ndarray. + # For the other sub-classes (SVR, NuSVR, and OneClassSVM), the number of + # models optimized by libSVM is always one, so `n_iter_` stores an + # integer. + if self._impl in ["c_svc", "nu_svc"]: + self.n_iter_ = self._num_iter + else: + self.n_iter_ = self._num_iter.item() + return self def _validate_targets(self, y): @@ -320,6 +331,7 @@ def _dense_fit(self, X, y, sample_weight, solver_type, kernel, random_seed): self._probA, self._probB, self.fit_status_, + self._num_iter, ) = libsvm.fit( X, y, @@ -360,6 +372,7 @@ def _sparse_fit(self, X, y, sample_weight, solver_type, kernel, random_seed): self._probA, self._probB, self.fit_status_, + self._num_iter, ) = libsvm_sparse.libsvm_sparse_train( X.shape[1], X.data, diff --git a/sklearn/svm/_classes.py b/sklearn/svm/_classes.py index 719540cd725c0..cafaf9b2c2cf5 100644 --- a/sklearn/svm/_classes.py +++ b/sklearn/svm/_classes.py @@ -670,6 +670,13 @@ class SVC(BaseSVC): .. versionadded:: 1.0 + n_iter_ : ndarray of shape (n_classes * (n_classes - 1) // 2,) + Number of iterations run by the optimization routine to fit the model. + The shape of this attribute depends on the number of models optimized + which in turn depends on the number of classes. + + .. versionadded:: 1.1 + support_ : ndarray of shape (n_SV) Indices of support vectors. @@ -925,6 +932,13 @@ class NuSVC(BaseSVC): .. versionadded:: 1.0 + n_iter_ : ndarray of shape (n_classes * (n_classes - 1) // 2,) + Number of iterations run by the optimization routine to fit the model. + The shape of this attribute depends on the number of models optimized + which in turn depends on the number of classes. + + .. versionadded:: 1.1 + support_ : ndarray of shape (n_SV,) Indices of support vectors. @@ -1140,6 +1154,11 @@ class SVR(RegressorMixin, BaseLibSVM): .. versionadded:: 1.0 + n_iter_ : int + Number of iterations run by the optimization routine to fit the model. + + .. versionadded:: 1.1 + n_support_ : ndarray of shape (n_classes,), dtype=int32 Number of support vectors for each class. @@ -1328,6 +1347,11 @@ class NuSVR(RegressorMixin, BaseLibSVM): .. versionadded:: 1.0 + n_iter_ : int + Number of iterations run by the optimization routine to fit the model. + + .. versionadded:: 1.1 + n_support_ : ndarray of shape (n_classes,), dtype=int32 Number of support vectors for each class. @@ -1512,6 +1536,11 @@ class OneClassSVM(OutlierMixin, BaseLibSVM): .. versionadded:: 1.0 + n_iter_ : int + Number of iterations run by the optimization routine to fit the model. + + .. versionadded:: 1.1 + n_support_ : ndarray of shape (n_classes,), dtype=int32 Number of support vectors for each class. diff --git a/sklearn/svm/_libsvm.pxi b/sklearn/svm/_libsvm.pxi index ab7d212e3ba1a..75a6fb55bcf8e 100644 --- a/sklearn/svm/_libsvm.pxi +++ b/sklearn/svm/_libsvm.pxi @@ -56,6 +56,7 @@ cdef extern from "libsvm_helper.c": char *, char *, char *, char *) void copy_sv_coef (char *, svm_model *) + void copy_n_iter (char *, svm_model *) void copy_intercept (char *, svm_model *, np.npy_intp *) void copy_SV (char *, svm_model *, np.npy_intp *) int copy_support (char *data, svm_model *model) diff --git a/sklearn/svm/_libsvm.pyx b/sklearn/svm/_libsvm.pyx index 9186f0fcf7e29..4df99724b790a 100644 --- a/sklearn/svm/_libsvm.pyx +++ b/sklearn/svm/_libsvm.pyx @@ -152,6 +152,9 @@ def fit( probA, probB : array of shape (n_class*(n_class-1)/2,) Probability estimates, empty array for probability=False. + + n_iter : ndarray of shape (max(1, (n_class * (n_class - 1) // 2)),) + Number of iterations run by the optimization routine to fit the model. """ cdef svm_parameter param @@ -199,6 +202,10 @@ def fit( SV_len = get_l(model) n_class = get_nr(model) + cdef np.ndarray[int, ndim=1, mode='c'] n_iter + n_iter = np.empty(max(1, n_class * (n_class - 1) // 2), dtype=np.intc) + copy_n_iter(n_iter.data, model) + cdef np.ndarray[np.float64_t, ndim=2, mode='c'] sv_coef sv_coef = np.empty((n_class-1, SV_len), dtype=np.float64) copy_sv_coef (sv_coef.data, model) @@ -248,7 +255,7 @@ def fit( free(problem.x) return (support, support_vectors, n_class_SV, sv_coef, intercept, - probA, probB, fit_status) + probA, probB, fit_status, n_iter) cdef void set_predict_params( diff --git a/sklearn/svm/_libsvm_sparse.pyx b/sklearn/svm/_libsvm_sparse.pyx index 92d94b0c685a5..64fc69364b2ee 100644 --- a/sklearn/svm/_libsvm_sparse.pyx +++ b/sklearn/svm/_libsvm_sparse.pyx @@ -41,6 +41,7 @@ cdef extern from "libsvm_sparse_helper.c": double, int, int, int, char *, char *, int, int) void copy_sv_coef (char *, svm_csr_model *) + void copy_n_iter (char *, svm_csr_model *) void copy_support (char *, svm_csr_model *) void copy_intercept (char *, svm_csr_model *, np.npy_intp *) int copy_predict (char *, svm_csr_model *, np.npy_intp *, char *, BlasFunctions *) @@ -159,6 +160,10 @@ def libsvm_sparse_train ( int n_features, cdef np.npy_intp SV_len = get_l(model) cdef np.npy_intp n_class = get_nr(model) + cdef np.ndarray[int, ndim=1, mode='c'] n_iter + n_iter = np.empty(max(1, n_class * (n_class - 1) // 2), dtype=np.intc) + copy_n_iter(n_iter.data, model) + # copy model.sv_coef # we create a new array instead of resizing, otherwise # it would not erase previous information @@ -217,7 +222,7 @@ def libsvm_sparse_train ( int n_features, free_param(param) return (support, support_vectors_, sv_coef_data, intercept, n_class_SV, - probA, probB, fit_status) + probA, probB, fit_status, n_iter) def libsvm_sparse_predict (np.ndarray[np.float64_t, ndim=1, mode='c'] T_data, diff --git a/sklearn/svm/src/libsvm/LIBSVM_CHANGES b/sklearn/svm/src/libsvm/LIBSVM_CHANGES index bde6beaca2694..663550b8ddd6f 100644 --- a/sklearn/svm/src/libsvm/LIBSVM_CHANGES +++ b/sklearn/svm/src/libsvm/LIBSVM_CHANGES @@ -7,4 +7,5 @@ This is here mainly as checklist for incorporation of new versions of libsvm. * Improved random number generator (fix on windows, enhancement on other platforms). See <https://github.com/scikit-learn/scikit-learn/pull/13511#issuecomment-481729756> * invoke scipy blas api for svm kernel function to improve performance with speedup rate of 1.5X to 2X for dense data only. See <https://github.com/scikit-learn/scikit-learn/pull/16530> + * Expose the number of iterations run in optimization. See <https://github.com/scikit-learn/scikit-learn/pull/21408> The changes made with respect to upstream are detailed in the heading of svm.cpp diff --git a/sklearn/svm/src/libsvm/libsvm_helper.c b/sklearn/svm/src/libsvm/libsvm_helper.c index 17f328f9e7c4c..1adf6b1b35370 100644 --- a/sklearn/svm/src/libsvm/libsvm_helper.c +++ b/sklearn/svm/src/libsvm/libsvm_helper.c @@ -2,6 +2,13 @@ #include <numpy/arrayobject.h> #include "svm.h" #include "_svm_cython_blas_helpers.h" + + +#ifndef MAX + #define MAX(x, y) (((x) > (y)) ? (x) : (y)) +#endif + + /* * Some helper methods for libsvm bindings. * @@ -128,6 +135,9 @@ struct svm_model *set_model(struct svm_parameter *param, int nr_class, if ((model->rho = malloc( m * sizeof(double))) == NULL) goto rho_error; + // This is only allocated in dynamic memory while training. + model->n_iter = NULL; + model->nr_class = nr_class; model->param = *param; model->l = (int) support_dims[0]; @@ -218,6 +228,15 @@ npy_intp get_nr(struct svm_model *model) return (npy_intp) model->nr_class; } +/* + * Get the number of iterations run in optimization + */ +void copy_n_iter(char *data, struct svm_model *model) +{ + const int n_models = MAX(1, model->nr_class * (model->nr_class-1) / 2); + memcpy(data, model->n_iter, n_models * sizeof(int)); +} + /* * Some helpers to convert from libsvm sparse data structures * model->sv_coef is a double **, whereas data is just a double *, @@ -363,9 +382,11 @@ int free_model(struct svm_model *model) if (model == NULL) return -1; free(model->SV); - /* We don't free sv_ind, since we did not create them in + /* We don't free sv_ind and n_iter, since we did not create them in set_model */ - /* free(model->sv_ind); */ + /* free(model->sv_ind); + * free(model->n_iter); + */ free(model->sv_coef); free(model->rho); free(model->label); diff --git a/sklearn/svm/src/libsvm/libsvm_sparse_helper.c b/sklearn/svm/src/libsvm/libsvm_sparse_helper.c index a85a532319d88..08556212bab5e 100644 --- a/sklearn/svm/src/libsvm/libsvm_sparse_helper.c +++ b/sklearn/svm/src/libsvm/libsvm_sparse_helper.c @@ -3,6 +3,12 @@ #include "svm.h" #include "_svm_cython_blas_helpers.h" + +#ifndef MAX + #define MAX(x, y) (((x) > (y)) ? (x) : (y)) +#endif + + /* * Convert scipy.sparse.csr to libsvm's sparse data structure */ @@ -122,6 +128,9 @@ struct svm_csr_model *csr_set_model(struct svm_parameter *param, int nr_class, if ((model->rho = malloc( m * sizeof(double))) == NULL) goto rho_error; + // This is only allocated in dynamic memory while training. + model->n_iter = NULL; + /* in the case of precomputed kernels we do not use dense_to_precomputed because we don't want the leading 0. As indices start at 1 (not at 0) this will work */ @@ -348,6 +357,15 @@ void copy_sv_coef(char *data, struct svm_csr_model *model) } } +/* + * Get the number of iterations run in optimization + */ +void copy_n_iter(char *data, struct svm_csr_model *model) +{ + const int n_models = MAX(1, model->nr_class * (model->nr_class-1) / 2); + memcpy(data, model->n_iter, n_models * sizeof(int)); +} + /* * Get the number of support vectors in a model. */ @@ -402,6 +420,7 @@ int free_problem(struct svm_csr_problem *problem) int free_model(struct svm_csr_model *model) { /* like svm_free_and_destroy_model, but does not free sv_coef[i] */ + /* We don't free n_iter, since we did not create them in set_model. */ if (model == NULL) return -1; free(model->SV); free(model->sv_coef); diff --git a/sklearn/svm/src/libsvm/svm.cpp b/sklearn/svm/src/libsvm/svm.cpp index d209e35fc0a35..de07fecdba2ac 100644 --- a/sklearn/svm/src/libsvm/svm.cpp +++ b/sklearn/svm/src/libsvm/svm.cpp @@ -55,6 +55,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Sylvain Marie, Schneider Electric see <https://github.com/scikit-learn/scikit-learn/pull/13511#issuecomment-481729756> + Modified 2021: + + - Exposed number of iterations run in optimization, Juan Martín Loyola. + See <https://github.com/scikit-learn/scikit-learn/pull/21408/> */ #include <math.h> @@ -553,6 +557,7 @@ class Solver { double *upper_bound; double r; // for Solver_NU bool solve_timed_out; + int n_iter; }; void Solve(int l, const QMatrix& Q, const double *p_, const schar *y_, @@ -919,6 +924,9 @@ void Solver::Solve(int l, const QMatrix& Q, const double *p_, const schar *y_, for(int i=0;i<l;i++) si->upper_bound[i] = C[i]; + // store number of iterations + si->n_iter = iter; + info("\noptimization finished, #iter = %d\n",iter); delete[] p; @@ -1837,6 +1845,7 @@ struct decision_function { double *alpha; double rho; + int n_iter; }; static decision_function svm_train_one( @@ -1902,6 +1911,7 @@ static decision_function svm_train_one( decision_function f; f.alpha = alpha; f.rho = si.rho; + f.n_iter = si.n_iter; return f; } @@ -2387,6 +2397,8 @@ PREFIX(model) *PREFIX(train)(const PREFIX(problem) *prob, const svm_parameter *p NAMESPACE::decision_function f = NAMESPACE::svm_train_one(prob,param,0,0, status,blas_functions); model->rho = Malloc(double,1); model->rho[0] = f.rho; + model->n_iter = Malloc(int,1); + model->n_iter[0] = f.n_iter; int nSV = 0; int i; @@ -2523,8 +2535,12 @@ PREFIX(model) *PREFIX(train)(const PREFIX(problem) *prob, const svm_parameter *p model->label[i] = label[i]; model->rho = Malloc(double,nr_class*(nr_class-1)/2); + model->n_iter = Malloc(int,nr_class*(nr_class-1)/2); for(i=0;i<nr_class*(nr_class-1)/2;i++) + { model->rho[i] = f[i].rho; + model->n_iter[i] = f[i].n_iter; + } if(param->probability) { @@ -2978,6 +2994,9 @@ void PREFIX(free_model_content)(PREFIX(model)* model_ptr) free(model_ptr->nSV); model_ptr->nSV = NULL; + + free(model_ptr->n_iter); + model_ptr->n_iter = NULL; } void PREFIX(free_and_destroy_model)(PREFIX(model)** model_ptr_ptr) diff --git a/sklearn/svm/src/libsvm/svm.h b/sklearn/svm/src/libsvm/svm.h index a1634119858f1..518872c67bc5c 100644 --- a/sklearn/svm/src/libsvm/svm.h +++ b/sklearn/svm/src/libsvm/svm.h @@ -76,6 +76,7 @@ struct svm_model int l; /* total #SV */ struct svm_node *SV; /* SVs (SV[l]) */ double **sv_coef; /* coefficients for SVs in decision functions (sv_coef[k-1][l]) */ + int *n_iter; /* number of iterations run by the optimization routine to fit the model */ int *sv_ind; /* index of support vectors */ @@ -101,6 +102,7 @@ struct svm_csr_model int l; /* total #SV */ struct svm_csr_node **SV; /* SVs (SV[l]) */ double **sv_coef; /* coefficients for SVs in decision functions (sv_coef[k-1][l]) */ + int *n_iter; /* number of iterations run by the optimization routine to fit the model */ int *sv_ind; /* index of support vectors */ diff --git a/sklearn/utils/estimator_checks.py b/sklearn/utils/estimator_checks.py index e6cbc38adbcac..31f14110e80bb 100644 --- a/sklearn/utils/estimator_checks.py +++ b/sklearn/utils/estimator_checks.py @@ -278,6 +278,7 @@ def _yield_outliers_checks(estimator): # test if NotFittedError is raised if _safe_tags(estimator, key="requires_fit"): yield check_estimators_unfitted + yield check_non_transformer_estimators_n_iter def _yield_all_checks(estimator): @@ -3261,11 +3262,7 @@ def check_non_transformer_estimators_n_iter(name, estimator_orig): # labeled, hence n_iter_ = 0 is valid. not_run_check_n_iter = [ "Ridge", - "SVR", - "NuSVR", - "NuSVC", "RidgeClassifier", - "SVC", "RandomizedLasso", "LogisticRegressionCV", "LinearSVC", @@ -3290,9 +3287,11 @@ def check_non_transformer_estimators_n_iter(name, estimator_orig): set_random_state(estimator, 0) + X = _pairwise_estimator_convert_X(X, estimator_orig) + estimator.fit(X, y_) - assert estimator.n_iter_ >= 1 + assert np.all(estimator.n_iter_ >= 1) @ignore_warnings(category=FutureWarning)
diff --git a/sklearn/svm/tests/test_svm.py b/sklearn/svm/tests/test_svm.py index 67eabf9fc8d2c..af4e7d4a0935b 100644 --- a/sklearn/svm/tests/test_svm.py +++ b/sklearn/svm/tests/test_svm.py @@ -66,12 +66,58 @@ def test_libsvm_iris(): assert_array_equal(clf.classes_, np.sort(clf.classes_)) # check also the low-level API - model = _libsvm.fit(iris.data, iris.target.astype(np.float64)) - pred = _libsvm.predict(iris.data, *model) + # We unpack the values to create a dictionary with some of the return values + # from Libsvm's fit. + ( + libsvm_support, + libsvm_support_vectors, + libsvm_n_class_SV, + libsvm_sv_coef, + libsvm_intercept, + libsvm_probA, + libsvm_probB, + # libsvm_fit_status and libsvm_n_iter won't be used below. + libsvm_fit_status, + libsvm_n_iter, + ) = _libsvm.fit(iris.data, iris.target.astype(np.float64)) + + model_params = { + "support": libsvm_support, + "SV": libsvm_support_vectors, + "nSV": libsvm_n_class_SV, + "sv_coef": libsvm_sv_coef, + "intercept": libsvm_intercept, + "probA": libsvm_probA, + "probB": libsvm_probB, + } + pred = _libsvm.predict(iris.data, **model_params) assert np.mean(pred == iris.target) > 0.95 - model = _libsvm.fit(iris.data, iris.target.astype(np.float64), kernel="linear") - pred = _libsvm.predict(iris.data, *model, kernel="linear") + # We unpack the values to create a dictionary with some of the return values + # from Libsvm's fit. + ( + libsvm_support, + libsvm_support_vectors, + libsvm_n_class_SV, + libsvm_sv_coef, + libsvm_intercept, + libsvm_probA, + libsvm_probB, + # libsvm_fit_status and libsvm_n_iter won't be used below. + libsvm_fit_status, + libsvm_n_iter, + ) = _libsvm.fit(iris.data, iris.target.astype(np.float64), kernel="linear") + + model_params = { + "support": libsvm_support, + "SV": libsvm_support_vectors, + "nSV": libsvm_n_class_SV, + "sv_coef": libsvm_sv_coef, + "intercept": libsvm_intercept, + "probA": libsvm_probA, + "probB": libsvm_probB, + } + pred = _libsvm.predict(iris.data, **model_params, kernel="linear") assert np.mean(pred == iris.target) > 0.95 pred = _libsvm.cross_validation( @@ -1059,16 +1105,17 @@ def test_svc_bad_kernel(): svc.fit(X, Y) -def test_timeout(): +def test_libsvm_convergence_warnings(): a = svm.SVC( - kernel=lambda x, y: np.dot(x, y.T), probability=True, random_state=0, max_iter=1 + kernel=lambda x, y: np.dot(x, y.T), probability=True, random_state=0, max_iter=2 ) warning_msg = ( - r"Solver terminated early \(max_iter=1\). Consider pre-processing " + r"Solver terminated early \(max_iter=2\). Consider pre-processing " r"your data with StandardScaler or MinMaxScaler." ) with pytest.warns(ConvergenceWarning, match=warning_msg): a.fit(np.array(X), Y) + assert np.all(a.n_iter_ == 2) def test_unfitted(): @@ -1422,3 +1469,35 @@ def test_svc_raises_error_internal_representation(): msg = "The internal representation of SVC was altered" with pytest.raises(ValueError, match=msg): clf.predict(X) + + [email protected]( + "estimator, expected_n_iter_type", + [ + (svm.SVC, np.ndarray), + (svm.NuSVC, np.ndarray), + (svm.SVR, int), + (svm.NuSVR, int), + (svm.OneClassSVM, int), + ], +) [email protected]( + "dataset", + [ + make_classification(n_classes=2, n_informative=2, random_state=0), + make_classification(n_classes=3, n_informative=3, random_state=0), + make_classification(n_classes=4, n_informative=4, random_state=0), + ], +) +def test_n_iter_libsvm(estimator, expected_n_iter_type, dataset): + # Check that the type of n_iter_ is correct for the classes that inherit + # from BaseSVC. + # Note that for SVC, and NuSVC this is an ndarray; while for SVR, NuSVR, and + # OneClassSVM, it is an int. + # For SVC and NuSVC also check the shape of n_iter_. + X, y = dataset + n_iter = estimator(kernel="linear").fit(X, y).n_iter_ + assert type(n_iter) == expected_n_iter_type + if estimator in [svm.SVC, svm.NuSVC]: + n_classes = len(np.unique(y)) + assert n_iter.shape == (n_classes * (n_classes - 1) // 2,)
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 37dc4c56dc860..1438b96a8295a 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -266,6 +266,13 @@ Changelog\n Setting a transformer to \"passthrough\" will pass the features unchanged.\n :pr:`20860` by :user:`Shubhraneel Pal <shubhraneel>`.\n \n+:mod:`sklearn.svm`\n+...................\n+\n+- |Enhancement| :class:`svm.OneClassSVM`, :class:`svm.NuSVC`,\n+ :class:`svm.NuSVR`, :class:`svm.SVC` and :class:`svm.SVR` now expose\n+ `n_iter_`, the number of iterations of the libsvm optimization routine.\n+ :pr:`21408` by :user:`Juan Martín Loyola <jmloyola>`.\n - |Fix| :class: `pipeline.Pipeline` now does not validate hyper-parameters in\n `__init__` but in `.fit()`.\n :pr:`21888` by :user:`iofall <iofall>` and :user: `Arisa Y. <arisayosh>`.\n" } ]
1.01
39782b71b03d180bb2fe2ac321b6bab87a43746a
[ "sklearn/svm/tests/test_svm.py::test_linearsvm_liblinear_sample_weight[LinearSVC-params2]", "sklearn/svm/tests/test_svm.py::test_negative_sample_weights_mask_all_samples[weights-are-negative-NuSVR]", "sklearn/svm/tests/test_svm.py::test_auto_weight", "sklearn/svm/tests/test_svm.py::test_negative_weight_equal_coeffs[partial-mask-label-2-NuSVR]", "sklearn/svm/tests/test_svm.py::test_negative_sample_weights_mask_all_samples[weights-are-negative-SVR]", "sklearn/svm/tests/test_svm.py::test_sparse_fit_support_vectors_empty", "sklearn/svm/tests/test_svm.py::test_consistent_proba", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[auto_deprecated-When 'gamma' is a string, it should be either 'scale' or 'auto'-NuSVC-data1]", "sklearn/svm/tests/test_svm.py::test_dense_liblinear_intercept_handling", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[0.0-gamma value must be > 0; 0.0 is invalid. Use a positive number or use 'auto' to set gamma to a value of 1 / n_features.-NuSVC-data1]", "sklearn/svm/tests/test_svm.py::test_negative_weight_equal_coeffs[partial-mask-label-2-SVC]", "sklearn/svm/tests/test_svm.py::test_libsvm_parameters", "sklearn/svm/tests/test_svm.py::test_svm_classifier_sided_sample_weight[estimator1]", "sklearn/svm/tests/test_svm.py::test_lsvc_intercept_scaling_zero", "sklearn/svm/tests/test_svm.py::test_linearsvm_liblinear_sample_weight[LinearSVR-params5]", "sklearn/svm/tests/test_svm.py::test_negative_sample_weights_mask_all_samples[weights-are-zero-NuSVR]", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[0.0-gamma value must be > 0; 0.0 is invalid. Use a positive number or use 'auto' to set gamma to a value of 1 / n_features.-SVC-data0]", "sklearn/svm/tests/test_svm.py::test_linearsvm_liblinear_sample_weight[LinearSVC-params0]", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[gamma5-The gamma value should be set to 'scale', 'auto' or a positive float value. {} is not a valid option-NuSVR-data3]", "sklearn/svm/tests/test_svm.py::test_negative_weight_equal_coeffs[partial-mask-label-2-NuSVC]", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[gamma3-The gamma value should be set to 'scale', 'auto' or a positive float value. array([1., 4.]) is not a valid option-OneClassSVM-data4]", "sklearn/svm/tests/test_svm.py::test_oneclass_decision_function", "sklearn/svm/tests/test_svm.py::test_negative_sample_weights_mask_all_samples[weights-are-negative-OneClassSVM]", "sklearn/svm/tests/test_svm.py::test_negative_weights_svc_leave_just_one_label[mask-label-1-NuSVC]", "sklearn/svm/tests/test_svm.py::test_bad_input", "sklearn/svm/tests/test_svm.py::test_svc_ovr_tie_breaking[SVC]", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[gamma5-The gamma value should be set to 'scale', 'auto' or a positive float value. {} is not a valid option-NuSVC-data1]", "sklearn/svm/tests/test_svm.py::test_svc_clone_with_callable_kernel", "sklearn/svm/tests/test_svm.py::test_svr_predict", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[-1-gamma value must be > 0; -1 is invalid. Use a positive number or use 'auto' to set gamma to a value of 1 / n_features.-OneClassSVM-data4]", "sklearn/svm/tests/test_svm.py::test_linearsvc_fit_sampleweight", "sklearn/svm/tests/test_svm.py::test_negative_weight_equal_coeffs[partial-mask-label-1-NuSVC]", "sklearn/svm/tests/test_svm.py::test_ovr_decision_function", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[-1-gamma value must be > 0; -1 is invalid. Use a positive number or use 'auto' to set gamma to a value of 1 / n_features.-NuSVR-data3]", "sklearn/svm/tests/test_svm.py::test_svm_equivalence_sample_weight_C", "sklearn/svm/tests/test_svm.py::test_linearsvm_liblinear_sample_weight[LinearSVC-params3]", "sklearn/svm/tests/test_svm.py::test_linearsvc_parameters", "sklearn/svm/tests/test_svm.py::test_tweak_params", "sklearn/svm/tests/test_svm.py::test_sparse_precomputed", "sklearn/svm/tests/test_svm.py::test_negative_sample_weights_mask_all_samples[weights-are-negative-NuSVC]", "sklearn/svm/tests/test_svm.py::test_negative_sample_weights_mask_all_samples[weights-are-zero-OneClassSVM]", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[-1-gamma value must be > 0; -1 is invalid. Use a positive number or use 'auto' to set gamma to a value of 1 / n_features.-SVR-data2]", "sklearn/svm/tests/test_svm.py::test_linearsvr_fit_sampleweight", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[0.0-gamma value must be > 0; 0.0 is invalid. Use a positive number or use 'auto' to set gamma to a value of 1 / n_features.-OneClassSVM-data4]", "sklearn/svm/tests/test_svm.py::test_crammer_singer_binary", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[-1-gamma value must be > 0; -1 is invalid. Use a positive number or use 'auto' to set gamma to a value of 1 / n_features.-SVC-data0]", "sklearn/svm/tests/test_svm.py::test_negative_weights_svc_leave_just_one_label[mask-label-1-SVC]", "sklearn/svm/tests/test_svm.py::test_negative_weights_svc_leave_just_one_label[mask-label-2-SVC]", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[gamma4-The gamma value should be set to 'scale', 'auto' or a positive float value. [] is not a valid option-SVR-data2]", "sklearn/svm/tests/test_svm.py::test_linearsvm_liblinear_sample_weight[LinearSVC-params1]", "sklearn/svm/tests/test_svm.py::test_svc_ovr_tie_breaking[NuSVC]", "sklearn/svm/tests/test_svm.py::test_svr_errors", "sklearn/svm/tests/test_svm.py::test_svc_bad_kernel", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[gamma3-The gamma value should be set to 'scale', 'auto' or a positive float value. array([1., 4.]) is not a valid option-NuSVC-data1]", "sklearn/svm/tests/test_svm.py::test_negative_weights_svc_leave_two_labels[partial-mask-label-2-SVC]", "sklearn/svm/tests/test_svm.py::test_liblinear_set_coef", "sklearn/svm/tests/test_svm.py::test_immutable_coef_property", "sklearn/svm/tests/test_svm.py::test_negative_sample_weights_mask_all_samples[weights-are-negative-SVC]", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[gamma4-The gamma value should be set to 'scale', 'auto' or a positive float value. [] is not a valid option-SVC-data0]", "sklearn/svm/tests/test_svm.py::test_linear_svx_uppercase_loss_penality_raises_error", "sklearn/svm/tests/test_svm.py::test_hasattr_predict_proba", "sklearn/svm/tests/test_svm.py::test_linearsvm_liblinear_sample_weight[LinearSVR-params4]", "sklearn/svm/tests/test_svm.py::test_svm_classifier_sided_sample_weight[estimator0]", "sklearn/svm/tests/test_svm.py::test_svc_raises_error_internal_representation", "sklearn/svm/tests/test_svm.py::test_decision_function", "sklearn/svm/tests/test_svm.py::test_svm_regressor_sided_sample_weight[estimator0]", "sklearn/svm/tests/test_svm.py::test_linearsvc_verbose", "sklearn/svm/tests/test_svm.py::test_decision_function_shape_two_class", "sklearn/svm/tests/test_svm.py::test_oneclass", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[gamma3-The gamma value should be set to 'scale', 'auto' or a positive float value. array([1., 4.]) is not a valid option-SVC-data0]", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[gamma5-The gamma value should be set to 'scale', 'auto' or a positive float value. {} is not a valid option-SVC-data0]", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[gamma5-The gamma value should be set to 'scale', 'auto' or a positive float value. {} is not a valid option-OneClassSVM-data4]", "sklearn/svm/tests/test_svm.py::test_negative_sample_weights_mask_all_samples[weights-are-zero-SVC]", "sklearn/svm/tests/test_svm.py::test_negative_weights_svc_leave_just_one_label[mask-label-2-NuSVC]", "sklearn/svm/tests/test_svm.py::test_negative_weights_svc_leave_two_labels[partial-mask-label-2-NuSVC]", "sklearn/svm/tests/test_svm.py::test_custom_kernel_not_array_input[SVC]", "sklearn/svm/tests/test_svm.py::test_precomputed", "sklearn/svm/tests/test_svm.py::test_unicode_kernel", "sklearn/svm/tests/test_svm.py::test_linearsvm_liblinear_sample_weight[LinearSVR-params6]", "sklearn/svm/tests/test_svm.py::test_decision_function_shape[SVC]", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[gamma5-The gamma value should be set to 'scale', 'auto' or a positive float value. {} is not a valid option-SVR-data2]", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[0.0-gamma value must be > 0; 0.0 is invalid. Use a positive number or use 'auto' to set gamma to a value of 1 / n_features.-NuSVR-data3]", "sklearn/svm/tests/test_svm.py::test_linear_svc_intercept_scaling", "sklearn/svm/tests/test_svm.py::test_linearsvr", "sklearn/svm/tests/test_svm.py::test_negative_weights_svc_leave_two_labels[partial-mask-label-1-SVC]", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[auto_deprecated-When 'gamma' is a string, it should be either 'scale' or 'auto'-OneClassSVM-data4]", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[gamma3-The gamma value should be set to 'scale', 'auto' or a positive float value. array([1., 4.]) is not a valid option-NuSVR-data3]", "sklearn/svm/tests/test_svm.py::test_linearsvc_crammer_singer", "sklearn/svm/tests/test_svm.py::test_oneclass_fit_params_is_deprecated", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[-1-gamma value must be > 0; -1 is invalid. Use a positive number or use 'auto' to set gamma to a value of 1 / n_features.-NuSVC-data1]", "sklearn/svm/tests/test_svm.py::test_linearsvc_iris", "sklearn/svm/tests/test_svm.py::test_unfitted", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[gamma4-The gamma value should be set to 'scale', 'auto' or a positive float value. [] is not a valid option-NuSVR-data3]", "sklearn/svm/tests/test_svm.py::test_svm_regressor_sided_sample_weight[estimator1]", "sklearn/svm/tests/test_svm.py::test_n_support_oneclass_svr", "sklearn/svm/tests/test_svm.py::test_negative_sample_weights_mask_all_samples[weights-are-zero-SVR]", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[auto_deprecated-When 'gamma' is a string, it should be either 'scale' or 'auto'-SVC-data0]", "sklearn/svm/tests/test_svm.py::test_svr_coef_sign", "sklearn/svm/tests/test_svm.py::test_svr", "sklearn/svm/tests/test_svm.py::test_negative_weights_svc_leave_two_labels[partial-mask-label-1-NuSVC]", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[gamma4-The gamma value should be set to 'scale', 'auto' or a positive float value. [] is not a valid option-OneClassSVM-data4]", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[gamma3-The gamma value should be set to 'scale', 'auto' or a positive float value. array([1., 4.]) is not a valid option-SVR-data2]", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[auto_deprecated-When 'gamma' is a string, it should be either 'scale' or 'auto'-SVR-data2]", "sklearn/svm/tests/test_svm.py::test_custom_kernel_not_array_input[SVR]", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[gamma4-The gamma value should be set to 'scale', 'auto' or a positive float value. [] is not a valid option-NuSVC-data1]", "sklearn/svm/tests/test_svm.py::test_weight", "sklearn/svm/tests/test_svm.py::test_svc_invalid_break_ties_param[SVC]", "sklearn/svm/tests/test_svm.py::test_probability", "sklearn/svm/tests/test_svm.py::test_oneclass_score_samples", "sklearn/svm/tests/test_svm.py::test_svc_invalid_break_ties_param[NuSVC]", "sklearn/svm/tests/test_svm.py::test_negative_sample_weights_mask_all_samples[weights-are-zero-NuSVC]", "sklearn/svm/tests/test_svm.py::test_negative_weight_equal_coeffs[partial-mask-label-1-NuSVR]", "sklearn/svm/tests/test_svm.py::test_decision_function_shape[NuSVC]", "sklearn/svm/tests/test_svm.py::test_linearsvc", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[auto_deprecated-When 'gamma' is a string, it should be either 'scale' or 'auto'-NuSVR-data3]", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[0.0-gamma value must be > 0; 0.0 is invalid. Use a positive number or use 'auto' to set gamma to a value of 1 / n_features.-SVR-data2]", "sklearn/svm/tests/test_svm.py::test_linear_svm_convergence_warnings", "sklearn/svm/tests/test_svm.py::test_negative_weight_equal_coeffs[partial-mask-label-1-SVC]" ]
[ "sklearn/svm/tests/test_svm.py::test_n_iter_libsvm[dataset1-NuSVR-int]", "sklearn/svm/tests/test_svm.py::test_n_iter_libsvm[dataset1-SVR-int]", "sklearn/svm/tests/test_svm.py::test_n_iter_libsvm[dataset0-NuSVC-ndarray]", "sklearn/svm/tests/test_svm.py::test_n_iter_libsvm[dataset2-OneClassSVM-int]", "sklearn/svm/tests/test_svm.py::test_n_iter_libsvm[dataset2-SVR-int]", "sklearn/svm/tests/test_svm.py::test_n_iter_libsvm[dataset1-NuSVC-ndarray]", "sklearn/svm/tests/test_svm.py::test_libsvm_iris", "sklearn/svm/tests/test_svm.py::test_n_iter_libsvm[dataset2-NuSVR-int]", "sklearn/svm/tests/test_svm.py::test_n_iter_libsvm[dataset2-NuSVC-ndarray]", "sklearn/svm/tests/test_svm.py::test_n_iter_libsvm[dataset1-SVC-ndarray]", "sklearn/svm/tests/test_svm.py::test_n_iter_libsvm[dataset0-NuSVR-int]", "sklearn/svm/tests/test_svm.py::test_n_iter_libsvm[dataset2-SVC-ndarray]", "sklearn/svm/tests/test_svm.py::test_libsvm_convergence_warnings", "sklearn/svm/tests/test_svm.py::test_n_iter_libsvm[dataset0-SVC-ndarray]", "sklearn/svm/tests/test_svm.py::test_n_iter_libsvm[dataset0-SVR-int]", "sklearn/svm/tests/test_svm.py::test_n_iter_libsvm[dataset0-OneClassSVM-int]", "sklearn/svm/tests/test_svm.py::test_n_iter_libsvm[dataset1-OneClassSVM-int]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 37dc4c56dc860..1438b96a8295a 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -266,6 +266,13 @@ Changelog\n Setting a transformer to \"passthrough\" will pass the features unchanged.\n :pr:`<PRID>` by :user:`<NAME>`.\n \n+:mod:`sklearn.svm`\n+...................\n+\n+- |Enhancement| :class:`svm.OneClassSVM`, :class:`svm.NuSVC`,\n+ :class:`svm.NuSVR`, :class:`svm.SVC` and :class:`svm.SVR` now expose\n+ `n_iter_`, the number of iterations of the libsvm optimization routine.\n+ :pr:`<PRID>` by :user:`<NAME>`.\n - |Fix| :class: `pipeline.Pipeline` now does not validate hyper-parameters in\n `__init__` but in `.fit()`.\n :pr:`<PRID>` by :user:`<NAME>` and :user: `Arisa Y. <arisayosh>`.\n" } ]
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 37dc4c56dc860..1438b96a8295a 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -266,6 +266,13 @@ Changelog Setting a transformer to "passthrough" will pass the features unchanged. :pr:`<PRID>` by :user:`<NAME>`. +:mod:`sklearn.svm` +................... + +- |Enhancement| :class:`svm.OneClassSVM`, :class:`svm.NuSVC`, + :class:`svm.NuSVR`, :class:`svm.SVC` and :class:`svm.SVR` now expose + `n_iter_`, the number of iterations of the libsvm optimization routine. + :pr:`<PRID>` by :user:`<NAME>`. - |Fix| :class: `pipeline.Pipeline` now does not validate hyper-parameters in `__init__` but in `.fit()`. :pr:`<PRID>` by :user:`<NAME>` and :user: `Arisa Y. <arisayosh>`.
scikit-learn/scikit-learn
scikit-learn__scikit-learn-22149
https://github.com/scikit-learn/scikit-learn/pull/22149
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 61d5c64255f71..d03ce62dae5b4 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -451,6 +451,12 @@ Changelog parameters in `fit` instead of `__init__`. :pr:`21436` by :user:`Haidar Almubarak <Haidar13 >`. +- |Enhancement| :func:`svm.SVR`, :func:`svm.SVC`, :func:`svm.NuSVR`, + :func:`svm.OneClassSVM`, :func:`svm.NuSVC` now raise an error + when the dual-gap estimation produce non-finite parameter weights. + :pr:`22149` by :user:`Christian Ritter <chritter>` and + :user:`Norbert Preining <norbusan>`. + :mod:`sklearn.utils` .................... diff --git a/sklearn/svm/_base.py b/sklearn/svm/_base.py index 2c74ae153543b..f25669651f0e4 100644 --- a/sklearn/svm/_base.py +++ b/sklearn/svm/_base.py @@ -274,6 +274,16 @@ def fit(self, X, y, sample_weight=None): self.intercept_ *= -1 self.dual_coef_ = -self.dual_coef_ + dual_coef = self._dual_coef_.data if self._sparse else self._dual_coef_ + intercept_finiteness = np.isfinite(self._intercept_).all() + dual_coef_finiteness = np.isfinite(dual_coef).all() + if not (intercept_finiteness and dual_coef_finiteness): + raise ValueError( + "The dual coefficients or intercepts are not finite. " + "The input data may contain large values and need to be" + "preprocessed." + ) + # Since, in the case of SVC and NuSVC, the number of models optimized by # libSVM could be greater than one (depending on the input), `n_iter_` # stores an ndarray.
diff --git a/sklearn/svm/tests/test_svm.py b/sklearn/svm/tests/test_svm.py index af4e7d4a0935b..a8e53a5d50cb0 100644 --- a/sklearn/svm/tests/test_svm.py +++ b/sklearn/svm/tests/test_svm.py @@ -731,6 +731,20 @@ def test_bad_input(): clf.predict(Xt) +def test_svc_nonfinite_params(): + # Check SVC throws ValueError when dealing with non-finite parameter values + rng = np.random.RandomState(0) + n_samples = 10 + fmax = np.finfo(np.float64).max + X = fmax * rng.uniform(size=(n_samples, 2)) + y = rng.randint(0, 2, size=n_samples) + + clf = svm.SVC() + msg = "The dual coefficients or intercepts are not finite" + with pytest.raises(ValueError, match=msg): + clf.fit(X, y) + + @pytest.mark.parametrize( "Estimator, data", [
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 61d5c64255f71..d03ce62dae5b4 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -451,6 +451,12 @@ Changelog\n parameters in `fit` instead of `__init__`.\n :pr:`21436` by :user:`Haidar Almubarak <Haidar13 >`.\n \n+- |Enhancement| :func:`svm.SVR`, :func:`svm.SVC`, :func:`svm.NuSVR`,\n+ :func:`svm.OneClassSVM`, :func:`svm.NuSVC` now raise an error\n+ when the dual-gap estimation produce non-finite parameter weights.\n+ :pr:`22149` by :user:`Christian Ritter <chritter>` and\n+ :user:`Norbert Preining <norbusan>`.\n+\n :mod:`sklearn.utils`\n ....................\n \n" } ]
1.01
8d6217107f02d6f52d2f8c8908958fe82778c7cc
[ "sklearn/svm/tests/test_svm.py::test_linearsvm_liblinear_sample_weight[LinearSVC-params2]", "sklearn/svm/tests/test_svm.py::test_negative_sample_weights_mask_all_samples[weights-are-negative-NuSVR]", "sklearn/svm/tests/test_svm.py::test_auto_weight", "sklearn/svm/tests/test_svm.py::test_negative_weight_equal_coeffs[partial-mask-label-2-NuSVR]", "sklearn/svm/tests/test_svm.py::test_negative_sample_weights_mask_all_samples[weights-are-negative-SVR]", "sklearn/svm/tests/test_svm.py::test_sparse_fit_support_vectors_empty", "sklearn/svm/tests/test_svm.py::test_consistent_proba", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[auto_deprecated-When 'gamma' is a string, it should be either 'scale' or 'auto'-NuSVC-data1]", "sklearn/svm/tests/test_svm.py::test_dense_liblinear_intercept_handling", "sklearn/svm/tests/test_svm.py::test_n_iter_libsvm[dataset1-NuSVR-int]", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[0.0-gamma value must be > 0; 0.0 is invalid. Use a positive number or use 'auto' to set gamma to a value of 1 / n_features.-NuSVC-data1]", "sklearn/svm/tests/test_svm.py::test_negative_weight_equal_coeffs[partial-mask-label-2-SVC]", "sklearn/svm/tests/test_svm.py::test_libsvm_parameters", "sklearn/svm/tests/test_svm.py::test_n_iter_libsvm[dataset1-SVR-int]", "sklearn/svm/tests/test_svm.py::test_svm_classifier_sided_sample_weight[estimator1]", "sklearn/svm/tests/test_svm.py::test_lsvc_intercept_scaling_zero", "sklearn/svm/tests/test_svm.py::test_linearsvm_liblinear_sample_weight[LinearSVR-params5]", "sklearn/svm/tests/test_svm.py::test_n_iter_libsvm[dataset0-NuSVC-ndarray]", "sklearn/svm/tests/test_svm.py::test_negative_sample_weights_mask_all_samples[weights-are-zero-NuSVR]", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[0.0-gamma value must be > 0; 0.0 is invalid. Use a positive number or use 'auto' to set gamma to a value of 1 / n_features.-SVC-data0]", "sklearn/svm/tests/test_svm.py::test_linearsvm_liblinear_sample_weight[LinearSVC-params0]", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[gamma5-The gamma value should be set to 'scale', 'auto' or a positive float value. {} is not a valid option-NuSVR-data3]", "sklearn/svm/tests/test_svm.py::test_negative_weight_equal_coeffs[partial-mask-label-2-NuSVC]", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[gamma3-The gamma value should be set to 'scale', 'auto' or a positive float value. array([1., 4.]) is not a valid option-OneClassSVM-data4]", "sklearn/svm/tests/test_svm.py::test_oneclass_decision_function", "sklearn/svm/tests/test_svm.py::test_negative_sample_weights_mask_all_samples[weights-are-negative-OneClassSVM]", "sklearn/svm/tests/test_svm.py::test_negative_weights_svc_leave_just_one_label[mask-label-1-NuSVC]", "sklearn/svm/tests/test_svm.py::test_bad_input", "sklearn/svm/tests/test_svm.py::test_svc_ovr_tie_breaking[SVC]", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[gamma5-The gamma value should be set to 'scale', 'auto' or a positive float value. {} is not a valid option-NuSVC-data1]", "sklearn/svm/tests/test_svm.py::test_svc_clone_with_callable_kernel", "sklearn/svm/tests/test_svm.py::test_svr_predict", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[-1-gamma value must be > 0; -1 is invalid. Use a positive number or use 'auto' to set gamma to a value of 1 / n_features.-OneClassSVM-data4]", "sklearn/svm/tests/test_svm.py::test_linearsvc_fit_sampleweight", "sklearn/svm/tests/test_svm.py::test_negative_weight_equal_coeffs[partial-mask-label-1-NuSVC]", "sklearn/svm/tests/test_svm.py::test_n_iter_libsvm[dataset2-OneClassSVM-int]", "sklearn/svm/tests/test_svm.py::test_ovr_decision_function", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[-1-gamma value must be > 0; -1 is invalid. Use a positive number or use 'auto' to set gamma to a value of 1 / n_features.-NuSVR-data3]", "sklearn/svm/tests/test_svm.py::test_n_iter_libsvm[dataset2-SVR-int]", "sklearn/svm/tests/test_svm.py::test_svm_equivalence_sample_weight_C", "sklearn/svm/tests/test_svm.py::test_n_iter_libsvm[dataset1-NuSVC-ndarray]", "sklearn/svm/tests/test_svm.py::test_linearsvm_liblinear_sample_weight[LinearSVC-params3]", "sklearn/svm/tests/test_svm.py::test_linearsvc_parameters", "sklearn/svm/tests/test_svm.py::test_libsvm_iris", "sklearn/svm/tests/test_svm.py::test_tweak_params", "sklearn/svm/tests/test_svm.py::test_sparse_precomputed", "sklearn/svm/tests/test_svm.py::test_negative_sample_weights_mask_all_samples[weights-are-negative-NuSVC]", "sklearn/svm/tests/test_svm.py::test_negative_sample_weights_mask_all_samples[weights-are-zero-OneClassSVM]", "sklearn/svm/tests/test_svm.py::test_n_iter_libsvm[dataset2-NuSVR-int]", "sklearn/svm/tests/test_svm.py::test_n_iter_libsvm[dataset2-NuSVC-ndarray]", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[-1-gamma value must be > 0; -1 is invalid. Use a positive number or use 'auto' to set gamma to a value of 1 / n_features.-SVR-data2]", "sklearn/svm/tests/test_svm.py::test_linearsvr_fit_sampleweight", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[0.0-gamma value must be > 0; 0.0 is invalid. Use a positive number or use 'auto' to set gamma to a value of 1 / n_features.-OneClassSVM-data4]", "sklearn/svm/tests/test_svm.py::test_crammer_singer_binary", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[-1-gamma value must be > 0; -1 is invalid. Use a positive number or use 'auto' to set gamma to a value of 1 / n_features.-SVC-data0]", "sklearn/svm/tests/test_svm.py::test_negative_weights_svc_leave_just_one_label[mask-label-1-SVC]", "sklearn/svm/tests/test_svm.py::test_negative_weights_svc_leave_just_one_label[mask-label-2-SVC]", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[gamma4-The gamma value should be set to 'scale', 'auto' or a positive float value. [] is not a valid option-SVR-data2]", "sklearn/svm/tests/test_svm.py::test_linearsvm_liblinear_sample_weight[LinearSVC-params1]", "sklearn/svm/tests/test_svm.py::test_svc_ovr_tie_breaking[NuSVC]", "sklearn/svm/tests/test_svm.py::test_svr_errors", "sklearn/svm/tests/test_svm.py::test_svc_bad_kernel", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[gamma3-The gamma value should be set to 'scale', 'auto' or a positive float value. array([1., 4.]) is not a valid option-NuSVC-data1]", "sklearn/svm/tests/test_svm.py::test_negative_weights_svc_leave_two_labels[partial-mask-label-2-SVC]", "sklearn/svm/tests/test_svm.py::test_liblinear_set_coef", "sklearn/svm/tests/test_svm.py::test_immutable_coef_property", "sklearn/svm/tests/test_svm.py::test_negative_sample_weights_mask_all_samples[weights-are-negative-SVC]", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[gamma4-The gamma value should be set to 'scale', 'auto' or a positive float value. [] is not a valid option-SVC-data0]", "sklearn/svm/tests/test_svm.py::test_linear_svx_uppercase_loss_penality_raises_error", "sklearn/svm/tests/test_svm.py::test_hasattr_predict_proba", "sklearn/svm/tests/test_svm.py::test_linearsvm_liblinear_sample_weight[LinearSVR-params4]", "sklearn/svm/tests/test_svm.py::test_svm_classifier_sided_sample_weight[estimator0]", "sklearn/svm/tests/test_svm.py::test_svc_raises_error_internal_representation", "sklearn/svm/tests/test_svm.py::test_decision_function", "sklearn/svm/tests/test_svm.py::test_svm_regressor_sided_sample_weight[estimator0]", "sklearn/svm/tests/test_svm.py::test_n_iter_libsvm[dataset1-SVC-ndarray]", "sklearn/svm/tests/test_svm.py::test_linearsvc_verbose", "sklearn/svm/tests/test_svm.py::test_decision_function_shape_two_class", "sklearn/svm/tests/test_svm.py::test_oneclass", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[gamma3-The gamma value should be set to 'scale', 'auto' or a positive float value. array([1., 4.]) is not a valid option-SVC-data0]", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[gamma5-The gamma value should be set to 'scale', 'auto' or a positive float value. {} is not a valid option-SVC-data0]", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[gamma5-The gamma value should be set to 'scale', 'auto' or a positive float value. {} is not a valid option-OneClassSVM-data4]", "sklearn/svm/tests/test_svm.py::test_negative_sample_weights_mask_all_samples[weights-are-zero-SVC]", "sklearn/svm/tests/test_svm.py::test_negative_weights_svc_leave_just_one_label[mask-label-2-NuSVC]", "sklearn/svm/tests/test_svm.py::test_negative_weights_svc_leave_two_labels[partial-mask-label-2-NuSVC]", "sklearn/svm/tests/test_svm.py::test_custom_kernel_not_array_input[SVC]", "sklearn/svm/tests/test_svm.py::test_precomputed", "sklearn/svm/tests/test_svm.py::test_unicode_kernel", "sklearn/svm/tests/test_svm.py::test_linearsvm_liblinear_sample_weight[LinearSVR-params6]", "sklearn/svm/tests/test_svm.py::test_decision_function_shape[SVC]", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[gamma5-The gamma value should be set to 'scale', 'auto' or a positive float value. {} is not a valid option-SVR-data2]", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[0.0-gamma value must be > 0; 0.0 is invalid. Use a positive number or use 'auto' to set gamma to a value of 1 / n_features.-NuSVR-data3]", "sklearn/svm/tests/test_svm.py::test_linear_svc_intercept_scaling", "sklearn/svm/tests/test_svm.py::test_linearsvr", "sklearn/svm/tests/test_svm.py::test_n_iter_libsvm[dataset0-NuSVR-int]", "sklearn/svm/tests/test_svm.py::test_negative_weights_svc_leave_two_labels[partial-mask-label-1-SVC]", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[auto_deprecated-When 'gamma' is a string, it should be either 'scale' or 'auto'-OneClassSVM-data4]", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[gamma3-The gamma value should be set to 'scale', 'auto' or a positive float value. array([1., 4.]) is not a valid option-NuSVR-data3]", "sklearn/svm/tests/test_svm.py::test_n_iter_libsvm[dataset2-SVC-ndarray]", "sklearn/svm/tests/test_svm.py::test_linearsvc_crammer_singer", "sklearn/svm/tests/test_svm.py::test_oneclass_fit_params_is_deprecated", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[-1-gamma value must be > 0; -1 is invalid. Use a positive number or use 'auto' to set gamma to a value of 1 / n_features.-NuSVC-data1]", "sklearn/svm/tests/test_svm.py::test_libsvm_convergence_warnings", "sklearn/svm/tests/test_svm.py::test_n_iter_libsvm[dataset0-SVC-ndarray]", "sklearn/svm/tests/test_svm.py::test_n_iter_libsvm[dataset0-SVR-int]", "sklearn/svm/tests/test_svm.py::test_linearsvc_iris", "sklearn/svm/tests/test_svm.py::test_unfitted", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[gamma4-The gamma value should be set to 'scale', 'auto' or a positive float value. [] is not a valid option-NuSVR-data3]", "sklearn/svm/tests/test_svm.py::test_svm_regressor_sided_sample_weight[estimator1]", "sklearn/svm/tests/test_svm.py::test_n_support_oneclass_svr", "sklearn/svm/tests/test_svm.py::test_negative_sample_weights_mask_all_samples[weights-are-zero-SVR]", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[auto_deprecated-When 'gamma' is a string, it should be either 'scale' or 'auto'-SVC-data0]", "sklearn/svm/tests/test_svm.py::test_svr_coef_sign", "sklearn/svm/tests/test_svm.py::test_n_iter_libsvm[dataset0-OneClassSVM-int]", "sklearn/svm/tests/test_svm.py::test_svr", "sklearn/svm/tests/test_svm.py::test_negative_weights_svc_leave_two_labels[partial-mask-label-1-NuSVC]", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[gamma4-The gamma value should be set to 'scale', 'auto' or a positive float value. [] is not a valid option-OneClassSVM-data4]", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[gamma3-The gamma value should be set to 'scale', 'auto' or a positive float value. array([1., 4.]) is not a valid option-SVR-data2]", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[auto_deprecated-When 'gamma' is a string, it should be either 'scale' or 'auto'-SVR-data2]", "sklearn/svm/tests/test_svm.py::test_custom_kernel_not_array_input[SVR]", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[gamma4-The gamma value should be set to 'scale', 'auto' or a positive float value. [] is not a valid option-NuSVC-data1]", "sklearn/svm/tests/test_svm.py::test_weight", "sklearn/svm/tests/test_svm.py::test_svc_invalid_break_ties_param[SVC]", "sklearn/svm/tests/test_svm.py::test_n_iter_libsvm[dataset1-OneClassSVM-int]", "sklearn/svm/tests/test_svm.py::test_probability", "sklearn/svm/tests/test_svm.py::test_oneclass_score_samples", "sklearn/svm/tests/test_svm.py::test_svc_invalid_break_ties_param[NuSVC]", "sklearn/svm/tests/test_svm.py::test_negative_sample_weights_mask_all_samples[weights-are-zero-NuSVC]", "sklearn/svm/tests/test_svm.py::test_negative_weight_equal_coeffs[partial-mask-label-1-NuSVR]", "sklearn/svm/tests/test_svm.py::test_decision_function_shape[NuSVC]", "sklearn/svm/tests/test_svm.py::test_linearsvc", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[auto_deprecated-When 'gamma' is a string, it should be either 'scale' or 'auto'-NuSVR-data3]", "sklearn/svm/tests/test_svm.py::test_svm_gamma_error[0.0-gamma value must be > 0; 0.0 is invalid. Use a positive number or use 'auto' to set gamma to a value of 1 / n_features.-SVR-data2]", "sklearn/svm/tests/test_svm.py::test_linear_svm_convergence_warnings", "sklearn/svm/tests/test_svm.py::test_negative_weight_equal_coeffs[partial-mask-label-1-SVC]" ]
[ "sklearn/svm/tests/test_svm.py::test_svc_nonfinite_params" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 61d5c64255f71..d03ce62dae5b4 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -451,6 +451,12 @@ Changelog\n parameters in `fit` instead of `__init__`.\n :pr:`<PRID>` by :user:`<NAME>`.\n \n+- |Enhancement| :func:`svm.SVR`, :func:`svm.SVC`, :func:`svm.NuSVR`,\n+ :func:`svm.OneClassSVM`, :func:`svm.NuSVC` now raise an error\n+ when the dual-gap estimation produce non-finite parameter weights.\n+ :pr:`<PRID>` by :user:`<NAME>` and\n+ :user:`<NAME>`.\n+\n :mod:`sklearn.utils`\n ....................\n \n" } ]
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 61d5c64255f71..d03ce62dae5b4 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -451,6 +451,12 @@ Changelog parameters in `fit` instead of `__init__`. :pr:`<PRID>` by :user:`<NAME>`. +- |Enhancement| :func:`svm.SVR`, :func:`svm.SVC`, :func:`svm.NuSVR`, + :func:`svm.OneClassSVM`, :func:`svm.NuSVC` now raise an error + when the dual-gap estimation produce non-finite parameter weights. + :pr:`<PRID>` by :user:`<NAME>` and + :user:`<NAME>`. + :mod:`sklearn.utils` ....................
scikit-learn/scikit-learn
scikit-learn__scikit-learn-22254
https://github.com/scikit-learn/scikit-learn/pull/22254
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 38aea32e776aa..3ae1c260570b2 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -413,6 +413,9 @@ Changelog preserve this dtype. :pr:`21534` by :user:`Andrew Knyazev <lobpcg>`. +- |Enhancement| Adds `get_feature_names_out` to :class:`manifold.Isomap` + and :class:`manifold.LocallyLinearEmbedding`. :pr:`22254` by `Thomas Fan`_. + - |Fix| :func:`manifold.spectral_embedding` now uses Gaussian instead of the previous uniform on [0, 1] random initial approximations to eigenvectors in eigen_solvers `lobpcg` and `amg` to improve their numerical stability. diff --git a/sklearn/manifold/_isomap.py b/sklearn/manifold/_isomap.py index 312c1166522ea..98f0e719b7cdd 100644 --- a/sklearn/manifold/_isomap.py +++ b/sklearn/manifold/_isomap.py @@ -10,7 +10,7 @@ from scipy.sparse.csgraph import shortest_path from scipy.sparse.csgraph import connected_components -from ..base import BaseEstimator, TransformerMixin +from ..base import BaseEstimator, TransformerMixin, _ClassNamePrefixFeaturesOutMixin from ..neighbors import NearestNeighbors, kneighbors_graph from ..utils.validation import check_is_fitted from ..decomposition import KernelPCA @@ -19,7 +19,7 @@ from ..externals._packaging.version import parse as parse_version -class Isomap(TransformerMixin, BaseEstimator): +class Isomap(_ClassNamePrefixFeaturesOutMixin, TransformerMixin, BaseEstimator): """Isomap Embedding. Non-linear dimensionality reduction through Isometric Mapping @@ -257,6 +257,7 @@ def _fit_transform(self, X): G *= -0.5 self.embedding_ = self.kernel_pca_.fit_transform(G) + self._n_features_out = self.embedding_.shape[1] def reconstruction_error(self): """Compute the reconstruction error for the embedding. diff --git a/sklearn/manifold/_locally_linear.py b/sklearn/manifold/_locally_linear.py index 32fc3623f8cfb..a9c6ec350b912 100644 --- a/sklearn/manifold/_locally_linear.py +++ b/sklearn/manifold/_locally_linear.py @@ -9,7 +9,12 @@ from scipy.sparse import eye, csr_matrix from scipy.sparse.linalg import eigsh -from ..base import BaseEstimator, TransformerMixin, _UnstableArchMixin +from ..base import ( + BaseEstimator, + TransformerMixin, + _UnstableArchMixin, + _ClassNamePrefixFeaturesOutMixin, +) from ..utils import check_random_state, check_array from ..utils._arpack import _init_arpack_v0 from ..utils.extmath import stable_cumsum @@ -542,7 +547,12 @@ def locally_linear_embedding( ) -class LocallyLinearEmbedding(TransformerMixin, _UnstableArchMixin, BaseEstimator): +class LocallyLinearEmbedding( + _ClassNamePrefixFeaturesOutMixin, + TransformerMixin, + _UnstableArchMixin, + BaseEstimator, +): """Locally Linear Embedding. Read more in the :ref:`User Guide <locally_linear_embedding>`. @@ -728,6 +738,7 @@ def _fit_transform(self, X): reg=self.reg, n_jobs=self.n_jobs, ) + self._n_features_out = self.embedding_.shape[1] def fit(self, X, y=None): """Compute the embedding vectors for data X.
diff --git a/sklearn/manifold/tests/test_isomap.py b/sklearn/manifold/tests/test_isomap.py index fa2f2188e3d6e..68ea433a58b93 100644 --- a/sklearn/manifold/tests/test_isomap.py +++ b/sklearn/manifold/tests/test_isomap.py @@ -1,6 +1,10 @@ from itertools import product import numpy as np -from numpy.testing import assert_almost_equal, assert_array_almost_equal +from numpy.testing import ( + assert_almost_equal, + assert_array_almost_equal, + assert_array_equal, +) import pytest from sklearn import datasets @@ -8,6 +12,7 @@ from sklearn import neighbors from sklearn import pipeline from sklearn import preprocessing +from sklearn.datasets import make_blobs from sklearn.metrics.pairwise import pairwise_distances from scipy.sparse import rand as sparse_rand @@ -220,3 +225,14 @@ def test_multiple_connected_components_metric_precomputed(): X_graph = neighbors.kneighbors_graph(X, n_neighbors=2, mode="distance") with pytest.raises(RuntimeError, match="number of connected components"): manifold.Isomap(n_neighbors=1, metric="precomputed").fit(X_graph) + + +def test_get_feature_names_out(): + """Check get_feature_names_out for Isomap.""" + X, y = make_blobs(random_state=0, n_features=4) + n_components = 2 + + iso = manifold.Isomap(n_components=n_components) + iso.fit_transform(X) + names = iso.get_feature_names_out() + assert_array_equal([f"isomap{i}" for i in range(n_components)], names) diff --git a/sklearn/manifold/tests/test_locally_linear.py b/sklearn/manifold/tests/test_locally_linear.py index 520ba00df2e09..ff93a15c0704d 100644 --- a/sklearn/manifold/tests/test_locally_linear.py +++ b/sklearn/manifold/tests/test_locally_linear.py @@ -1,11 +1,16 @@ from itertools import product import numpy as np -from numpy.testing import assert_almost_equal, assert_array_almost_equal +from numpy.testing import ( + assert_almost_equal, + assert_array_almost_equal, + assert_array_equal, +) from scipy import linalg import pytest from sklearn import neighbors, manifold +from sklearn.datasets import make_blobs from sklearn.manifold._locally_linear import barycenter_kneighbors_graph from sklearn.utils._testing import ignore_warnings @@ -159,3 +164,16 @@ def test_integer_input(): for method in ["standard", "hessian", "modified", "ltsa"]: clf = manifold.LocallyLinearEmbedding(method=method, n_neighbors=10) clf.fit(X) # this previously raised a TypeError + + +def test_get_feature_names_out(): + """Check get_feature_names_out for LocallyLinearEmbedding.""" + X, y = make_blobs(random_state=0, n_features=4) + n_components = 2 + + iso = manifold.LocallyLinearEmbedding(n_components=n_components) + iso.fit(X) + names = iso.get_feature_names_out() + assert_array_equal( + [f"locallylinearembedding{i}" for i in range(n_components)], names + ) diff --git a/sklearn/tests/test_common.py b/sklearn/tests/test_common.py index de00fd713c5c7..de8818b53a477 100644 --- a/sklearn/tests/test_common.py +++ b/sklearn/tests/test_common.py @@ -385,7 +385,6 @@ def test_pandas_column_name_consistency(estimator): "isotonic", "kernel_approximation", "preprocessing", - "manifold", "neural_network", ]
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 38aea32e776aa..3ae1c260570b2 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -413,6 +413,9 @@ Changelog\n preserve this dtype.\n :pr:`21534` by :user:`Andrew Knyazev <lobpcg>`.\n \n+- |Enhancement| Adds `get_feature_names_out` to :class:`manifold.Isomap`\n+ and :class:`manifold.LocallyLinearEmbedding`. :pr:`22254` by `Thomas Fan`_.\n+\n - |Fix| :func:`manifold.spectral_embedding` now uses Gaussian instead of\n the previous uniform on [0, 1] random initial approximations to eigenvectors\n in eigen_solvers `lobpcg` and `amg` to improve their numerical stability.\n" } ]
1.01
755d10a7fcfc44656bbed8d7f00f9e06e505732a
[ "sklearn/manifold/tests/test_isomap.py::test_pipeline", "sklearn/manifold/tests/test_isomap.py::test_different_metric", "sklearn/manifold/tests/test_locally_linear.py::test_integer_input", "sklearn/manifold/tests/test_isomap.py::test_transform", "sklearn/manifold/tests/test_isomap.py::test_isomap_clone_bug", "sklearn/manifold/tests/test_locally_linear.py::test_lle_init_parameters", "sklearn/manifold/tests/test_isomap.py::test_multiple_connected_components_metric_precomputed", "sklearn/manifold/tests/test_isomap.py::test_pipeline_with_nearest_neighbors_transformer", "sklearn/manifold/tests/test_locally_linear.py::test_barycenter_kneighbors_graph", "sklearn/manifold/tests/test_locally_linear.py::test_singular_matrix", "sklearn/manifold/tests/test_isomap.py::test_isomap_reconstruction_error", "sklearn/manifold/tests/test_locally_linear.py::test_lle_manifold", "sklearn/manifold/tests/test_locally_linear.py::test_lle_simple_grid", "sklearn/manifold/tests/test_isomap.py::test_multiple_connected_components", "sklearn/manifold/tests/test_locally_linear.py::test_pipeline", "sklearn/manifold/tests/test_isomap.py::test_sparse_input", "sklearn/manifold/tests/test_isomap.py::test_isomap_simple_grid" ]
[ "sklearn/manifold/tests/test_isomap.py::test_get_feature_names_out", "sklearn/manifold/tests/test_locally_linear.py::test_get_feature_names_out" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 38aea32e776aa..3ae1c260570b2 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -413,6 +413,9 @@ Changelog\n preserve this dtype.\n :pr:`<PRID>` by :user:`<NAME>`.\n \n+- |Enhancement| Adds `get_feature_names_out` to :class:`manifold.Isomap`\n+ and :class:`manifold.LocallyLinearEmbedding`. :pr:`<PRID>` by `<NAME>`_.\n+\n - |Fix| :func:`manifold.spectral_embedding` now uses Gaussian instead of\n the previous uniform on [0, 1] random initial approximations to eigenvectors\n in eigen_solvers `lobpcg` and `amg` to improve their numerical stability.\n" } ]
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 38aea32e776aa..3ae1c260570b2 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -413,6 +413,9 @@ Changelog preserve this dtype. :pr:`<PRID>` by :user:`<NAME>`. +- |Enhancement| Adds `get_feature_names_out` to :class:`manifold.Isomap` + and :class:`manifold.LocallyLinearEmbedding`. :pr:`<PRID>` by `<NAME>`_. + - |Fix| :func:`manifold.spectral_embedding` now uses Gaussian instead of the previous uniform on [0, 1] random initial approximations to eigenvectors in eigen_solvers `lobpcg` and `amg` to improve their numerical stability.
scikit-learn/scikit-learn
scikit-learn__scikit-learn-20860
https://github.com/scikit-learn/scikit-learn/pull/20860
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index fba40e25a9e7e..9c1084e393e8d 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -53,6 +53,12 @@ Changelog :pr:`20880` by :user:`Guillaume Lemaitre <glemaitre>` and :user:`András Simon <simonandras>`. +:mod:`sklearn.pipeline` +....................... + +- |Enhancement| Added support for "passthrough" in :class:`FeatureUnion`. + Setting a transformer to "passthrough" will pass the features unchanged. + :pr:`20860` by :user:`Shubhraneel Pal <shubhraneel>`. Code and Documentation Contributors ----------------------------------- diff --git a/sklearn/pipeline.py b/sklearn/pipeline.py index 9d4997686612b..e2f9b0f0950ec 100644 --- a/sklearn/pipeline.py +++ b/sklearn/pipeline.py @@ -17,6 +17,7 @@ from joblib import Parallel from .base import clone, TransformerMixin +from .preprocessing import FunctionTransformer from .utils._estimator_html_repr import _VisualBlock from .utils.metaestimators import available_if from .utils import ( @@ -853,8 +854,9 @@ class FeatureUnion(TransformerMixin, _BaseComposition): Parameters of the transformers may be set using its name and the parameter name separated by a '__'. A transformer may be replaced entirely by - setting the parameter with its name to another transformer, - or removed by setting to 'drop'. + setting the parameter with its name to another transformer, removed by + setting to 'drop' or disabled by setting to 'passthrough' (features are + passed without transformation). Read more in the :ref:`User Guide <feature_union>`. @@ -862,12 +864,14 @@ class FeatureUnion(TransformerMixin, _BaseComposition): Parameters ---------- - transformer_list : list of tuple - List of tuple containing `(str, transformer)`. The first element - of the tuple is name affected to the transformer while the - second element is a scikit-learn transformer instance. - The transformer instance can also be `"drop"` for it to be - ignored. + transformer_list : list of (str, transformer) tuples + List of transformer objects to be applied to the data. The first + half of each tuple is the name of the transformer. The transformer can + be 'drop' for it to be ignored or can be 'passthrough' for features to + be passed unchanged. + + .. versionadded:: 1.1 + Added the option `"passthrough"`. .. versionchanged:: 0.22 Deprecated `None` as a transformer in favor of 'drop'. @@ -977,7 +981,7 @@ def _validate_transformers(self): # validate estimators for t in transformers: - if t == "drop": + if t in ("drop", "passthrough"): continue if not (hasattr(t, "fit") or hasattr(t, "fit_transform")) or not hasattr( t, "transform" @@ -1004,12 +1008,15 @@ def _iter(self): Generate (name, trans, weight) tuples excluding None and 'drop' transformers. """ + get_weight = (self.transformer_weights or {}).get - return ( - (name, trans, get_weight(name)) - for name, trans in self.transformer_list - if trans != "drop" - ) + + for name, trans in self.transformer_list: + if trans == "drop": + continue + if trans == "passthrough": + trans = FunctionTransformer() + yield (name, trans, get_weight(name)) @deprecated( "get_feature_names is deprecated in 1.0 and will be removed "
diff --git a/sklearn/tests/test_pipeline.py b/sklearn/tests/test_pipeline.py index 445bd9064b959..fa01b6e834b11 100644 --- a/sklearn/tests/test_pipeline.py +++ b/sklearn/tests/test_pipeline.py @@ -1004,6 +1004,60 @@ def test_set_feature_union_step_drop(get_names): assert not record +def test_set_feature_union_passthrough(): + """Check the behaviour of setting a transformer to `"passthrough"`.""" + mult2 = Mult(2) + mult3 = Mult(3) + X = np.asarray([[1]]) + + ft = FeatureUnion([("m2", mult2), ("m3", mult3)]) + assert_array_equal([[2, 3]], ft.fit(X).transform(X)) + assert_array_equal([[2, 3]], ft.fit_transform(X)) + + ft.set_params(m2="passthrough") + assert_array_equal([[1, 3]], ft.fit(X).transform(X)) + assert_array_equal([[1, 3]], ft.fit_transform(X)) + + ft.set_params(m3="passthrough") + assert_array_equal([[1, 1]], ft.fit(X).transform(X)) + assert_array_equal([[1, 1]], ft.fit_transform(X)) + + # check we can change back + ft.set_params(m3=mult3) + assert_array_equal([[1, 3]], ft.fit(X).transform(X)) + assert_array_equal([[1, 3]], ft.fit_transform(X)) + + # Check 'passthrough' step at construction time + ft = FeatureUnion([("m2", "passthrough"), ("m3", mult3)]) + assert_array_equal([[1, 3]], ft.fit(X).transform(X)) + assert_array_equal([[1, 3]], ft.fit_transform(X)) + + X = iris.data + columns = X.shape[1] + pca = PCA(n_components=2, svd_solver="randomized", random_state=0) + + ft = FeatureUnion([("passthrough", "passthrough"), ("pca", pca)]) + assert_array_equal(X, ft.fit(X).transform(X)[:, :columns]) + assert_array_equal(X, ft.fit_transform(X)[:, :columns]) + + ft.set_params(pca="passthrough") + X_ft = ft.fit(X).transform(X) + assert_array_equal(X_ft, np.hstack([X, X])) + X_ft = ft.fit_transform(X) + assert_array_equal(X_ft, np.hstack([X, X])) + + ft.set_params(passthrough=pca) + assert_array_equal(X, ft.fit(X).transform(X)[:, -columns:]) + assert_array_equal(X, ft.fit_transform(X)[:, -columns:]) + + ft = FeatureUnion( + [("passthrough", "passthrough"), ("pca", pca)], + transformer_weights={"passthrough": 2}, + ) + assert_array_equal(X * 2, ft.fit(X).transform(X)[:, :columns]) + assert_array_equal(X * 2, ft.fit_transform(X)[:, :columns]) + + def test_step_name_validation(): error_message_1 = r"Estimator names must not contain __: got \['a__q'\]" error_message_2 = r"Names provided are not unique: \['a', 'a'\]"
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex fba40e25a9e7e..9c1084e393e8d 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -53,6 +53,12 @@ Changelog\n :pr:`20880` by :user:`Guillaume Lemaitre <glemaitre>`\n and :user:`András Simon <simonandras>`.\n \n+:mod:`sklearn.pipeline`\n+.......................\n+\n+- |Enhancement| Added support for \"passthrough\" in :class:`FeatureUnion`.\n+ Setting a transformer to \"passthrough\" will pass the features unchanged.\n+ :pr:`20860` by :user:`Shubhraneel Pal <shubhraneel>`.\n \n Code and Documentation Contributors\n -----------------------------------\n" } ]
1.01
40e1f895b172b9941fdcdefffd5a2aa8556ed227
[ "sklearn/tests/test_pipeline.py::test_fit_predict_with_intermediate_fit_params", "sklearn/tests/test_pipeline.py::test_pipeline_feature_names_out_error_without_definition", "sklearn/tests/test_pipeline.py::test_score_samples_on_pipeline_without_score_samples", "sklearn/tests/test_pipeline.py::test_set_feature_union_steps[get_feature_names_out]", "sklearn/tests/test_pipeline.py::test_pipeline_get_tags_none[None]", "sklearn/tests/test_pipeline.py::test_pipeline_correctly_adjusts_steps[None]", "sklearn/tests/test_pipeline.py::test_search_cv_using_minimal_compatible_estimator[MinimalRegressor]", "sklearn/tests/test_pipeline.py::test_feature_union_fit_params", "sklearn/tests/test_pipeline.py::test_pipeline_slice[1-None]", "sklearn/tests/test_pipeline.py::test_verbose[est6-\\\\[Pipeline\\\\].*\\\\(step 1 of 2\\\\) Processing transf.* total=.*\\\\n\\\\[Pipeline\\\\].*\\\\(step 2 of 2\\\\) Processing clf.* total=.*\\\\n$-fit]", "sklearn/tests/test_pipeline.py::test_pipeline_sample_weight_unsupported", "sklearn/tests/test_pipeline.py::test_step_name_validation", "sklearn/tests/test_pipeline.py::test_verbose[est15-\\\\[FeatureUnion\\\\].*\\\\(step 1 of 1\\\\) Processing mult2.* total=.*\\\\n$-fit_transform]", "sklearn/tests/test_pipeline.py::test_pipeline_with_cache_attribute", "sklearn/tests/test_pipeline.py::test_verbose[est11-\\\\[Pipeline\\\\].*\\\\(step 1 of 2\\\\) Processing transf.* total=.*\\\\n\\\\[Pipeline\\\\].*\\\\(step 2 of 2\\\\) Processing mult.* total=.*\\\\n$-fit_transform]", "sklearn/tests/test_pipeline.py::test_predict_methods_with_predict_params[predict]", "sklearn/tests/test_pipeline.py::test_fit_predict_on_pipeline_without_fit_predict", "sklearn/tests/test_pipeline.py::test_make_pipeline", "sklearn/tests/test_pipeline.py::test_make_pipeline_memory", "sklearn/tests/test_pipeline.py::test_pipeline_methods_anova", "sklearn/tests/test_pipeline.py::test_n_features_in_pipeline", "sklearn/tests/test_pipeline.py::test_pipeline_sample_weight_supported", "sklearn/tests/test_pipeline.py::test_verbose[est13-\\\\[FeatureUnion\\\\].*\\\\(step 1 of 2\\\\) Processing mult1.* total=.*\\\\n\\\\[FeatureUnion\\\\].*\\\\(step 2 of 2\\\\) Processing mult2.* total=.*\\\\n$-fit_transform]", "sklearn/tests/test_pipeline.py::test_verbose[est9-\\\\[Pipeline\\\\].*\\\\(step 1 of 2\\\\) Processing transf.* total=.*\\\\n\\\\[Pipeline\\\\].*\\\\(step 2 of 2\\\\) Processing mult.* total=.*\\\\n$-fit_transform]", "sklearn/tests/test_pipeline.py::test_pipeline_slice[1-2]", "sklearn/tests/test_pipeline.py::test_pipeline_missing_values_leniency", "sklearn/tests/test_pipeline.py::test_predict_methods_with_predict_params[predict_log_proba]", "sklearn/tests/test_pipeline.py::test_pipeline_fit_params", "sklearn/tests/test_pipeline.py::test_verbose[est5-\\\\[Pipeline\\\\].*\\\\(step 1 of 3\\\\) Processing transf.* total=.*\\\\n\\\\[Pipeline\\\\].*\\\\(step 2 of 3\\\\) Processing noop.* total=.*\\\\n\\\\[Pipeline\\\\].*\\\\(step 3 of 3\\\\) Processing clf.* total=.*\\\\n$-fit_predict]", "sklearn/tests/test_pipeline.py::test_pipeline_score_samples_pca_lof", "sklearn/tests/test_pipeline.py::test_verbose[est4-\\\\[Pipeline\\\\].*\\\\(step 1 of 3\\\\) Processing transf.* total=.*\\\\n\\\\[Pipeline\\\\].*\\\\(step 2 of 3\\\\) Processing noop.* total=.*\\\\n\\\\[Pipeline\\\\].*\\\\(step 3 of 3\\\\) Processing clf.* total=.*\\\\n$-fit]", "sklearn/tests/test_pipeline.py::test_feature_union_warns_unknown_transformer_weight", "sklearn/tests/test_pipeline.py::test_pipeline_methods_pca_svm", "sklearn/tests/test_pipeline.py::test_verbose[est14-\\\\[FeatureUnion\\\\].*\\\\(step 1 of 1\\\\) Processing mult2.* total=.*\\\\n$-fit]", "sklearn/tests/test_pipeline.py::test_verbose[est3-\\\\[Pipeline\\\\].*\\\\(step 1 of 3\\\\) Processing transf.* total=.*\\\\n\\\\[Pipeline\\\\].*\\\\(step 2 of 3\\\\) Processing noop.* total=.*\\\\n\\\\[Pipeline\\\\].*\\\\(step 3 of 3\\\\) Processing clf.* total=.*\\\\n$-fit_predict]", "sklearn/tests/test_pipeline.py::test_pipeline_index", "sklearn/tests/test_pipeline.py::test_pipeline_raise_set_params_error", "sklearn/tests/test_pipeline.py::test_predict_methods_with_predict_params[predict_proba]", "sklearn/tests/test_pipeline.py::test_set_pipeline_step_passthrough[passthrough]", "sklearn/tests/test_pipeline.py::test_set_params_nested_pipeline", "sklearn/tests/test_pipeline.py::test_set_pipeline_steps", "sklearn/tests/test_pipeline.py::test_pipeline_init_tuple", "sklearn/tests/test_pipeline.py::test_verbose[est0-\\\\[Pipeline\\\\].*\\\\(step 1 of 2\\\\) Processing transf.* total=.*\\\\n\\\\[Pipeline\\\\].*\\\\(step 2 of 2\\\\) Processing clf.* total=.*\\\\n$-fit]", "sklearn/tests/test_pipeline.py::test_pipeline_slice[1-3]", "sklearn/tests/test_pipeline.py::test_verbose[est12-\\\\[FeatureUnion\\\\].*\\\\(step 1 of 2\\\\) Processing mult1.* total=.*\\\\n\\\\[FeatureUnion\\\\].*\\\\(step 2 of 2\\\\) Processing mult2.* total=.*\\\\n$-fit]", "sklearn/tests/test_pipeline.py::test_pipeline_fit_transform", "sklearn/tests/test_pipeline.py::test_make_union", "sklearn/tests/test_pipeline.py::test_pipeline_get_tags_none[passthrough]", "sklearn/tests/test_pipeline.py::test_make_union_kwargs", "sklearn/tests/test_pipeline.py::test_feature_union_feature_names[get_feature_names]", "sklearn/tests/test_pipeline.py::test_verbose[est2-\\\\[Pipeline\\\\].*\\\\(step 1 of 3\\\\) Processing transf.* total=.*\\\\n\\\\[Pipeline\\\\].*\\\\(step 2 of 3\\\\) Processing noop.* total=.*\\\\n\\\\[Pipeline\\\\].*\\\\(step 3 of 3\\\\) Processing clf.* total=.*\\\\n$-fit]", "sklearn/tests/test_pipeline.py::test_feature_union_feature_names[get_feature_names_out]", "sklearn/tests/test_pipeline.py::test_verbose[est7-\\\\[Pipeline\\\\].*\\\\(step 1 of 2\\\\) Processing transf.* total=.*\\\\n\\\\[Pipeline\\\\].*\\\\(step 2 of 2\\\\) Processing clf.* total=.*\\\\n$-fit_transform]", "sklearn/tests/test_pipeline.py::test_pipeline_slice[0-2]", "sklearn/tests/test_pipeline.py::test_set_pipeline_step_passthrough[None]", "sklearn/tests/test_pipeline.py::test_verbose[est8-\\\\[Pipeline\\\\].*\\\\(step 1 of 2\\\\) Processing transf.* total=.*\\\\n\\\\[Pipeline\\\\].*\\\\(step 2 of 2\\\\) Processing mult.* total=.*\\\\n$-fit]", "sklearn/tests/test_pipeline.py::test_feature_union_get_feature_names_deprecated", "sklearn/tests/test_pipeline.py::test_pipeline_ducktyping", "sklearn/tests/test_pipeline.py::test_pipeline_wrong_memory", "sklearn/tests/test_pipeline.py::test_fit_predict_on_pipeline", "sklearn/tests/test_pipeline.py::test_classes_property", "sklearn/tests/test_pipeline.py::test_features_names_passthrough", "sklearn/tests/test_pipeline.py::test_pipeline_slice[0-1]", "sklearn/tests/test_pipeline.py::test_pipeline_param_error", "sklearn/tests/test_pipeline.py::test_feature_union_weights", "sklearn/tests/test_pipeline.py::test_pipeline_check_if_fitted", "sklearn/tests/test_pipeline.py::test_feature_union_parallel", "sklearn/tests/test_pipeline.py::test_set_feature_union_steps[get_feature_names]", "sklearn/tests/test_pipeline.py::test_feature_names_count_vectorizer", "sklearn/tests/test_pipeline.py::test_verbose[est10-\\\\[Pipeline\\\\].*\\\\(step 1 of 2\\\\) Processing transf.* total=.*\\\\n\\\\[Pipeline\\\\].*\\\\(step 2 of 2\\\\) Processing mult.* total=.*\\\\n$-fit]", "sklearn/tests/test_pipeline.py::test_pipeline_named_steps", "sklearn/tests/test_pipeline.py::test_pipeline_correctly_adjusts_steps[passthrough]", "sklearn/tests/test_pipeline.py::test_pipeline_memory", "sklearn/tests/test_pipeline.py::test_pipeline_slice[None-None]", "sklearn/tests/test_pipeline.py::test_search_cv_using_minimal_compatible_estimator[MinimalClassifier]", "sklearn/tests/test_pipeline.py::test_pipeline_slice[None-1]", "sklearn/tests/test_pipeline.py::test_pipeline_methods_preprocessing_svm", "sklearn/tests/test_pipeline.py::test_verbose[est1-\\\\[Pipeline\\\\].*\\\\(step 1 of 2\\\\) Processing transf.* total=.*\\\\n\\\\[Pipeline\\\\].*\\\\(step 2 of 2\\\\) Processing clf.* total=.*\\\\n$-fit_predict]", "sklearn/tests/test_pipeline.py::test_pipeline_transform", "sklearn/tests/test_pipeline.py::test_n_features_in_feature_union" ]
[ "sklearn/tests/test_pipeline.py::test_set_feature_union_passthrough" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex fba40e25a9e7e..9c1084e393e8d 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -53,6 +53,12 @@ Changelog\n :pr:`<PRID>` by :user:`<NAME>`\n and :user:`<NAME>`.\n \n+:mod:`sklearn.pipeline`\n+.......................\n+\n+- |Enhancement| Added support for \"passthrough\" in :class:`FeatureUnion`.\n+ Setting a transformer to \"passthrough\" will pass the features unchanged.\n+ :pr:`<PRID>` by :user:`<NAME>`.\n \n Code and Documentation Contributors\n -----------------------------------\n" } ]
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index fba40e25a9e7e..9c1084e393e8d 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -53,6 +53,12 @@ Changelog :pr:`<PRID>` by :user:`<NAME>` and :user:`<NAME>`. +:mod:`sklearn.pipeline` +....................... + +- |Enhancement| Added support for "passthrough" in :class:`FeatureUnion`. + Setting a transformer to "passthrough" will pass the features unchanged. + :pr:`<PRID>` by :user:`<NAME>`. Code and Documentation Contributors -----------------------------------
scikit-learn/scikit-learn
scikit-learn__scikit-learn-22548
https://github.com/scikit-learn/scikit-learn/pull/22548
diff --git a/doc/modules/linear_model.rst b/doc/modules/linear_model.rst index 6d176e8482537..24dfa901b1d42 100644 --- a/doc/modules/linear_model.rst +++ b/doc/modules/linear_model.rst @@ -1032,7 +1032,7 @@ reproductive exponential dispersion model (EDM) [11]_). The minimization problem becomes: -.. math:: \min_{w} \frac{1}{2 n_{\text{samples}}} \sum_i d(y_i, \hat{y}_i) + \frac{\alpha}{2} ||w||_2, +.. math:: \min_{w} \frac{1}{2 n_{\text{samples}}} \sum_i d(y_i, \hat{y}_i) + \frac{\alpha}{2} ||w||_2^2, where :math:`\alpha` is the L2 regularization penalty. When sample weights are provided, the average becomes a weighted average. diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index f64a6bda6ea95..13b473fba11a9 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -557,6 +557,12 @@ Changelog :pr:`21808`, :pr:`20567` and :pr:`21814` by :user:`Christian Lorentzen <lorentzenchr>`. +- |Enhancement| :class:`~linear_model.GammaRegressor`, + :class:`~linear_model.PoissonRegressor` and :class:`~linear_model.TweedieRegressor` + are faster for ``solvers="lbfgs"``. + :pr:`22548`, :pr:`21808` and :pr:`20567` by + :user:`Christian Lorentzen <lorentzenchr>`. + - |Enhancement| Rename parameter `base_estimator` to `estimator` in :class:`linear_model.RANSACRegressor` to improve readability and consistency. `base_estimator` is deprecated and will be removed in 1.3. @@ -590,6 +596,12 @@ Changelog sub-problem while now all of them are recorded. :pr:`21998` by :user:`Olivier Grisel <ogrisel>`. +- |Fix| The property `family` of :class:`linear_model.TweedieRegressor` is not + validated in `__init__` anymore. Instead, this (private) property is deprecated in + :class:`linear_model.GammaRegressor`, :class:`linear_model.PoissonRegressor` and + :class:`linear_model.TweedieRegressor`, and will be removed in 1.3. + :pr:`22548` by :user:`Christian Lorentzen <lorentzenchr>`. + - |Enhancement| :class:`linear_model.BayesianRidge` and :class:`linear_model.ARDRegression` now preserve float32 dtype. :pr:`9087` by :user:`Arthur Imbert <Henley13>` and :pr:`22525` by :user:`Meekail Zain <micky774>`. diff --git a/sklearn/_loss/__init__.py b/sklearn/_loss/__init__.py index 14548c62231a2..63ae3038df8ae 100644 --- a/sklearn/_loss/__init__.py +++ b/sklearn/_loss/__init__.py @@ -10,6 +10,7 @@ HalfPoissonLoss, HalfGammaLoss, HalfTweedieLoss, + HalfTweedieLossIdentity, HalfBinomialLoss, HalfMultinomialLoss, ) @@ -22,6 +23,7 @@ "HalfPoissonLoss", "HalfGammaLoss", "HalfTweedieLoss", + "HalfTweedieLossIdentity", "HalfBinomialLoss", "HalfMultinomialLoss", ] diff --git a/sklearn/_loss/_loss.pxd b/sklearn/_loss/_loss.pxd index 7255243d331dc..36fc91586a1df 100644 --- a/sklearn/_loss/_loss.pxd +++ b/sklearn/_loss/_loss.pxd @@ -69,6 +69,13 @@ cdef class CyHalfTweedieLoss(CyLossFunction): cdef double_pair cy_grad_hess(self, double y_true, double raw_prediction) nogil +cdef class CyHalfTweedieLossIdentity(CyLossFunction): + cdef readonly double power # readonly makes it accessible from Python + cdef double cy_loss(self, double y_true, double raw_prediction) nogil + cdef double cy_gradient(self, double y_true, double raw_prediction) nogil + cdef double_pair cy_grad_hess(self, double y_true, double raw_prediction) nogil + + cdef class CyHalfBinomialLoss(CyLossFunction): cdef double cy_loss(self, double y_true, double raw_prediction) nogil cdef double cy_gradient(self, double y_true, double raw_prediction) nogil diff --git a/sklearn/_loss/_loss.pyx.tp b/sklearn/_loss/_loss.pyx.tp index 5565cc108af07..af637d34eba16 100644 --- a/sklearn/_loss/_loss.pyx.tp +++ b/sklearn/_loss/_loss.pyx.tp @@ -1,7 +1,7 @@ {{py: """ -Template file for easily generate loops over samples using Tempita +Template file to easily generate loops over samples using Tempita (https://github.com/cython/cython/blob/master/Cython/Tempita/_tempita.py). Generated file: _loss.pyx @@ -117,6 +117,28 @@ doc_HalfTweedieLoss = ( """ ) +doc_HalfTweedieLossIdentity = ( + """Half Tweedie deviance loss with identity link. + + Domain: + y_true in real numbers if p <= 0 + y_true in non-negative real numbers if 0 < p < 2 + y_true in positive real numbers if p >= 2 + y_pred and power in positive real numbers, y_pred may be negative for p=0. + + Link: + y_pred = raw_prediction + + Half Tweedie deviance with identity link and p=power is + max(y_true, 0)**(2-p) / (1-p) / (2-p) + - y_true * y_pred**(1-p) / (1-p) + + y_pred**(2-p) / (2-p) + + Notes: + - Here, we do not drop constant terms in contrast to the version with log-link. + """ +) + doc_HalfBinomialLoss = ( """Half Binomial deviance loss with logit link. @@ -151,6 +173,9 @@ class_list = [ ("CyHalfTweedieLoss", doc_HalfTweedieLoss, "power", "closs_half_tweedie", "closs_grad_half_tweedie", "cgradient_half_tweedie", "cgrad_hess_half_tweedie"), + ("CyHalfTweedieLossIdentity", doc_HalfTweedieLossIdentity, "power", + "closs_half_tweedie_identity", "closs_grad_half_tweedie_identity", + "cgradient_half_tweedie_identity", "cgrad_hess_half_tweedie_identity"), ("CyHalfBinomialLoss", doc_HalfBinomialLoss, None, "closs_half_binomial", "closs_grad_half_binomial", "cgradient_half_binomial", "cgrad_hess_half_binomial"), @@ -194,7 +219,7 @@ from cython.parallel import parallel, prange import numpy as np cimport numpy as np -from libc.math cimport exp, fabs, log, log1p +from libc.math cimport exp, fabs, log, log1p, pow from libc.stdlib cimport malloc, free np.import_array() @@ -420,7 +445,7 @@ cdef inline double_pair cgrad_hess_half_gamma( # Half Tweedie Deviance with Log-Link, dropping constant terms -# Note that by dropping constants this is no longer smooth in parameter power. +# Note that by dropping constants this is no longer continuous in parameter power. cdef inline double closs_half_tweedie( double y_true, double raw_prediction, @@ -501,6 +526,102 @@ cdef inline double_pair cgrad_hess_half_tweedie( return gh +# Half Tweedie Deviance with identity link, without dropping constant terms! +# Therefore, best loss value is zero. +cdef inline double closs_half_tweedie_identity( + double y_true, + double raw_prediction, + double power +) nogil: + cdef double tmp + if power == 0.: + return closs_half_squared_error(y_true, raw_prediction) + elif power == 1.: + if y_true == 0: + return raw_prediction + else: + return y_true * log(y_true/raw_prediction) + raw_prediction - y_true + elif power == 2.: + return log(raw_prediction/y_true) + y_true/raw_prediction - 1. + else: + tmp = pow(raw_prediction, 1. - power) + tmp = raw_prediction * tmp / (2. - power) - y_true * tmp / (1. - power) + if y_true > 0: + tmp += pow(y_true, 2. - power) / ((1. - power) * (2. - power)) + return tmp + + +cdef inline double cgradient_half_tweedie_identity( + double y_true, + double raw_prediction, + double power +) nogil: + if power == 0.: + return raw_prediction - y_true + elif power == 1.: + return 1. - y_true / raw_prediction + elif power == 2.: + return (raw_prediction - y_true) / (raw_prediction * raw_prediction) + else: + return pow(raw_prediction, -power) * (raw_prediction - y_true) + + +cdef inline double_pair closs_grad_half_tweedie_identity( + double y_true, + double raw_prediction, + double power +) nogil: + cdef double_pair lg + cdef double tmp + if power == 0.: + lg.val2 = raw_prediction - y_true # gradient + lg.val1 = 0.5 * lg.val2 * lg.val2 # loss + elif power == 1.: + if y_true == 0: + lg.val1 = raw_prediction + else: + lg.val1 = (y_true * log(y_true/raw_prediction) # loss + + raw_prediction - y_true) + lg.val2 = 1. - y_true / raw_prediction # gradient + elif power == 2.: + lg.val1 = log(raw_prediction/y_true) + y_true/raw_prediction - 1. # loss + tmp = raw_prediction * raw_prediction + lg.val2 = (raw_prediction - y_true) / tmp # gradient + else: + tmp = pow(raw_prediction, 1. - power) + lg.val1 = (raw_prediction * tmp / (2. - power) # loss + - y_true * tmp / (1. - power)) + if y_true > 0: + lg.val1 += (pow(y_true, 2. - power) + / ((1. - power) * (2. - power))) + lg.val2 = tmp * (1. - y_true / raw_prediction) # gradient + return lg + + +cdef inline double_pair cgrad_hess_half_tweedie_identity( + double y_true, + double raw_prediction, + double power +) nogil: + cdef double_pair gh + cdef double tmp + if power == 0.: + gh.val1 = raw_prediction - y_true # gradient + gh.val2 = 1. # hessian + elif power == 1.: + gh.val1 = 1. - y_true / raw_prediction # gradient + gh.val2 = y_true / (raw_prediction * raw_prediction) # hessian + elif power == 2.: + tmp = raw_prediction * raw_prediction + gh.val1 = (raw_prediction - y_true) / tmp # gradient + gh.val2 = (-1. + 2. * y_true / raw_prediction) / tmp # hessian + else: + tmp = pow(raw_prediction, -power) + gh.val1 = tmp * (raw_prediction - y_true) # gradient + gh.val2 = tmp * ((1. - power) + power * y_true / raw_prediction) # hessian + return gh + + # Half Binomial deviance with logit-link, aka log-loss or binary cross entropy cdef inline double closs_half_binomial( double y_true, diff --git a/sklearn/_loss/glm_distribution.py b/sklearn/_loss/glm_distribution.py index dfc512c8b10b7..6fbe675fef533 100644 --- a/sklearn/_loss/glm_distribution.py +++ b/sklearn/_loss/glm_distribution.py @@ -4,6 +4,10 @@ # Author: Christian Lorentzen <[email protected]> # License: BSD 3 clause +# +# TODO(1.3): remove file +# This is only used for backward compatibility in _GeneralizedLinearRegressor +# for the deprecated family attribute. from abc import ABCMeta, abstractmethod from collections import namedtuple diff --git a/sklearn/_loss/link.py b/sklearn/_loss/link.py index 18ad5901d1f3c..68d1b89116b99 100644 --- a/sklearn/_loss/link.py +++ b/sklearn/_loss/link.py @@ -1,7 +1,7 @@ """ Module contains classes for invertible (and differentiable) link functions. """ -# Author: Christian Lorentzen <[email protected]> +# Author: Christian Lorentzen <[email protected]> from abc import ABC, abstractmethod from dataclasses import dataclass @@ -23,7 +23,7 @@ def __post_init__(self): """Check that low <= high""" if self.low > self.high: raise ValueError( - f"On must have low <= high; got low={self.low}, high={self.high}." + f"One must have low <= high; got low={self.low}, high={self.high}." ) def includes(self, x): diff --git a/sklearn/_loss/loss.py b/sklearn/_loss/loss.py index d7dbdf44b8c3e..5eb58bb0c27f9 100644 --- a/sklearn/_loss/loss.py +++ b/sklearn/_loss/loss.py @@ -25,6 +25,7 @@ CyHalfPoissonLoss, CyHalfGammaLoss, CyHalfTweedieLoss, + CyHalfTweedieLossIdentity, CyHalfBinomialLoss, CyHalfMultinomialLoss, ) @@ -770,6 +771,52 @@ def constant_to_optimal_zero(self, y_true, sample_weight=None): return term +class HalfTweedieLossIdentity(BaseLoss): + """Half Tweedie deviance loss with identity link, for regression. + + Domain: + y_true in real numbers for power <= 0 + y_true in non-negative real numbers for 0 < power < 2 + y_true in positive real numbers for 2 <= power + y_pred in positive real numbers for power != 0 + y_pred in real numbers for power = 0 + power in real numbers + + Link: + y_pred = raw_prediction + + For a given sample x_i, half Tweedie deviance loss with p=power is defined + as:: + + loss(x_i) = max(y_true_i, 0)**(2-p) / (1-p) / (2-p) + - y_true_i * raw_prediction_i**(1-p) / (1-p) + + raw_prediction_i**(2-p) / (2-p) + + Note that the minimum value of this loss is 0. + + Note furthermore that although no Tweedie distribution exists for + 0 < power < 1, it still gives a strictly consistent scoring function for + the expectation. + """ + + def __init__(self, sample_weight=None, power=1.5): + super().__init__( + closs=CyHalfTweedieLossIdentity(power=float(power)), + link=IdentityLink(), + ) + if self.closs.power <= 0: + self.interval_y_true = Interval(-np.inf, np.inf, False, False) + elif self.closs.power < 2: + self.interval_y_true = Interval(0, np.inf, True, False) + else: + self.interval_y_true = Interval(0, np.inf, False, False) + + if self.closs.power == 0: + self.interval_y_pred = Interval(-np.inf, np.inf, False, False) + else: + self.interval_y_pred = Interval(0, np.inf, False, False) + + class HalfBinomialLoss(BaseLoss): """Half Binomial deviance loss with logit link, for binary classification. diff --git a/sklearn/linear_model/_glm/__init__.py b/sklearn/linear_model/_glm/__init__.py index e5d944fc225a4..fea9c4d4cf6ba 100644 --- a/sklearn/linear_model/_glm/__init__.py +++ b/sklearn/linear_model/_glm/__init__.py @@ -1,14 +1,14 @@ # License: BSD 3 clause from .glm import ( - GeneralizedLinearRegressor, + _GeneralizedLinearRegressor, PoissonRegressor, GammaRegressor, TweedieRegressor, ) __all__ = [ - "GeneralizedLinearRegressor", + "_GeneralizedLinearRegressor", "PoissonRegressor", "GammaRegressor", "TweedieRegressor", diff --git a/sklearn/linear_model/_glm/glm.py b/sklearn/linear_model/_glm/glm.py index d7af8ae60d8b6..68aa4ea0df22c 100644 --- a/sklearn/linear_model/_glm/glm.py +++ b/sklearn/linear_model/_glm/glm.py @@ -2,7 +2,7 @@ Generalized Linear Models with Exponential Dispersion Family """ -# Author: Christian Lorentzen <[email protected]> +# Author: Christian Lorentzen <[email protected]> # some parts and tricks stolen from other sklearn files. # License: BSD 3 clause @@ -11,57 +11,42 @@ import numpy as np import scipy.optimize +from ..._loss.glm_distribution import TweedieDistribution +from ..._loss.loss import ( + HalfGammaLoss, + HalfPoissonLoss, + HalfSquaredError, + HalfTweedieLoss, + HalfTweedieLossIdentity, +) from ...base import BaseEstimator, RegressorMixin from ...utils.optimize import _check_optimize_result -from ...utils import check_scalar +from ...utils import check_scalar, check_array, deprecated from ...utils.validation import check_is_fitted, _check_sample_weight -from ..._loss.glm_distribution import ( - ExponentialDispersionModel, - TweedieDistribution, - EDM_DISTRIBUTIONS, -) -from .link import ( - BaseLink, - IdentityLink, - LogLink, -) - - -def _safe_lin_pred(X, coef): - """Compute the linear predictor taking care if intercept is present.""" - if coef.size == X.shape[1] + 1: - return X @ coef[1:] + coef[0] - else: - return X @ coef +from ...utils._openmp_helpers import _openmp_effective_n_threads +from .._linear_loss import LinearModelLoss -def _y_pred_deviance_derivative(coef, X, y, weights, family, link): - """Compute y_pred and the derivative of the deviance w.r.t coef.""" - lin_pred = _safe_lin_pred(X, coef) - y_pred = link.inverse(lin_pred) - d1 = link.inverse_derivative(lin_pred) - temp = d1 * family.deviance_derivative(y, y_pred, weights) - if coef.size == X.shape[1] + 1: - devp = np.concatenate(([temp.sum()], temp @ X)) - else: - devp = temp @ X # same as X.T @ temp - return y_pred, devp - - -class GeneralizedLinearRegressor(RegressorMixin, BaseEstimator): +class _GeneralizedLinearRegressor(RegressorMixin, BaseEstimator): """Regression via a penalized Generalized Linear Model (GLM). - GLMs based on a reproductive Exponential Dispersion Model (EDM) aim at - fitting and predicting the mean of the target y as y_pred=h(X*w). - Therefore, the fit minimizes the following objective function with L2 - priors as regularizer:: + GLMs based on a reproductive Exponential Dispersion Model (EDM) aim at fitting and + predicting the mean of the target y as y_pred=h(X*w) with coefficients w. + Therefore, the fit minimizes the following objective function with L2 priors as + regularizer:: - 1/(2*sum(s)) * deviance(y, h(X*w); s) - + 1/2 * alpha * |w|_2 + 1/(2*sum(s_i)) * sum(s_i * deviance(y_i, h(x_i*w)) + 1/2 * alpha * ||w||_2^2 - with inverse link function h and s=sample_weight. + with inverse link function h, s=sample_weight and per observation (unit) deviance + deviance(y_i, h(x_i*w)). Note that for an EDM, 1/2 * deviance is the negative + log-likelihood up to a constant (in w) term. The parameter ``alpha`` corresponds to the lambda parameter in glmnet. + Instead of implementing the EDM family and a link function seperately, we directly + use the loss functions `from sklearn._loss` which have the link functions included + in them for performance reasons. We pick the loss functions that implement + (1/2 times) EDM deviances. + Read more in the :ref:`User Guide <Generalized_linear_regression>`. .. versionadded:: 0.23 @@ -79,20 +64,6 @@ class GeneralizedLinearRegressor(RegressorMixin, BaseEstimator): Specifies if a constant (a.k.a. bias or intercept) should be added to the linear predictor (X @ coef + intercept). - family : {'normal', 'poisson', 'gamma', 'inverse-gaussian'} \ - or an ExponentialDispersionModel instance, default='normal' - The distributional assumption of the GLM, i.e. which distribution from - the EDM, specifies the loss function to be minimized. - - link : {'auto', 'identity', 'log'} or an instance of class BaseLink, \ - default='auto' - The link function of the GLM, i.e. mapping from linear predictor - `X @ coeff + intercept` to prediction `y_pred`. Option 'auto' sets - the link depending on the chosen family as follows: - - - 'identity' for Normal distribution - - 'log' for Poisson, Gamma and Inverse Gaussian distributions - solver : 'lbfgs', default='lbfgs' Algorithm to use in the optimization problem: @@ -129,6 +100,26 @@ class GeneralizedLinearRegressor(RegressorMixin, BaseEstimator): n_iter_ : int Actual number of iterations used in the solver. + + _base_loss : BaseLoss, default=HalfSquaredError() + This is set during fit via `self._get_loss()`. + A `_base_loss` contains a specific loss function as well as the link + function. The loss to be minimized specifies the distributional assumption of + the GLM, i.e. the distribution from the EDM. Here are some examples: + + ======================= ======== ========================== + _base_loss Link Target Domain + ======================= ======== ========================== + HalfSquaredError identity y any real number + HalfPoissonLoss log 0 <= y + HalfGammaLoss log 0 < y + HalfTweedieLoss log dependend on tweedie power + HalfTweedieLossIdentity identity dependend on tweedie power + ======================= ======== ========================== + + The link function of the GLM, i.e. mapping from linear predictor + `X @ coeff + intercept` to prediction `y_pred`. For instance, with a log link, + we have `y_pred = exp(X @ coeff + intercept)`. """ def __init__( @@ -136,8 +127,6 @@ def __init__( *, alpha=1.0, fit_intercept=True, - family="normal", - link="auto", solver="lbfgs", max_iter=100, tol=1e-4, @@ -146,8 +135,6 @@ def __init__( ): self.alpha = alpha self.fit_intercept = fit_intercept - self.family = family - self.link = link self.solver = solver self.max_iter = max_iter self.tol = tol @@ -173,47 +160,6 @@ def fit(self, X, y, sample_weight=None): self : object Fitted model. """ - if isinstance(self.family, ExponentialDispersionModel): - self._family_instance = self.family - elif self.family in EDM_DISTRIBUTIONS: - self._family_instance = EDM_DISTRIBUTIONS[self.family]() - else: - raise ValueError( - "The family must be an instance of class" - " ExponentialDispersionModel or an element of" - " ['normal', 'poisson', 'gamma', 'inverse-gaussian']" - "; got (family={0})".format(self.family) - ) - - # Guarantee that self._link_instance is set to an instance of - # class BaseLink - if isinstance(self.link, BaseLink): - self._link_instance = self.link - else: - if self.link == "auto": - if isinstance(self._family_instance, TweedieDistribution): - if self._family_instance.power <= 0: - self._link_instance = IdentityLink() - if self._family_instance.power >= 1: - self._link_instance = LogLink() - else: - raise ValueError( - "No default link known for the " - "specified distribution family. Please " - "set link manually, i.e. not to 'auto'; " - "got (link='auto', family={})".format(self.family) - ) - elif self.link == "identity": - self._link_instance = IdentityLink() - elif self.link == "log": - self._link_instance = LogLink() - else: - raise ValueError( - "The link must be an instance of class Link or " - "an element of ['auto', 'identity', 'log']; " - "got (link={0})".format(self.link) - ) - check_scalar( self.alpha, name="alpha", @@ -229,8 +175,8 @@ def fit(self, X, y, sample_weight=None): ) if self.solver not in ["lbfgs"]: raise ValueError( - "GeneralizedLinearRegressor supports only solvers" - "'lbfgs'; got {0}".format(self.solver) + f"{self.__class__.__name__} supports only solvers 'lbfgs'; " + f"got {self.solver}" ) solver = self.solver check_scalar( @@ -257,9 +203,6 @@ def fit(self, X, y, sample_weight=None): "The argument warm_start must be bool; got {0}".format(self.warm_start) ) - family = self._family_instance - link = self._link_instance - X, y = self._validate_data( X, y, @@ -269,57 +212,71 @@ def fit(self, X, y, sample_weight=None): multi_output=False, ) - weights = _check_sample_weight(sample_weight, X) + # required by losses + if solver == "lbfgs": + # lbfgs will force coef and therefore raw_prediction to be float64. The + # base_loss needs y, X @ coef and sample_weight all of same dtype + # (and contiguous). + loss_dtype = np.float64 + else: + loss_dtype = min(max(y.dtype, X.dtype), np.float64) + y = check_array(y, dtype=loss_dtype, order="C", ensure_2d=False) + + # TODO: We could support samples_weight=None as the losses support it. + # Note that _check_sample_weight calls check_array(order="C") required by + # losses. + sample_weight = _check_sample_weight(sample_weight, X, dtype=loss_dtype) + + n_samples, n_features = X.shape + self._base_loss = self._get_loss() - _, n_features = X.shape + self._linear_loss = LinearModelLoss( + base_loss=self._base_loss, + fit_intercept=self.fit_intercept, + ) - if not np.all(family.in_y_range(y)): + if not self._linear_loss.base_loss.in_y_true_range(y): raise ValueError( - "Some value(s) of y are out of the valid range for family {0}".format( - family.__class__.__name__ - ) + "Some value(s) of y are out of the valid range of the loss" + f" {self._base_loss.__class__.__name__!r}." ) + # TODO: if alpha=0 check that X is not rank deficient - # rescaling of sample_weight - # - # IMPORTANT NOTE: Since we want to minimize - # 1/(2*sum(sample_weight)) * deviance + L2, - # deviance = sum(sample_weight * unit_deviance), - # we rescale weights such that sum(weights) = 1 and this becomes - # 1/2*deviance + L2 with deviance=sum(weights * unit_deviance) - weights = weights / weights.sum() + # IMPORTANT NOTE: Rescaling of sample_weight: + # We want to minimize + # obj = 1/(2*sum(sample_weight)) * sum(sample_weight * deviance) + # + 1/2 * alpha * L2, + # with + # deviance = 2 * loss. + # The objective is invariant to multiplying sample_weight by a constant. We + # choose this constant such that sum(sample_weight) = 1. Thus, we end up with + # obj = sum(sample_weight * loss) + 1/2 * alpha * L2. + # Note that LinearModelLoss.loss() computes sum(sample_weight * loss). + sample_weight = sample_weight / sample_weight.sum() if self.warm_start and hasattr(self, "coef_"): if self.fit_intercept: - coef = np.concatenate((np.array([self.intercept_]), self.coef_)) + # LinearModelLoss needs intercept at the end of coefficient array. + coef = np.concatenate((self.coef_, np.array([self.intercept_]))) else: coef = self.coef_ + coef = coef.astype(loss_dtype, copy=False) else: if self.fit_intercept: - coef = np.zeros(n_features + 1) - coef[0] = link(np.average(y, weights=weights)) + coef = np.zeros(n_features + 1, dtype=loss_dtype) + coef[-1] = self._linear_loss.base_loss.link.link( + np.average(y, weights=sample_weight) + ) else: - coef = np.zeros(n_features) - - # algorithms for optimization + coef = np.zeros(n_features, dtype=loss_dtype) + # Algorithms for optimization: + # Note again that our losses implement 1/2 * deviance. if solver == "lbfgs": - - def func(coef, X, y, weights, alpha, family, link): - y_pred, devp = _y_pred_deviance_derivative( - coef, X, y, weights, family, link - ) - dev = family.deviance(y, y_pred, weights) - # offset if coef[0] is intercept - offset = 1 if self.fit_intercept else 0 - coef_scaled = alpha * coef[offset:] - obj = 0.5 * dev + 0.5 * (coef[offset:] @ coef_scaled) - objp = 0.5 * devp - objp[offset:] += coef_scaled - return obj, objp - - args = (X, y, weights, self.alpha, family, link) + func = self._linear_loss.loss_gradient + l2_reg_strength = self.alpha + n_threads = _openmp_effective_n_threads() opt_res = scipy.optimize.minimize( func, @@ -332,14 +289,14 @@ def func(coef, X, y, weights, alpha, family, link): "gtol": self.tol, "ftol": 1e3 * np.finfo(float).eps, }, - args=args, + args=(X, y, sample_weight, l2_reg_strength, n_threads), ) self.n_iter_ = _check_optimize_result("lbfgs", opt_res) coef = opt_res.x if self.fit_intercept: - self.intercept_ = coef[0] - self.coef_ = coef[1:] + self.intercept_ = coef[-1] + self.coef_ = coef[:-1] else: # set intercept to zero as the other linear models do self.intercept_ = 0.0 @@ -350,6 +307,8 @@ def func(coef, X, y, weights, alpha, family, link): def _linear_predictor(self, X): """Compute the linear_predictor = `X @ coef_ + intercept_`. + Note that we often use the term raw_prediction instead of linear predictor. + Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) @@ -385,16 +344,16 @@ def predict(self, X): Returns predicted values. """ # check_array is done in _linear_predictor - eta = self._linear_predictor(X) - y_pred = self._link_instance.inverse(eta) + raw_prediction = self._linear_predictor(X) + y_pred = self._linear_loss.base_loss.link.inverse(raw_prediction) return y_pred def score(self, X, y, sample_weight=None): """Compute D^2, the percentage of deviance explained. D^2 is a generalization of the coefficient of determination R^2. - R^2 uses squared error and D^2 deviance. Note that those two are equal - for ``family='normal'``. + R^2 uses squared error and D^2 uses the deviance of this GLM, see the + :ref:`User Guide <regression_metrics>`. D^2 is defined as :math:`D^2 = 1-\\frac{D(y_{true},y_{pred})}{D_{null}}`, @@ -420,30 +379,88 @@ def score(self, X, y, sample_weight=None): score : float D^2 of self.predict(X) w.r.t. y. """ + # TODO: Adapt link to User Guide in the docstring, once + # https://github.com/scikit-learn/scikit-learn/pull/22118 is merged. + # # Note, default score defined in RegressorMixin is R^2 score. # TODO: make D^2 a score function in module metrics (and thereby get # input validation and so on) - weights = _check_sample_weight(sample_weight, X) - y_pred = self.predict(X) - dev = self._family_instance.deviance(y, y_pred, weights=weights) - y_mean = np.average(y, weights=weights) - dev_null = self._family_instance.deviance(y, y_mean, weights=weights) - return 1 - dev / dev_null + raw_prediction = self._linear_predictor(X) # validates X + # required by losses + y = check_array(y, dtype=raw_prediction.dtype, order="C", ensure_2d=False) + + if sample_weight is not None: + # Note that _check_sample_weight calls check_array(order="C") required by + # losses. + sample_weight = _check_sample_weight(sample_weight, X, dtype=y.dtype) + + base_loss = self._linear_loss.base_loss + + if not base_loss.in_y_true_range(y): + raise ValueError( + "Some value(s) of y are out of the valid range of the loss" + f" {self._base_loss.__name__}." + ) + + # Note that constant_to_optimal_zero is already multiplied by sample_weight. + constant = np.mean(base_loss.constant_to_optimal_zero(y_true=y)) + if sample_weight is not None: + constant *= sample_weight.shape[0] / np.sum(sample_weight) + + # Missing factor of 2 in deviance cancels out. + deviance = base_loss( + y_true=y, + raw_prediction=raw_prediction, + sample_weight=sample_weight, + n_threads=1, + ) + y_mean = base_loss.link.link(np.average(y, weights=sample_weight)) + deviance_null = base_loss( + y_true=y, + raw_prediction=np.tile(y_mean, y.shape[0]), + sample_weight=sample_weight, + n_threads=1, + ) + return 1 - (deviance + constant) / (deviance_null + constant) def _more_tags(self): - # create the _family_instance if fit wasn't called yet. - if hasattr(self, "_family_instance"): - _family_instance = self._family_instance - elif isinstance(self.family, ExponentialDispersionModel): - _family_instance = self.family - elif self.family in EDM_DISTRIBUTIONS: - _family_instance = EDM_DISTRIBUTIONS[self.family]() + # Create instance of BaseLoss if fit wasn't called yet. This is necessary as + # TweedieRegressor might set the used loss during fit different from + # self._base_loss. + base_loss = self._get_loss() + return {"requires_positive_y": not base_loss.in_y_true_range(-1.0)} + + def _get_loss(self): + """This is only necessary because of the link and power arguments of the + TweedieRegressor. + + Note that we do not need to pass sample_weight to the loss class as this is + only needed to set loss.constant_hessian on which GLMs do not rely. + """ + return HalfSquaredError() + + # TODO(1.3): remove + @deprecated( # type: ignore + "Attribute `family` was deprecated in version 1.1 and will be removed in 1.3." + ) + @property + def family(self): + """Ensure backward compatibility for the time of deprecation.""" + if isinstance(self, PoissonRegressor): + return "poisson" + elif isinstance(self, GammaRegressor): + return "gamma" + elif isinstance(self, TweedieRegressor): + return TweedieDistribution(power=self.power) else: - raise ValueError - return {"requires_positive_y": not _family_instance.in_y_range(-1.0)} + raise ValueError( # noqa + "This should never happen. You presumably accessed the deprecated " + "`family` attribute from a subclass of the private scikit-learn class " + "_GeneralizedLinearRegressor." + ) -class PoissonRegressor(GeneralizedLinearRegressor): +class PoissonRegressor(_GeneralizedLinearRegressor): """Generalized Linear Model with a Poisson distribution. This regressor uses the 'log' link function. @@ -509,8 +526,7 @@ class PoissonRegressor(GeneralizedLinearRegressor): See Also -------- - GeneralizedLinearRegressor : Generalized Linear Model with a Poisson - distribution. + TweedieRegressor : Generalized Linear Model with a Tweedie distribution. Examples -------- @@ -540,31 +556,20 @@ def __init__( warm_start=False, verbose=0, ): - super().__init__( alpha=alpha, fit_intercept=fit_intercept, - family="poisson", - link="log", max_iter=max_iter, tol=tol, warm_start=warm_start, verbose=verbose, ) - @property - def family(self): - """Return the string `'poisson'`.""" - # Make this attribute read-only to avoid mis-uses e.g. in GridSearch. - return "poisson" - - @family.setter - def family(self, value): - if value != "poisson": - raise ValueError("PoissonRegressor.family must be 'poisson'!") + def _get_loss(self): + return HalfPoissonLoss() -class GammaRegressor(GeneralizedLinearRegressor): +class GammaRegressor(_GeneralizedLinearRegressor): """Generalized Linear Model with a Gamma distribution. This regressor uses the 'log' link function. @@ -661,31 +666,20 @@ def __init__( warm_start=False, verbose=0, ): - super().__init__( alpha=alpha, fit_intercept=fit_intercept, - family="gamma", - link="log", max_iter=max_iter, tol=tol, warm_start=warm_start, verbose=verbose, ) - @property - def family(self): - """Return the family of the regressor.""" - # Make this attribute read-only to avoid mis-uses e.g. in GridSearch. - return "gamma" - - @family.setter - def family(self, value): - if value != "gamma": - raise ValueError("GammaRegressor.family must be 'gamma'!") + def _get_loss(self): + return HalfGammaLoss() -class TweedieRegressor(GeneralizedLinearRegressor): +class TweedieRegressor(_GeneralizedLinearRegressor): """Generalized Linear Model with a Tweedie distribution. This estimator can be used to model different GLMs depending on the @@ -731,10 +725,11 @@ class TweedieRegressor(GeneralizedLinearRegressor): link : {'auto', 'identity', 'log'}, default='auto' The link function of the GLM, i.e. mapping from linear predictor `X @ coeff + intercept` to prediction `y_pred`. Option 'auto' sets - the link depending on the chosen family as follows: + the link depending on the chosen `power` parameter as follows: - - 'identity' for Normal distribution - - 'log' for Poisson, Gamma and Inverse Gaussian distributions + - 'identity' for ``power <= 0``, e.g. for the Normal distribution + - 'log' for ``power > 0``, e.g. for Poisson, Gamma and Inverse Gaussian + distributions max_iter : int, default=100 The maximal number of iterations for the solver. @@ -813,33 +808,31 @@ def __init__( warm_start=False, verbose=0, ): - super().__init__( alpha=alpha, fit_intercept=fit_intercept, - family=TweedieDistribution(power=power), - link=link, max_iter=max_iter, tol=tol, warm_start=warm_start, verbose=verbose, ) + self.link = link + self.power = power - @property - def family(self): - """Return the family of the regressor.""" - # We use a property with a setter to make sure that the family is - # always a Tweedie distribution, and that self.power and - # self.family.power are identical by construction. - dist = TweedieDistribution(power=self.power) - # TODO: make the returned object immutable - return dist - - @family.setter - def family(self, value): - if isinstance(value, TweedieDistribution): - self.power = value.power + def _get_loss(self): + if self.link == "auto": + if self.power <= 0: + # identity link + return HalfTweedieLossIdentity(power=self.power) + else: + # log link + return HalfTweedieLoss(power=self.power) + elif self.link == "log": + return HalfTweedieLoss(power=self.power) + elif self.link == "identity": + return HalfTweedieLossIdentity(power=self.power) else: - raise TypeError( - "TweedieRegressor.family must be of type TweedieDistribution!" + raise ValueError( + "The link must be an element of ['auto', 'identity', 'log']; " + f"got (link={self.link!r})" ) diff --git a/sklearn/linear_model/_glm/link.py b/sklearn/linear_model/_glm/link.py deleted file mode 100644 index 878d8e835bc42..0000000000000 --- a/sklearn/linear_model/_glm/link.py +++ /dev/null @@ -1,110 +0,0 @@ -""" -Link functions used in GLM -""" - -# Author: Christian Lorentzen <[email protected]> -# License: BSD 3 clause - -from abc import ABCMeta, abstractmethod - -import numpy as np -from scipy.special import expit, logit - - -class BaseLink(metaclass=ABCMeta): - """Abstract base class for Link functions.""" - - @abstractmethod - def __call__(self, y_pred): - """Compute the link function g(y_pred). - - The link function links the mean y_pred=E[Y] to the so called linear - predictor (X*w), i.e. g(y_pred) = linear predictor. - - Parameters - ---------- - y_pred : array of shape (n_samples,) - Usually the (predicted) mean. - """ - - @abstractmethod - def derivative(self, y_pred): - """Compute the derivative of the link g'(y_pred). - - Parameters - ---------- - y_pred : array of shape (n_samples,) - Usually the (predicted) mean. - """ - - @abstractmethod - def inverse(self, lin_pred): - """Compute the inverse link function h(lin_pred). - - Gives the inverse relationship between linear predictor and the mean - y_pred=E[Y], i.e. h(linear predictor) = y_pred. - - Parameters - ---------- - lin_pred : array of shape (n_samples,) - Usually the (fitted) linear predictor. - """ - - @abstractmethod - def inverse_derivative(self, lin_pred): - """Compute the derivative of the inverse link function h'(lin_pred). - - Parameters - ---------- - lin_pred : array of shape (n_samples,) - Usually the (fitted) linear predictor. - """ - - -class IdentityLink(BaseLink): - """The identity link function g(x)=x.""" - - def __call__(self, y_pred): - return y_pred - - def derivative(self, y_pred): - return np.ones_like(y_pred) - - def inverse(self, lin_pred): - return lin_pred - - def inverse_derivative(self, lin_pred): - return np.ones_like(lin_pred) - - -class LogLink(BaseLink): - """The log link function g(x)=log(x).""" - - def __call__(self, y_pred): - return np.log(y_pred) - - def derivative(self, y_pred): - return 1 / y_pred - - def inverse(self, lin_pred): - return np.exp(lin_pred) - - def inverse_derivative(self, lin_pred): - return np.exp(lin_pred) - - -class LogitLink(BaseLink): - """The logit link function g(x)=logit(x).""" - - def __call__(self, y_pred): - return logit(y_pred) - - def derivative(self, y_pred): - return 1 / (y_pred * (1 - y_pred)) - - def inverse(self, lin_pred): - return expit(lin_pred) - - def inverse_derivative(self, lin_pred): - ep = expit(lin_pred) - return ep * (1 - ep) diff --git a/sklearn/linear_model/_linear_loss.py b/sklearn/linear_model/_linear_loss.py index 93a7684aea5b6..64a99325dcd7a 100644 --- a/sklearn/linear_model/_linear_loss.py +++ b/sklearn/linear_model/_linear_loss.py @@ -9,6 +9,8 @@ class LinearModelLoss: """General class for loss functions with raw_prediction = X @ coef + intercept. + Note that raw_prediction is also known as linear predictor. + The loss is the sum of per sample losses and includes a term for L2 regularization:: @@ -194,13 +196,13 @@ def loss_gradient( if not self.base_loss.is_multiclass: loss += 0.5 * l2_reg_strength * (weights @ weights) - grad = np.empty_like(coef, dtype=X.dtype) + grad = np.empty_like(coef, dtype=weights.dtype) grad[:n_features] = X.T @ grad_per_sample + l2_reg_strength * weights if self.fit_intercept: grad[-1] = grad_per_sample.sum() else: loss += 0.5 * l2_reg_strength * squared_norm(weights) - grad = np.empty((n_classes, n_dof), dtype=X.dtype, order="F") + grad = np.empty((n_classes, n_dof), dtype=weights.dtype, order="F") # grad_per_sample.shape = (n_samples, n_classes) grad[:, :n_features] = grad_per_sample.T @ X + l2_reg_strength * weights if self.fit_intercept: @@ -250,13 +252,13 @@ def gradient( ) if not self.base_loss.is_multiclass: - grad = np.empty_like(coef, dtype=X.dtype) + grad = np.empty_like(coef, dtype=weights.dtype) grad[:n_features] = X.T @ grad_per_sample + l2_reg_strength * weights if self.fit_intercept: grad[-1] = grad_per_sample.sum() return grad else: - grad = np.empty((n_classes, n_dof), dtype=X.dtype, order="F") + grad = np.empty((n_classes, n_dof), dtype=weights.dtype, order="F") # gradient.shape = (n_samples, n_classes) grad[:, :n_features] = grad_per_sample.T @ X + l2_reg_strength * weights if self.fit_intercept: @@ -309,7 +311,7 @@ def gradient_hessian_product( sample_weight=sample_weight, n_threads=n_threads, ) - grad = np.empty_like(coef, dtype=X.dtype) + grad = np.empty_like(coef, dtype=weights.dtype) grad[:n_features] = X.T @ gradient + l2_reg_strength * weights if self.fit_intercept: grad[-1] = gradient.sum() @@ -356,7 +358,7 @@ def hessp(s): sample_weight=sample_weight, n_threads=n_threads, ) - grad = np.empty((n_classes, n_dof), dtype=X.dtype, order="F") + grad = np.empty((n_classes, n_dof), dtype=weights.dtype, order="F") grad[:, :n_features] = gradient.T @ X + l2_reg_strength * weights if self.fit_intercept: grad[:, -1] = gradient.sum(axis=0) @@ -396,7 +398,7 @@ def hessp(s): tmp *= sample_weight[:, np.newaxis] # hess_prod = empty_like(grad), but we ravel grad below and this # function is run after that. - hess_prod = np.empty((n_classes, n_dof), dtype=X.dtype, order="F") + hess_prod = np.empty((n_classes, n_dof), dtype=weights.dtype, order="F") hess_prod[:, :n_features] = tmp.T @ X + l2_reg_strength * s if self.fit_intercept: hess_prod[:, -1] = tmp.sum(axis=0) diff --git a/sklearn/metrics/_regression.py b/sklearn/metrics/_regression.py index c701320f9c23a..270d6a2c19cfe 100644 --- a/sklearn/metrics/_regression.py +++ b/sklearn/metrics/_regression.py @@ -19,21 +19,23 @@ # Manoj Kumar <[email protected]> # Michael Eickenberg <[email protected]> # Konstantin Shmelkov <[email protected]> -# Christian Lorentzen <[email protected]> +# Christian Lorentzen <[email protected]> # Ashutosh Hathidara <[email protected]> # Uttam kumar <[email protected]> # Sylvain Marie <[email protected]> # License: BSD 3 clause +import numbers import warnings import numpy as np +from scipy.special import xlogy -from .._loss.glm_distribution import TweedieDistribution from ..exceptions import UndefinedMetricWarning from ..utils.validation import ( check_array, check_consistent_length, + check_scalar, _num_samples, column_or_1d, _check_sample_weight, @@ -965,6 +967,35 @@ def max_error(y_true, y_pred): return np.max(np.abs(y_true - y_pred)) +def _mean_tweedie_deviance(y_true, y_pred, sample_weight, power): + """Mean Tweedie deviance regression loss.""" + p = power + if p < 0: + # 'Extreme stable', y any real number, y_pred > 0 + dev = 2 * ( + np.power(np.maximum(y_true, 0), 2 - p) / ((1 - p) * (2 - p)) + - y_true * np.power(y_pred, 1 - p) / (1 - p) + + np.power(y_pred, 2 - p) / (2 - p) + ) + elif p == 0: + # Normal distribution, y and y_pred any real number + dev = (y_true - y_pred) ** 2 + elif p == 1: + # Poisson distribution + dev = 2 * (xlogy(y_true, y_true / y_pred) - y_true + y_pred) + elif p == 2: + # Gamma distribution + dev = 2 * (np.log(y_pred / y_true) + y_true / y_pred - 1) + else: + dev = 2 * ( + np.power(y_true, 2 - p) / ((1 - p) * (2 - p)) + - y_true * np.power(y_pred, 1 - p) / (1 - p) + + np.power(y_pred, 2 - p) / (2 - p) + ) + + return np.average(dev, weights=sample_weight) + + def mean_tweedie_deviance(y_true, y_pred, *, sample_weight=None, power=0): """Mean Tweedie deviance regression loss. @@ -1024,10 +1055,37 @@ def mean_tweedie_deviance(y_true, y_pred, *, sample_weight=None, power=0): sample_weight = column_or_1d(sample_weight) sample_weight = sample_weight[:, np.newaxis] - dist = TweedieDistribution(power=power) - dev = dist.unit_deviance(y_true, y_pred, check_input=True) + p = check_scalar( + power, + name="power", + target_type=numbers.Real, + ) - return np.average(dev, weights=sample_weight) + message = f"Mean Tweedie deviance error with power={p} can only be used on " + if p < 0: + # 'Extreme stable', y any real number, y_pred > 0 + if (y_pred <= 0).any(): + raise ValueError(message + "strictly positive y_pred.") + elif p == 0: + # Normal, y and y_pred can be any real number + pass + elif 0 < p < 1: + raise ValueError("Tweedie deviance is only defined for power<=0 and power>=1.") + elif 1 <= p < 2: + # Poisson and compound Poisson distribution, y >= 0, y_pred > 0 + if (y_true < 0).any() or (y_pred <= 0).any(): + raise ValueError(message + "non-negative y and strictly positive y_pred.") + elif p >= 2: + # Gamma and Extreme stable distribution, y and y_pred > 0 + if (y_true <= 0).any() or (y_pred <= 0).any(): + raise ValueError(message + "strictly positive y and y_pred.") + else: # pragma: nocover + # Unreachable statement + raise ValueError + + return _mean_tweedie_deviance( + y_true, y_pred, sample_weight=sample_weight, power=power + ) def mean_poisson_deviance(y_true, y_pred, *, sample_weight=None): @@ -1182,24 +1240,20 @@ def d2_tweedie_score(y_true, y_pred, *, sample_weight=None, power=0): ) if y_type == "continuous-multioutput": raise ValueError("Multioutput not supported in d2_tweedie_score") - check_consistent_length(y_true, y_pred, sample_weight) if _num_samples(y_pred) < 2: msg = "D^2 score is not well-defined with less than two samples." warnings.warn(msg, UndefinedMetricWarning) return float("nan") - if sample_weight is not None: - sample_weight = column_or_1d(sample_weight) - sample_weight = sample_weight[:, np.newaxis] - - dist = TweedieDistribution(power=power) - - dev = dist.unit_deviance(y_true, y_pred, check_input=True) - numerator = np.average(dev, weights=sample_weight) + y_true, y_pred = np.squeeze(y_true), np.squeeze(y_pred) + numerator = mean_tweedie_deviance( + y_true, y_pred, sample_weight=sample_weight, power=power + ) y_avg = np.average(y_true, weights=sample_weight) - dev = dist.unit_deviance(y_true, y_avg, check_input=True) - denominator = np.average(dev, weights=sample_weight) + denominator = _mean_tweedie_deviance( + y_true, y_avg, sample_weight=sample_weight, power=power + ) return 1 - numerator / denominator
diff --git a/sklearn/_loss/tests/test_glm_distribution.py b/sklearn/_loss/tests/test_glm_distribution.py index 453f61e2f3214..aaaa9de39a502 100644 --- a/sklearn/_loss/tests/test_glm_distribution.py +++ b/sklearn/_loss/tests/test_glm_distribution.py @@ -1,6 +1,8 @@ # Authors: Christian Lorentzen <[email protected]> # # License: BSD 3 clause +# +# TODO(1.3): remove file import numpy as np from numpy.testing import ( assert_allclose, diff --git a/sklearn/_loss/tests/test_link.py b/sklearn/_loss/tests/test_link.py index b363a45109989..435361eaa50f1 100644 --- a/sklearn/_loss/tests/test_link.py +++ b/sklearn/_loss/tests/test_link.py @@ -16,7 +16,7 @@ def test_interval_raises(): """Test that interval with low > high raises ValueError.""" with pytest.raises( - ValueError, match="On must have low <= high; got low=1, high=0." + ValueError, match="One must have low <= high; got low=1, high=0." ): Interval(1, 0, False, False) diff --git a/sklearn/_loss/tests/test_loss.py b/sklearn/_loss/tests/test_loss.py index a830592d7796c..8aeb350440005 100644 --- a/sklearn/_loss/tests/test_loss.py +++ b/sklearn/_loss/tests/test_loss.py @@ -23,6 +23,7 @@ HalfPoissonLoss, HalfSquaredError, HalfTweedieLoss, + HalfTweedieLossIdentity, PinballLoss, ) from sklearn.utils import assert_all_finite @@ -40,6 +41,10 @@ HalfTweedieLoss(power=1), HalfTweedieLoss(power=2), HalfTweedieLoss(power=3.0), + HalfTweedieLossIdentity(power=0), + HalfTweedieLossIdentity(power=1), + HalfTweedieLossIdentity(power=2), + HalfTweedieLossIdentity(power=3.0), ] @@ -70,8 +75,14 @@ def random_y_true_raw_prediction( ) y_true = np.arange(n_samples).astype(float) % loss.n_classes else: + # If link is identity, we must respect the interval of y_pred: + if isinstance(loss.link, IdentityLink): + low, high = _inclusive_low_high(loss.interval_y_pred) + low = np.amax([low, raw_bound[0]]) + high = np.amin([high, raw_bound[1]]) + raw_bound = (low, high) raw_prediction = rng.uniform( - low=raw_bound[0], high=raw_bound[0], size=n_samples + low=raw_bound[0], high=raw_bound[1], size=n_samples ) # generate a y_true in valid range low, high = _inclusive_low_high(loss.interval_y_true) @@ -149,6 +160,11 @@ def test_loss_boundary(loss): (HalfTweedieLoss(power=1.5), [0.1, 100], [-np.inf, -3, -0.1, np.inf]), (HalfTweedieLoss(power=2), [0.1, 100], [-np.inf, -3, -0.1, 0, np.inf]), (HalfTweedieLoss(power=3), [0.1, 100], [-np.inf, -3, -0.1, 0, np.inf]), + (HalfTweedieLossIdentity(power=-3), [0.1, 100], [-np.inf, np.inf]), + (HalfTweedieLossIdentity(power=0), [-3, -0.1, 0, 0.1, 100], [-np.inf, np.inf]), + (HalfTweedieLossIdentity(power=1.5), [0.1, 100], [-np.inf, -3, -0.1, np.inf]), + (HalfTweedieLossIdentity(power=2), [0.1, 100], [-np.inf, -3, -0.1, 0, np.inf]), + (HalfTweedieLossIdentity(power=3), [0.1, 100], [-np.inf, -3, -0.1, 0, np.inf]), (HalfBinomialLoss(), [0.1, 0.5, 0.9], [-np.inf, -1, 2, np.inf]), (HalfMultinomialLoss(), [], [-np.inf, -1, 1.1, np.inf]), ] @@ -160,6 +176,9 @@ def test_loss_boundary(loss): (HalfTweedieLoss(power=-3), [-100, -0.1, 0], []), (HalfTweedieLoss(power=0), [-100, 0], []), (HalfTweedieLoss(power=1.5), [0], []), + (HalfTweedieLossIdentity(power=-3), [-100, -0.1, 0], []), + (HalfTweedieLossIdentity(power=0), [-100, 0], []), + (HalfTweedieLossIdentity(power=1.5), [0], []), (HalfBinomialLoss(), [0, 1], []), (HalfMultinomialLoss(), [0.0, 1.0, 2], []), ] @@ -169,6 +188,9 @@ def test_loss_boundary(loss): (HalfTweedieLoss(power=-3), [], [-3, -0.1, 0]), (HalfTweedieLoss(power=0), [], [-3, -0.1, 0]), (HalfTweedieLoss(power=1.5), [], [0]), + (HalfTweedieLossIdentity(power=-3), [], [-3, -0.1, 0]), + (HalfTweedieLossIdentity(power=0), [-3, -0.1, 0], []), + (HalfTweedieLossIdentity(power=1.5), [], [0]), (HalfBinomialLoss(), [], [0, 1]), (HalfMultinomialLoss(), [0.1, 0.5], [0, 1]), ] @@ -207,6 +229,9 @@ def test_loss_boundary_y_pred(loss, y_pred_success, y_pred_fail): (HalfPoissonLoss(), 2.0, np.log(4), 4 - 2 * np.log(4)), (HalfGammaLoss(), 2.0, np.log(4), np.log(4) + 2 / 4), (HalfTweedieLoss(power=3), 2.0, np.log(4), -1 / 4 + 1 / 4**2), + (HalfTweedieLossIdentity(power=1), 2.0, 4.0, 2 - 2 * np.log(2)), + (HalfTweedieLossIdentity(power=2), 2.0, 4.0, np.log(2) - 1 / 2), + (HalfTweedieLossIdentity(power=3), 2.0, 4.0, -1 / 4 + 1 / 4**2 + 1 / 2 / 2), (HalfBinomialLoss(), 0.25, np.log(4), np.log(5) - 0.25 * np.log(4)), ( HalfMultinomialLoss(n_classes=3), @@ -604,6 +629,16 @@ def test_loss_of_perfect_prediction(loss, sample_weight): if not loss.is_multiclass: # Use small values such that exp(value) is not nan. raw_prediction = np.array([-10, -0.1, 0, 0.1, 3, 10]) + # If link is identity, we must respect the interval of y_pred: + if isinstance(loss.link, IdentityLink): + eps = 1e-10 + low = loss.interval_y_pred.low + if not loss.interval_y_pred.low_inclusive: + low = low + eps + high = loss.interval_y_pred.high + if not loss.interval_y_pred.high_inclusive: + high = high - eps + raw_prediction = np.clip(raw_prediction, low, high) y_true = loss.link.inverse(raw_prediction) else: # HalfMultinomialLoss @@ -1091,3 +1126,48 @@ def test_loss_pickle(loss): assert loss(y_true=y_true, raw_prediction=raw_prediction) == approx( unpickled_loss(y_true=y_true, raw_prediction=raw_prediction) ) + + [email protected]("p", [-1.5, 0, 1, 1.5, 2, 3]) +def test_tweedie_log_identity_consistency(p): + """Test for identical losses when only the link function is different.""" + half_tweedie_log = HalfTweedieLoss(power=p) + half_tweedie_identity = HalfTweedieLossIdentity(power=p) + n_samples = 10 + y_true, raw_prediction = random_y_true_raw_prediction( + loss=half_tweedie_log, n_samples=n_samples, seed=42 + ) + y_pred = half_tweedie_log.link.inverse(raw_prediction) # exp(raw_prediction) + + # Let's compare the loss values, up to some constant term that is dropped + # in HalfTweedieLoss but not in HalfTweedieLossIdentity. + loss_log = half_tweedie_log.loss( + y_true=y_true, raw_prediction=raw_prediction + ) + half_tweedie_log.constant_to_optimal_zero(y_true) + loss_identity = half_tweedie_identity.loss( + y_true=y_true, raw_prediction=y_pred + ) + half_tweedie_identity.constant_to_optimal_zero(y_true) + # Note that HalfTweedieLoss ignores different constant terms than + # HalfTweedieLossIdentity. Constant terms means terms not depending on + # raw_prediction. By adding these terms, `constant_to_optimal_zero`, both losses + # give the same values. + assert_allclose(loss_log, loss_identity) + + # For gradients and hessians, the constant terms do not matter. We have, however, + # to account for the chain rule, i.e. with x=raw_prediction + # gradient_log(x) = d/dx loss_log(x) + # = d/dx loss_identity(exp(x)) + # = exp(x) * gradient_identity(exp(x)) + # Similarly, + # hessian_log(x) = exp(x) * gradient_identity(exp(x)) + # + exp(x)**2 * hessian_identity(x) + gradient_log, hessian_log = half_tweedie_log.gradient_hessian( + y_true=y_true, raw_prediction=raw_prediction + ) + gradient_identity, hessian_identity = half_tweedie_identity.gradient_hessian( + y_true=y_true, raw_prediction=y_pred + ) + assert_allclose(gradient_log, y_pred * gradient_identity) + assert_allclose( + hessian_log, y_pred * gradient_identity + y_pred**2 * hessian_identity + ) diff --git a/sklearn/linear_model/_glm/tests/test_glm.py b/sklearn/linear_model/_glm/tests/test_glm.py index 87fe2b51f4d28..9bfa2fe28e91a 100644 --- a/sklearn/linear_model/_glm/tests/test_glm.py +++ b/sklearn/linear_model/_glm/tests/test_glm.py @@ -2,27 +2,22 @@ # # License: BSD 3 clause +import re import numpy as np from numpy.testing import assert_allclose import pytest import warnings +from sklearn.base import clone +from sklearn._loss.glm_distribution import TweedieDistribution +from sklearn._loss.link import IdentityLink, LogLink + from sklearn.datasets import make_regression -from sklearn.linear_model._glm import GeneralizedLinearRegressor +from sklearn.linear_model._glm import _GeneralizedLinearRegressor from sklearn.linear_model import TweedieRegressor, PoissonRegressor, GammaRegressor -from sklearn.linear_model._glm.link import ( - IdentityLink, - LogLink, -) -from sklearn._loss.glm_distribution import ( - TweedieDistribution, - NormalDistribution, - PoissonDistribution, - GammaDistribution, - InverseGaussianDistribution, -) from sklearn.linear_model import Ridge from sklearn.exceptions import ConvergenceWarning +from sklearn.metrics import d2_tweedie_score from sklearn.model_selection import train_test_split @@ -40,7 +35,7 @@ def test_sample_weights_validation(): X = [[1]] y = [1] weights = 0 - glm = GeneralizedLinearRegressor() + glm = _GeneralizedLinearRegressor() # Positive weights are accepted glm.fit(X, y, sample_weight=1) @@ -57,65 +52,12 @@ def test_sample_weights_validation(): glm.fit(X, y, weights) [email protected]( - "name, instance", - [ - ("normal", NormalDistribution()), - ("poisson", PoissonDistribution()), - ("gamma", GammaDistribution()), - ("inverse-gaussian", InverseGaussianDistribution()), - ], -) -def test_glm_family_argument(name, instance): - """Test GLM family argument set as string.""" - y = np.array([0.1, 0.5]) # in range of all distributions - X = np.array([[1], [2]]) - glm = GeneralizedLinearRegressor(family=name, alpha=0).fit(X, y) - assert isinstance(glm._family_instance, instance.__class__) - - glm = GeneralizedLinearRegressor(family="not a family") - with pytest.raises(ValueError, match="family must be"): - glm.fit(X, y) - - [email protected]( - "name, instance", [("identity", IdentityLink()), ("log", LogLink())] -) -def test_glm_link_argument(name, instance): - """Test GLM link argument set as string.""" - y = np.array([0.1, 0.5]) # in range of all distributions - X = np.array([[1], [2]]) - glm = GeneralizedLinearRegressor(family="normal", link=name).fit(X, y) - assert isinstance(glm._link_instance, instance.__class__) - - glm = GeneralizedLinearRegressor(family="normal", link="not a link") - with pytest.raises(ValueError, match="link must be"): - glm.fit(X, y) - - [email protected]( - "family, expected_link_class", - [ - ("normal", IdentityLink), - ("poisson", LogLink), - ("gamma", LogLink), - ("inverse-gaussian", LogLink), - ], -) -def test_glm_link_auto(family, expected_link_class): - # Make sure link='auto' delivers the expected link function - y = np.array([0.1, 0.5]) # in range of all distributions - X = np.array([[1], [2]]) - glm = GeneralizedLinearRegressor(family=family, link="auto").fit(X, y) - assert isinstance(glm._link_instance, expected_link_class) - - @pytest.mark.parametrize("fit_intercept", ["not bool", 1, 0, [True]]) def test_glm_fit_intercept_argument(fit_intercept): """Test GLM for invalid fit_intercept argument.""" y = np.array([1, 2]) X = np.array([[1], [1]]) - glm = GeneralizedLinearRegressor(fit_intercept=fit_intercept) + glm = _GeneralizedLinearRegressor(fit_intercept=fit_intercept) with pytest.raises(ValueError, match="fit_intercept must be bool"): glm.fit(X, y) @@ -125,14 +67,14 @@ def test_glm_solver_argument(solver): """Test GLM for invalid solver argument.""" y = np.array([1, 2]) X = np.array([[1], [2]]) - glm = GeneralizedLinearRegressor(solver=solver) + glm = _GeneralizedLinearRegressor(solver=solver) with pytest.raises(ValueError): glm.fit(X, y) @pytest.mark.parametrize( "Estimator", - [GeneralizedLinearRegressor, PoissonRegressor, GammaRegressor, TweedieRegressor], + [_GeneralizedLinearRegressor, PoissonRegressor, GammaRegressor, TweedieRegressor], ) @pytest.mark.parametrize( "params, err_type, err_msg", @@ -200,21 +142,36 @@ def test_glm_warm_start_argument(warm_start): """Test GLM for invalid warm_start argument.""" y = np.array([1, 2]) X = np.array([[1], [1]]) - glm = GeneralizedLinearRegressor(warm_start=warm_start) + glm = _GeneralizedLinearRegressor(warm_start=warm_start) with pytest.raises(ValueError, match="warm_start must be bool"): glm.fit(X, y) [email protected]( + "glm", + [ + TweedieRegressor(power=3), + PoissonRegressor(), + GammaRegressor(), + TweedieRegressor(power=1.5), + ], +) +def test_glm_wrong_y_range(glm): + y = np.array([-1, 2]) + X = np.array([[1], [1]]) + msg = r"Some value\(s\) of y are out of the valid range of the loss" + with pytest.raises(ValueError, match=msg): + glm.fit(X, y) + + @pytest.mark.parametrize("fit_intercept", [False, True]) def test_glm_identity_regression(fit_intercept): """Test GLM regression with identity link on a simple dataset.""" coef = [1.0, 2.0] X = np.array([[1, 1, 1, 1, 1], [0, 1, 2, 3, 4]]).T y = np.dot(X, coef) - glm = GeneralizedLinearRegressor( + glm = _GeneralizedLinearRegressor( alpha=0, - family="normal", - link="identity", fit_intercept=fit_intercept, tol=1e-12, ) @@ -229,19 +186,19 @@ def test_glm_identity_regression(fit_intercept): @pytest.mark.parametrize("fit_intercept", [False, True]) @pytest.mark.parametrize("alpha", [0.0, 1.0]) [email protected]("family", ["normal", "poisson", "gamma"]) -def test_glm_sample_weight_consistentcy(fit_intercept, alpha, family): [email protected]( + "GLMEstimator", [_GeneralizedLinearRegressor, PoissonRegressor, GammaRegressor] +) +def test_glm_sample_weight_consistency(fit_intercept, alpha, GLMEstimator): """Test that the impact of sample_weight is consistent""" rng = np.random.RandomState(0) n_samples, n_features = 10, 5 X = rng.rand(n_samples, n_features) y = rng.rand(n_samples) - glm_params = dict( - alpha=alpha, family=family, link="auto", fit_intercept=fit_intercept - ) + glm_params = dict(alpha=alpha, fit_intercept=fit_intercept) - glm = GeneralizedLinearRegressor(**glm_params).fit(X, y) + glm = GLMEstimator(**glm_params).fit(X, y) coef = glm.coef_.copy() # sample_weight=np.ones(..) should be equivalent to sample_weight=None @@ -270,38 +227,38 @@ def test_glm_sample_weight_consistentcy(fit_intercept, alpha, family): sample_weight_1 = np.ones(len(y)) sample_weight_1[: n_samples // 2] = 2 - glm1 = GeneralizedLinearRegressor(**glm_params).fit( - X, y, sample_weight=sample_weight_1 - ) + glm1 = GLMEstimator(**glm_params).fit(X, y, sample_weight=sample_weight_1) - glm2 = GeneralizedLinearRegressor(**glm_params).fit(X2, y2, sample_weight=None) + glm2 = GLMEstimator(**glm_params).fit(X2, y2, sample_weight=None) assert_allclose(glm1.coef_, glm2.coef_) @pytest.mark.parametrize("fit_intercept", [True, False]) @pytest.mark.parametrize( - "family", + "estimator", [ - NormalDistribution(), - PoissonDistribution(), - GammaDistribution(), - InverseGaussianDistribution(), - TweedieDistribution(power=1.5), - TweedieDistribution(power=4.5), + PoissonRegressor(), + GammaRegressor(), + TweedieRegressor(power=3.0), + TweedieRegressor(power=0, link="log"), + TweedieRegressor(power=1.5), + TweedieRegressor(power=4.5), ], ) -def test_glm_log_regression(fit_intercept, family): +def test_glm_log_regression(fit_intercept, estimator): """Test GLM regression with log link on a simple dataset.""" coef = [0.2, -0.1] - X = np.array([[1, 1, 1, 1, 1], [0, 1, 2, 3, 4]]).T + X = np.array([[0, 1, 2, 3, 4], [1, 1, 1, 1, 1]]).T y = np.exp(np.dot(X, coef)) - glm = GeneralizedLinearRegressor( - alpha=0, family=family, link="log", fit_intercept=fit_intercept, tol=1e-7 + glm = clone(estimator).set_params( + alpha=0, + fit_intercept=fit_intercept, + tol=1e-8, ) if fit_intercept: - res = glm.fit(X[:, 1:], y) - assert_allclose(res.coef_, coef[1:], rtol=1e-6) - assert_allclose(res.intercept_, coef[0], rtol=1e-6) + res = glm.fit(X[:, :-1], y) + assert_allclose(res.coef_, coef[:-1], rtol=1e-6) + assert_allclose(res.intercept_, coef[-1], rtol=1e-6) else: res = glm.fit(X, y) assert_allclose(res.coef_, coef, rtol=2e-6) @@ -318,12 +275,12 @@ def test_warm_start(fit_intercept): random_state=42, ) - glm1 = GeneralizedLinearRegressor( + glm1 = _GeneralizedLinearRegressor( warm_start=False, fit_intercept=fit_intercept, max_iter=1000 ) glm1.fit(X, y) - glm2 = GeneralizedLinearRegressor( + glm2 = _GeneralizedLinearRegressor( warm_start=True, fit_intercept=fit_intercept, max_iter=1 ) # As we intentionally set max_iter=1, L-BFGS-B will issue a @@ -389,10 +346,8 @@ def test_normal_ridge_comparison( ) ridge.fit(X_train, y_train, sample_weight=sw_train) - glm = GeneralizedLinearRegressor( + glm = _GeneralizedLinearRegressor( alpha=alpha, - family="normal", - link="identity", fit_intercept=fit_intercept, max_iter=300, tol=1e-5, @@ -420,11 +375,9 @@ def test_poisson_glmnet(): # b 0.03741173122 X = np.array([[-2, -1, 1, 2], [0, 0, 1, 1]]).T y = np.array([0, 1, 1, 2]) - glm = GeneralizedLinearRegressor( + glm = PoissonRegressor( alpha=1, fit_intercept=True, - family="poisson", - link="log", tol=1e-7, max_iter=300, ) @@ -436,52 +389,57 @@ def test_poisson_glmnet(): def test_convergence_warning(regression_data): X, y = regression_data - est = GeneralizedLinearRegressor(max_iter=1, tol=1e-20) + est = _GeneralizedLinearRegressor(max_iter=1, tol=1e-20) with pytest.warns(ConvergenceWarning): est.fit(X, y) -def test_poisson_regression_family(regression_data): - # Make sure the family attribute is read-only to prevent searching over it - # e.g. in a grid search - est = PoissonRegressor() - est.family == "poisson" - - msg = "PoissonRegressor.family must be 'poisson'!" - with pytest.raises(ValueError, match=msg): - est.family = 0 - - -def test_gamma_regression_family(regression_data): - # Make sure the family attribute is read-only to prevent searching over it - # e.g. in a grid search - est = GammaRegressor() - est.family == "gamma" - - msg = "GammaRegressor.family must be 'gamma'!" - with pytest.raises(ValueError, match=msg): - est.family = 0 [email protected]( + "name, link_class", [("identity", IdentityLink), ("log", LogLink)] +) +def test_tweedie_link_argument(name, link_class): + """Test GLM link argument set as string.""" + y = np.array([0.1, 0.5]) # in range of all distributions + X = np.array([[1], [2]]) + glm = TweedieRegressor(power=1, link=name).fit(X, y) + assert isinstance(glm._linear_loss.base_loss.link, link_class) + + glm = TweedieRegressor(power=1, link="not a link") + with pytest.raises( + ValueError, + match=re.escape("The link must be an element of ['auto', 'identity', 'log']"), + ): + glm.fit(X, y) -def test_tweedie_regression_family(regression_data): - # Make sure the family attribute is always a TweedieDistribution and that - # the power attribute is properly updated - power = 2.0 - est = TweedieRegressor(power=power) - assert isinstance(est.family, TweedieDistribution) - assert est.family.power == power - assert est.power == power [email protected]( + "power, expected_link_class", + [ + (0, IdentityLink), # normal + (1, LogLink), # poisson + (2, LogLink), # gamma + (3, LogLink), # inverse-gaussian + ], +) +def test_tweedie_link_auto(power, expected_link_class): + """Test that link='auto' delivers the expected link function""" + y = np.array([0.1, 0.5]) # in range of all distributions + X = np.array([[1], [2]]) + glm = TweedieRegressor(link="auto", power=power).fit(X, y) + assert isinstance(glm._linear_loss.base_loss.link, expected_link_class) - new_power = 0 - new_family = TweedieDistribution(power=new_power) - est.family = new_family - assert isinstance(est.family, TweedieDistribution) - assert est.family.power == new_power - assert est.power == new_power - msg = "TweedieRegressor.family must be of type TweedieDistribution!" - with pytest.raises(TypeError, match=msg): - est.family = None [email protected]("power", [0, 1, 1.5, 2, 3]) [email protected]("link", ["log", "identity"]) +def test_tweedie_score(regression_data, power, link): + """Test that GLM score equals d2_tweedie_score for Tweedie losses.""" + X, y = regression_data + # make y positive + y = np.abs(y) + 1.0 + glm = TweedieRegressor(power=power, link=link).fit(X, y) + assert glm.score(X, y) == pytest.approx( + d2_tweedie_score(y, glm.predict(X), power=power) + ) @pytest.mark.parametrize( @@ -495,3 +453,24 @@ def test_tweedie_regression_family(regression_data): ) def test_tags(estimator, value): assert estimator._get_tags()["requires_positive_y"] is value + + +# TODO(1.3): remove [email protected]( + "est, family", + [ + (PoissonRegressor(), "poisson"), + (GammaRegressor(), "gamma"), + (TweedieRegressor(), TweedieDistribution()), + (TweedieRegressor(power=2), TweedieDistribution(power=2)), + (TweedieRegressor(power=3), TweedieDistribution(power=3)), + ], +) +def test_family_deprecation(est, family): + """Test backward compatibility of the family property.""" + with pytest.warns(FutureWarning, match="`family` was deprecated"): + if isinstance(family, str): + assert est.family == family + else: + assert est.family.__class__ == family.__class__ + assert est.family.power == family.power diff --git a/sklearn/linear_model/_glm/tests/test_link.py b/sklearn/linear_model/_glm/tests/test_link.py deleted file mode 100644 index a52d05b7cff6e..0000000000000 --- a/sklearn/linear_model/_glm/tests/test_link.py +++ /dev/null @@ -1,43 +0,0 @@ -# Authors: Christian Lorentzen <[email protected]> -# -# License: BSD 3 clause -import numpy as np -from numpy.testing import assert_allclose -import pytest -from scipy.optimize import check_grad - -from sklearn.linear_model._glm.link import ( - IdentityLink, - LogLink, - LogitLink, -) - - -LINK_FUNCTIONS = [IdentityLink, LogLink, LogitLink] - - [email protected]("Link", LINK_FUNCTIONS) -def test_link_properties(Link): - """Test link inverse and derivative.""" - rng = np.random.RandomState(42) - x = rng.rand(100) * 100 - link = Link() - if isinstance(link, LogitLink): - # careful for large x, note expit(36) = 1 - # limit max eta to 15 - x = x / 100 * 15 - assert_allclose(link(link.inverse(x)), x) - # if g(h(x)) = x, then g'(h(x)) = 1/h'(x) - # g = link, h = link.inverse - assert_allclose(link.derivative(link.inverse(x)), 1 / link.inverse_derivative(x)) - - [email protected]("Link", LINK_FUNCTIONS) -def test_link_derivative(Link): - link = Link() - x = np.random.RandomState(0).rand(1) - err = check_grad(link, link.derivative, x) / link.derivative(x) - assert abs(err) < 1e-6 - - err = check_grad(link.inverse, link.inverse_derivative, x) / link.derivative(x) - assert abs(err) < 1e-6 diff --git a/sklearn/tests/test_common.py b/sklearn/tests/test_common.py index 251f0831fb380..4ff94b11793d2 100644 --- a/sklearn/tests/test_common.py +++ b/sklearn/tests/test_common.py @@ -415,7 +415,6 @@ def test_transformers_get_feature_names_out(transformer): VALIDATE_ESTIMATOR_INIT = [ "SGDOneClassSVM", "TheilSenRegressor", - "TweedieRegressor", ] VALIDATE_ESTIMATOR_INIT = set(VALIDATE_ESTIMATOR_INIT)
[ { "path": "doc/modules/linear_model.rst", "old_path": "a/doc/modules/linear_model.rst", "new_path": "b/doc/modules/linear_model.rst", "metadata": "diff --git a/doc/modules/linear_model.rst b/doc/modules/linear_model.rst\nindex 6d176e8482537..24dfa901b1d42 100644\n--- a/doc/modules/linear_model.rst\n+++ b/doc/modules/linear_model.rst\n@@ -1032,7 +1032,7 @@ reproductive exponential dispersion model (EDM) [11]_).\n \n The minimization problem becomes:\n \n-.. math:: \\min_{w} \\frac{1}{2 n_{\\text{samples}}} \\sum_i d(y_i, \\hat{y}_i) + \\frac{\\alpha}{2} ||w||_2,\n+.. math:: \\min_{w} \\frac{1}{2 n_{\\text{samples}}} \\sum_i d(y_i, \\hat{y}_i) + \\frac{\\alpha}{2} ||w||_2^2,\n \n where :math:`\\alpha` is the L2 regularization penalty. When sample weights are\n provided, the average becomes a weighted average.\n" }, { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex f64a6bda6ea95..13b473fba11a9 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -557,6 +557,12 @@ Changelog\n :pr:`21808`, :pr:`20567` and :pr:`21814` by\n :user:`Christian Lorentzen <lorentzenchr>`.\n \n+- |Enhancement| :class:`~linear_model.GammaRegressor`,\n+ :class:`~linear_model.PoissonRegressor` and :class:`~linear_model.TweedieRegressor`\n+ are faster for ``solvers=\"lbfgs\"``.\n+ :pr:`22548`, :pr:`21808` and :pr:`20567` by\n+ :user:`Christian Lorentzen <lorentzenchr>`.\n+\n - |Enhancement| Rename parameter `base_estimator` to `estimator` in\n :class:`linear_model.RANSACRegressor` to improve readability and consistency.\n `base_estimator` is deprecated and will be removed in 1.3.\n@@ -590,6 +596,12 @@ Changelog\n sub-problem while now all of them are recorded. :pr:`21998` by\n :user:`Olivier Grisel <ogrisel>`.\n \n+- |Fix| The property `family` of :class:`linear_model.TweedieRegressor` is not\n+ validated in `__init__` anymore. Instead, this (private) property is deprecated in\n+ :class:`linear_model.GammaRegressor`, :class:`linear_model.PoissonRegressor` and\n+ :class:`linear_model.TweedieRegressor`, and will be removed in 1.3.\n+ :pr:`22548` by :user:`Christian Lorentzen <lorentzenchr>`.\n+\n - |Enhancement| :class:`linear_model.BayesianRidge` and\n :class:`linear_model.ARDRegression` now preserve float32 dtype. :pr:`9087` by\n :user:`Arthur Imbert <Henley13>` and :pr:`22525` by :user:`Meekail Zain <micky774>`.\n" } ]
1.01
aee564c544e3245e52bd413709e43f192ad02ba9
[ "sklearn/_loss/tests/test_link.py::test_is_in_range[interval1]", "sklearn/_loss/tests/test_glm_distribution.py::test_deviance_derivative[TweedieDistribution0]", "sklearn/_loss/tests/test_link.py::test_link_out_argument[MultinomialLogit]", "sklearn/_loss/tests/test_glm_distribution.py::test_deviance_zero[family0-chk_values0]", "sklearn/_loss/tests/test_link.py::test_is_in_range[interval4]", "sklearn/_loss/tests/test_link.py::test_is_in_range[interval11]", "sklearn/_loss/tests/test_link.py::test_is_in_range[interval9]", "sklearn/_loss/tests/test_link.py::test_link_inverse_identity[LogLink]", "sklearn/_loss/tests/test_link.py::test_is_in_range[interval8]", "sklearn/_loss/tests/test_link.py::test_is_in_range[interval5]", "sklearn/_loss/tests/test_link.py::test_is_in_range[interval3]", "sklearn/_loss/tests/test_link.py::test_link_out_argument[IdentityLink]", "sklearn/_loss/tests/test_glm_distribution.py::test_deviance_derivative[TweedieDistribution3]", "sklearn/_loss/tests/test_glm_distribution.py::test_family_bounds[family1-expected1]", "sklearn/_loss/tests/test_link.py::test_is_in_range[interval10]", "sklearn/_loss/tests/test_glm_distribution.py::test_deviance_derivative[TweedieDistribution2]", "sklearn/_loss/tests/test_link.py::test_is_in_range[interval2]", "sklearn/_loss/tests/test_link.py::test_link_out_argument[LogitLink]", "sklearn/_loss/tests/test_link.py::test_link_inverse_identity[MultinomialLogit]", "sklearn/_loss/tests/test_link.py::test_link_out_argument[LogLink]", "sklearn/_loss/tests/test_link.py::test_is_in_range[interval7]", "sklearn/_loss/tests/test_link.py::test_link_inverse_identity[LogitLink]", "sklearn/_loss/tests/test_glm_distribution.py::test_deviance_zero[family2-chk_values2]", "sklearn/_loss/tests/test_glm_distribution.py::test_deviance_derivative[InverseGaussianDistribution]", "sklearn/_loss/tests/test_glm_distribution.py::test_invalid_distribution_bound", "sklearn/_loss/tests/test_glm_distribution.py::test_tweedie_distribution_power", "sklearn/_loss/tests/test_glm_distribution.py::test_deviance_zero[family5-chk_values5]", "sklearn/_loss/tests/test_glm_distribution.py::test_deviance_zero[family1-chk_values1]", "sklearn/_loss/tests/test_glm_distribution.py::test_deviance_zero[family3-chk_values3]", "sklearn/_loss/tests/test_glm_distribution.py::test_family_bounds[family3-expected3]", "sklearn/_loss/tests/test_glm_distribution.py::test_family_bounds[family5-expected5]", "sklearn/_loss/tests/test_glm_distribution.py::test_deviance_derivative[NormalDistribution]", "sklearn/_loss/tests/test_glm_distribution.py::test_deviance_derivative[GammaDistribution]", "sklearn/_loss/tests/test_link.py::test_is_in_range[interval6]", "sklearn/_loss/tests/test_glm_distribution.py::test_deviance_zero[family7-chk_values7]", "sklearn/_loss/tests/test_glm_distribution.py::test_deviance_derivative[TweedieDistribution1]", "sklearn/_loss/tests/test_glm_distribution.py::test_family_bounds[family0-expected0]", "sklearn/_loss/tests/test_glm_distribution.py::test_deviance_zero[family6-chk_values6]", "sklearn/_loss/tests/test_glm_distribution.py::test_family_bounds[family4-expected4]", "sklearn/_loss/tests/test_glm_distribution.py::test_family_bounds[family2-expected2]", "sklearn/_loss/tests/test_glm_distribution.py::test_deviance_derivative[TweedieDistribution4]", "sklearn/_loss/tests/test_link.py::test_link_inverse_identity[IdentityLink]", "sklearn/_loss/tests/test_glm_distribution.py::test_deviance_zero[family4-chk_values4]", "sklearn/_loss/tests/test_link.py::test_is_in_range[interval0]", "sklearn/_loss/tests/test_glm_distribution.py::test_deviance_derivative[PoissonDistribution]", "sklearn/_loss/tests/test_glm_distribution.py::test_deviance_zero[family8-chk_values8]" ]
[ "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_true[loss13-y_true_success13-y_true_fail13]", "sklearn/_loss/tests/test_loss.py::test_graceful_squeezing[HalfTweedieLoss5]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[42-ones-PinballLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_on_specific_values[HalfMultinomialLoss-0.0-[0.2, 0.5, 0.3]-1.23983106084446]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_predict_proba[42-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[None-HalfTweedieLossIdentity2]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_derivatives[binomial_loss-30-0.9]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[None-HalfTweedieLoss5]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary[HalfTweedieLossIdentity0]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary[HalfTweedieLoss5]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[range-HalfTweedieLossIdentity1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float32-range-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_pred[loss14-y_pred_success14-y_pred_fail14]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float64-None-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float32-range-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[None-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_pickle[HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[42-None-HalfTweedieLossIdentity1]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[None-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_pickle[HalfTweedieLoss3]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[range-HalfTweedieLoss2]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[range-HalfTweedieLoss5]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[42-None-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[range-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[42-random-HalfTweedieLoss5]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_on_specific_values[PinballLoss-5.0-1.0-1.0]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[None-HalfTweedieLoss3]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[42-None-HalfTweedieLoss4]", "sklearn/_loss/tests/test_loss.py::test_specific_fit_intercept_only[42-loss0-mean-normal]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary[HalfTweedieLoss2]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary[HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[None-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float32-None-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_derivatives[squared_error-117.0-1.05]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[42-None-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessian_raises[params0-Valid options for 'dtype' are .* Got dtype=<class 'numpy.int64'> instead.-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float64-range-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[range-HalfTweedieLoss5]", "sklearn/_loss/tests/test_loss.py::test_predict_proba[42-HalfTweedieLossIdentity0]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[42-None-PinballLoss0]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[42-random-HalfTweedieLoss1]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[42-None-PinballLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float32-range-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[None-PinballLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[None-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_graceful_squeezing[AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[None-HalfTweedieLossIdentity0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_specific_fit_intercept_only[42-loss4-mean-exponential]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_graceful_squeezing[PinballLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[42-None-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[42-ones-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_true[loss20-y_true_success20-y_true_fail20]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[42-random-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_predict_proba[42-HalfTweedieLoss0]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessian_raises[params0-Valid options for 'dtype' are .* Got dtype=<class 'numpy.int64'> instead.-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[42-ones-HalfTweedieLoss5]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_true[loss22-y_true_success22-y_true_fail22]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[42-None-HalfTweedieLoss3]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_pickle[HalfTweedieLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_graceful_squeezing[HalfTweedieLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary[HalfTweedieLoss0]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float32-None-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[None-HalfTweedieLossIdentity3]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float64-range-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_tweedie_log_identity_consistency[0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[42-random-PinballLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_pred[loss9-y_pred_success9-y_pred_fail9]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[range-HalfTweedieLoss2]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[42-ones-HalfTweedieLoss2]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_pred[loss15-y_pred_success15-y_pred_fail15]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[None-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_predict_proba[42-HalfTweedieLossIdentity1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessian_raises[params0-Valid options for 'dtype' are .* Got dtype=<class 'numpy.int64'> instead.-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[None-HalfTweedieLossIdentity1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_true[loss18-y_true_success18-y_true_fail18]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[range-HalfTweedieLossIdentity0]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_true[loss25-y_true_success25-y_true_fail25]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[range-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_derivatives[squared_error-0.0-0.0]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float64-None-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[None-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[range-HalfTweedieLossIdentity1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_true[loss24-y_true_success24-y_true_fail24]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_graceful_squeezing[HalfTweedieLossIdentity3]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[None-HalfTweedieLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_on_specific_values[HalfTweedieLossIdentity-2.0-4.0-0.1931471805599453]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[42-range-HalfTweedieLoss2]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_pickle[AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float64-None-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_on_specific_values[PinballLoss-1.0-5.0-3.0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[range-HalfTweedieLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[42-None-HalfTweedieLossIdentity2]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[range-HalfTweedieLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[42-None-HalfTweedieLoss5]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[42-random-HalfTweedieLossIdentity3]", "sklearn/_loss/tests/test_loss.py::test_loss_on_specific_values[HalfMultinomialLoss-2.0-[0.2, 0.5, 0.3]-1.13983106084446]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[None-HalfTweedieLoss4]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float32-None-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[42-range-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_true[loss12-y_true_success12-y_true_fail12]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[None-PinballLoss1]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float32-None-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_graceful_squeezing[HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_predict_proba[42-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary[PinballLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_specific_fit_intercept_only[42-loss5-mean-exponential]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_on_specific_values[HalfTweedieLossIdentity-2.0-4.0-0.0625]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[None-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[range-HalfTweedieLossIdentity2]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_pred[loss24-y_pred_success24-y_pred_fail24]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[range-HalfTweedieLoss4]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_true[loss3-y_true_success3-y_true_fail3]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_on_specific_values[HalfPoissonLoss-2.0-1.3862943611198906-1.2274112777602189]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[42-random-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_init_parameter_validation[PinballLoss-params1-ValueError-quantile == 0, must be > 0.]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[None-HalfTweedieLoss2]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float64-range-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[None-PinballLoss0]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float32-None-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_on_specific_values[HalfMultinomialLoss-1.0-[0.2, 0.5, 0.3]-0.93983106084446]", "sklearn/_loss/tests/test_loss.py::test_loss_init_parameter_validation[HalfTweedieLoss-params3-TypeError-power must be an instance of float, not NoneType.]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[42-None-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary[HalfTweedieLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[42-None-HalfTweedieLossIdentity1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_graceful_squeezing[HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[42-None-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_on_specific_values[HalfBinomialLoss-0.25-1.3862943611198906-1.2628643221541276]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[42-random-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float32-range-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[42-None-HalfTweedieLossIdentity0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[None-HalfTweedieLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_true[loss1-y_true_success1-y_true_fail1]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float32-None-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_pred[loss5-y_pred_success5-y_pred_fail5]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[None-HalfTweedieLossIdentity0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[42-random-HalfTweedieLoss3]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_pickle[HalfTweedieLossIdentity1]", "sklearn/_loss/tests/test_loss.py::test_loss_pickle[HalfTweedieLossIdentity3]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float32-range-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[None-HalfTweedieLossIdentity1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[42-None-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_true[loss19-y_true_success19-y_true_fail19]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_pred[loss22-y_pred_success22-y_pred_fail22]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[42-range-HalfTweedieLoss2]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[None-HalfTweedieLoss2]", "sklearn/_loss/tests/test_loss.py::test_loss_init_parameter_validation[PinballLoss-params0-TypeError-quantile must be an instance of float, not NoneType.]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_tweedie_log_identity_consistency[2]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_true[loss8-y_true_success8-y_true_fail8]", "sklearn/_loss/tests/test_loss.py::test_binomial_and_multinomial_loss[42]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float32-range-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[42-ones-HalfTweedieLossIdentity1]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_true[loss2-y_true_success2-y_true_fail2]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_tweedie_log_identity_consistency[3]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_true[loss15-y_true_success15-y_true_fail15]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary[HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_true[loss4-y_true_success4-y_true_fail4]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[42-ones-HalfTweedieLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[range-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_pickle[HalfTweedieLoss1]", "sklearn/_loss/tests/test_loss.py::test_graceful_squeezing[HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_graceful_squeezing[HalfTweedieLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_tweedie_log_identity_consistency[-1.5]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[42-range-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[42-range-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary[HalfTweedieLoss4]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[range-PinballLoss1]", "sklearn/_loss/tests/test_loss.py::test_graceful_squeezing[HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[42-range-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[None-HalfTweedieLoss2]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float32-range-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float32-None-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_on_specific_values[PinballLoss-1.0-5.0-2]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[42-range-HalfTweedieLoss5]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float64-None-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[42-ones-HalfTweedieLossIdentity2]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float64-range-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float64-range-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float32-range-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float64-None-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessian_raises[params0-Valid options for 'dtype' are .* Got dtype=<class 'numpy.int64'> instead.-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[None-HalfTweedieLoss4]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_graceful_squeezing[HalfTweedieLoss4]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float32-range-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[42-None-HalfTweedieLoss4]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[range-HalfTweedieLoss3]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary[HalfTweedieLossIdentity2]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[None-HalfTweedieLoss3]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[range-HalfTweedieLoss3]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[range-HalfTweedieLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float32-None-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_predict_proba[42-HalfTweedieLoss2]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_pred[loss8-y_pred_success8-y_pred_fail8]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[42-random-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[range-PinballLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[42-None-HalfTweedieLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float64-None-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[None-HalfTweedieLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_predict_proba[42-HalfTweedieLoss1]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float64-None-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary[HalfTweedieLoss3]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_true[loss10-y_true_success10-y_true_fail10]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[range-PinballLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[range-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[42-None-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_on_specific_values[HalfTweedieLoss-2.0-1.3862943611198906--0.1875]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[42-random-HalfTweedieLoss4]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float64-None-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_pred[loss0-y_pred_success0-y_pred_fail0]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary[HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[42-None-HalfTweedieLoss5]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_true[loss14-y_true_success14-y_true_fail14]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_derivatives[poisson_loss--22.0-10.0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float64-range-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[None-HalfTweedieLoss1]", "sklearn/_loss/tests/test_loss.py::test_graceful_squeezing[HalfTweedieLossIdentity2]", "sklearn/_loss/tests/test_loss.py::test_predict_proba[42-HalfTweedieLoss5]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[range-HalfTweedieLossIdentity2]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[None-PinballLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[42-ones-HalfTweedieLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_on_specific_values[HalfSquaredError-1.0-5.0-8]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[None-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float32-range-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_pickle[HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[None-HalfTweedieLossIdentity2]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_derivatives[poisson_loss-0.0-2.0]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary[HalfTweedieLossIdentity1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float64-None-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_predict_proba[42-HalfTweedieLossIdentity2]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary[HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[42-range-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_predict_proba[42-HalfTweedieLoss3]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float32-None-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_true[loss16-y_true_success16-y_true_fail16]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float32-None-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[range-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_specific_fit_intercept_only[42-loss3-mean-poisson]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[None-PinballLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[None-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float32-None-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[range-HalfTweedieLoss3]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_pickle[HalfTweedieLossIdentity0]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[42-None-HalfTweedieLossIdentity3]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[None-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_specific_fit_intercept_only[42-loss2-<lambda>-normal]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[range-HalfTweedieLossIdentity3]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_derivatives[poisson_loss-12.0-1.0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[42-range-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float32-range-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_pickle[PinballLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float32-range-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[range-HalfTweedieLoss2]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_pred[loss2-y_pred_success2-y_pred_fail2]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float64-range-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_derivatives[binomial_loss--12-0.2]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_on_specific_values[AbsoluteError-1.0-5.0-4]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_true[loss5-y_true_success5-y_true_fail5]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[42-ones-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[range-HalfTweedieLossIdentity2]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[42-range-HalfTweedieLossIdentity0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[42-None-HalfTweedieLossIdentity0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessian_raises[params0-Valid options for 'dtype' are .* Got dtype=<class 'numpy.int64'> instead.-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[42-range-HalfTweedieLoss4]", "sklearn/_loss/tests/test_loss.py::test_predict_proba[42-PinballLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[None-HalfTweedieLoss3]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float32-None-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_pred[loss1-y_pred_success1-y_pred_fail1]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[None-HalfTweedieLoss5]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[None-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[42-random-HalfTweedieLoss0]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[42-range-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[None-HalfTweedieLossIdentity2]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[42-ones-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_true[loss17-y_true_success17-y_true_fail17]", "sklearn/_loss/tests/test_loss.py::test_loss_init_parameter_validation[HalfTweedieLoss-params4-ValueError-power == inf, must be < inf.]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[42-range-PinballLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[range-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[range-HalfTweedieLoss0]", "sklearn/_loss/tests/test_loss.py::test_specific_fit_intercept_only[42-loss1-median-normal]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[range-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[range-HalfTweedieLossIdentity3]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[42-random-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[range-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[None-HalfTweedieLoss5]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[42-ones-HalfTweedieLossIdentity0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_pred[loss23-y_pred_success23-y_pred_fail23]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float64-range-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_init_parameter_validation[PinballLoss-params2-ValueError-quantile == 1.1, must be < 1.]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float64-None-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[None-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float64-range-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[range-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_true[loss6-y_true_success6-y_true_fail6]", "sklearn/_loss/tests/test_loss.py::test_predict_proba[42-HalfTweedieLoss4]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_graceful_squeezing[HalfTweedieLossIdentity0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[range-HalfTweedieLossIdentity1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[42-None-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[42-None-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[42-None-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_pred[loss18-y_pred_success18-y_pred_fail18]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[range-HalfTweedieLossIdentity0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[None-HalfTweedieLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[42-range-HalfTweedieLoss3]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float32-range-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[42-range-PinballLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_predict_proba[42-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[range-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[42-None-HalfTweedieLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[range-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_on_specific_values[HalfTweedieLossIdentity-2.0-4.0-0.6137056388801094]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float32-range-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[42-ones-PinballLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_pred[loss25-y_pred_success25-y_pred_fail25]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[42-None-HalfTweedieLoss2]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary[HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[42-random-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[42-range-HalfTweedieLossIdentity3]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[None-HalfTweedieLossIdentity1]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[42-range-HalfTweedieLoss4]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[range-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_pickle[HalfTweedieLoss5]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[None-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float64-range-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[42-random-HalfTweedieLossIdentity1]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[42-None-HalfTweedieLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_predict_proba[42-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_tweedie_log_identity_consistency[1.5]", "sklearn/_loss/tests/test_loss.py::test_loss_pickle[HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[range-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float64-range-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[None-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[42-range-PinballLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[range-HalfTweedieLossIdentity3]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[None-HalfTweedieLossIdentity3]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_derivatives[binomial_loss-0.3-0.1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_pred[loss21-y_pred_success21-y_pred_fail21]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[42-ones-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[None-HalfTweedieLossIdentity3]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_predict_proba[42-PinballLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[42-range-PinballLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float64-None-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[42-None-PinballLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[range-HalfTweedieLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float32-range-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float32-None-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_on_specific_values[HalfGammaLoss-2.0-1.3862943611198906-1.8862943611198906]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_true[loss0-y_true_success0-y_true_fail0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float64-range-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[range-PinballLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[range-HalfTweedieLoss4]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[None-HalfTweedieLossIdentity0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[None-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_true[loss7-y_true_success7-y_true_fail7]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_pred[loss12-y_pred_success12-y_pred_fail12]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[42-range-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[range-HalfTweedieLossIdentity0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_pred[loss7-y_pred_success7-y_pred_fail7]", "sklearn/_loss/tests/test_loss.py::test_loss_pickle[PinballLoss0]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessian_raises[params0-Valid options for 'dtype' are .* Got dtype=<class 'numpy.int64'> instead.-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_predict_proba[42-HalfTweedieLossIdentity3]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_true[loss9-y_true_success9-y_true_fail9]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[42-ones-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[None-HalfTweedieLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[42-ones-HalfTweedieLoss4]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary[AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_pred[loss13-y_pred_success13-y_pred_fail13]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[None-PinballLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float64-None-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_graceful_squeezing[HalfTweedieLoss3]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float64-None-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_pickle[HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float32-None-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[range-HalfTweedieLoss4]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[42-random-HalfTweedieLoss2]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[42-ones-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_true[loss11-y_true_success11-y_true_fail11]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[42-random-HalfTweedieLossIdentity2]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[range-PinballLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[42-None-HalfTweedieLoss3]", "sklearn/_loss/tests/test_loss.py::test_predict_proba[42-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_pred[loss6-y_pred_success6-y_pred_fail6]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float64-range-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[range-HalfTweedieLoss5]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_graceful_squeezing[PinballLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[42-None-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_pickle[HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[None-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[42-random-HalfTweedieLossIdentity0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float64-None-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_predict_proba[42-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_pred[loss4-y_pred_success4-y_pred_fail4]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[range-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[42-None-HalfTweedieLoss0]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[42-range-HalfTweedieLoss5]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_pred[loss10-y_pred_success10-y_pred_fail10]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[42-range-HalfTweedieLossIdentity0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_pickle[HalfTweedieLossIdentity2]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float64-range-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_tweedie_log_identity_consistency[1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[42-range-HalfTweedieLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_true[loss21-y_true_success21-y_true_fail21]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[42-range-HalfTweedieLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[42-range-HalfTweedieLossIdentity2]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[42-range-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[42-None-HalfTweedieLossIdentity2]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[range-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_same_as_C_functions[None-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[42-range-HalfTweedieLossIdentity2]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[42-None-HalfTweedieLoss2]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_pred[loss20-y_pred_success20-y_pred_fail20]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[42-random-PinballLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float32-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary[HalfTweedieLossIdentity3]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_pred[loss3-y_pred_success3-y_pred_fail3]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float64-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_pred[loss17-y_pred_success17-y_pred_fail17]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[42-ones-HalfTweedieLossIdentity3]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[42-range-HalfTweedieLossIdentity3]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessian_raises[params0-Valid options for 'dtype' are .* Got dtype=<class 'numpy.int64'> instead.-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[42-range-HalfTweedieLossIdentity1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float32-range-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_pred[loss11-y_pred_success11-y_pred_fail11]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[range-HalfPoissonLoss]", "sklearn/_loss/tests/test_link.py::test_interval_raises", "sklearn/_loss/tests/test_loss.py::test_graceful_squeezing[HalfTweedieLossIdentity1]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float32-None-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float64-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[42-range-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_sample_weight_multiplies[42-ones-HalfTweedieLoss3]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[42-None-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float32-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float32-None-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_specific_fit_intercept_only[42-loss6-mean-binomial]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[42-range-HalfTweedieLossIdentity1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[42-range-HalfTweedieLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float32-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[42-range-HalfTweedieLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float32-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[range-PinballLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float64-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessian_raises[params0-Valid options for 'dtype' are .* Got dtype=<class 'numpy.int64'> instead.-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float64-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[None-HalfTweedieLoss4]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[42-None-HalfTweedieLossIdentity3]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float64-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[42-None-PinballLoss0]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float64-float32-True-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float32-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float32-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[None-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-None-float32-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_pickle[HalfTweedieLoss2]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float32-float64-False-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_gradients_hessians_numerically[42-range-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_true[loss23-y_true_success23-y_true_fail23]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float64-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float32-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float32-float64-True-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float32-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float64-True-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float32-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float32-float64-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[42-range-HalfTweedieLoss3]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-None-float64-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_gradients_are_the_same[42-range-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float64-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_multinomial_loss_fit_intercept_only", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float32-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float64-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float64-range-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float32-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_pred[loss19-y_pred_success19-y_pred_fail19]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-1-float32-float32-False-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-None-1-float32-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[C-float64-None-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_derivatives[squared_error--2.0-42]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float32-float32-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float64-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float64-False-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float64-False-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_intercept_only[range-HalfTweedieLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float64-False-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float64-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary_y_pred[loss16-y_pred_success16-y_pred_fail16]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float32-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-None-float64-float64-True-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-None-None-float32-float32-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-None-float64-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float32-True-AbsoluteError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-1-float64-float64-False-HalfGammaLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-1-float64-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_pickle[HalfTweedieLoss4]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-None-1-float32-float32-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[range-HalfMultinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float64-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_graceful_squeezing[HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-1-float32-float32-True-PinballLoss]", "sklearn/_loss/tests/test_loss.py::test_graceful_squeezing[HalfTweedieLoss2]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float64-None-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-1-1-None-float64-float64-True-HalfSquaredError]", "sklearn/_loss/tests/test_loss.py::test_loss_of_perfect_prediction[range-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_init_gradient_and_hessians[F-float64-range-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-None-None-float64-float64-False-HalfTweedieLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-None-1-None-float32-float32-False-HalfPoissonLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[1-None-1-1-float64-float32-True-HalfBinomialLoss]", "sklearn/_loss/tests/test_loss.py::test_loss_boundary[PinballLoss1]", "sklearn/_loss/tests/test_loss.py::test_loss_dtype[2-1-1-1-float64-float32-False-HalfGammaLoss]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/modules/linear_model.rst", "old_path": "a/doc/modules/linear_model.rst", "new_path": "b/doc/modules/linear_model.rst", "metadata": "diff --git a/doc/modules/linear_model.rst b/doc/modules/linear_model.rst\nindex 6d176e8482537..24dfa901b1d42 100644\n--- a/doc/modules/linear_model.rst\n+++ b/doc/modules/linear_model.rst\n@@ -1032,7 +1032,7 @@ reproductive exponential dispersion model (EDM) [11]_).\n \n The minimization problem becomes:\n \n-.. math:: \\min_{w} \\frac{1}{2 n_{\\text{samples}}} \\sum_i d(y_i, \\hat{y}_i) + \\frac{\\alpha}{2} ||w||_2,\n+.. math:: \\min_{w} \\frac{1}{2 n_{\\text{samples}}} \\sum_i d(y_i, \\hat{y}_i) + \\frac{\\alpha}{2} ||w||_2^2,\n \n where :math:`\\alpha` is the L2 regularization penalty. When sample weights are\n provided, the average becomes a weighted average.\n" }, { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex f64a6bda6ea95..13b473fba11a9 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -557,6 +557,12 @@ Changelog\n :pr:`<PRID>`, :pr:`<PRID>` and :pr:`<PRID>` by\n :user:`<NAME>`.\n \n+- |Enhancement| :class:`~linear_model.GammaRegressor`,\n+ :class:`~linear_model.PoissonRegressor` and :class:`~linear_model.TweedieRegressor`\n+ are faster for ``solvers=\"lbfgs\"``.\n+ :pr:`<PRID>`, :pr:`<PRID>` and :pr:`<PRID>` by\n+ :user:`<NAME>`.\n+\n - |Enhancement| Rename parameter `base_estimator` to `estimator` in\n :class:`linear_model.RANSACRegressor` to improve readability and consistency.\n `base_estimator` is deprecated and will be removed in 1.3.\n@@ -590,6 +596,12 @@ Changelog\n sub-problem while now all of them are recorded. :pr:`<PRID>` by\n :user:`<NAME>`.\n \n+- |Fix| The property `family` of :class:`linear_model.TweedieRegressor` is not\n+ validated in `__init__` anymore. Instead, this (private) property is deprecated in\n+ :class:`linear_model.GammaRegressor`, :class:`linear_model.PoissonRegressor` and\n+ :class:`linear_model.TweedieRegressor`, and will be removed in 1.3.\n+ :pr:`<PRID>` by :user:`<NAME>`.\n+\n - |Enhancement| :class:`linear_model.BayesianRidge` and\n :class:`linear_model.ARDRegression` now preserve float32 dtype. :pr:`<PRID>` by\n :user:`<NAME>` and :pr:`<PRID>` by :user:`<NAME>`.\n" } ]
diff --git a/doc/modules/linear_model.rst b/doc/modules/linear_model.rst index 6d176e8482537..24dfa901b1d42 100644 --- a/doc/modules/linear_model.rst +++ b/doc/modules/linear_model.rst @@ -1032,7 +1032,7 @@ reproductive exponential dispersion model (EDM) [11]_). The minimization problem becomes: -.. math:: \min_{w} \frac{1}{2 n_{\text{samples}}} \sum_i d(y_i, \hat{y}_i) + \frac{\alpha}{2} ||w||_2, +.. math:: \min_{w} \frac{1}{2 n_{\text{samples}}} \sum_i d(y_i, \hat{y}_i) + \frac{\alpha}{2} ||w||_2^2, where :math:`\alpha` is the L2 regularization penalty. When sample weights are provided, the average becomes a weighted average. diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index f64a6bda6ea95..13b473fba11a9 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -557,6 +557,12 @@ Changelog :pr:`<PRID>`, :pr:`<PRID>` and :pr:`<PRID>` by :user:`<NAME>`. +- |Enhancement| :class:`~linear_model.GammaRegressor`, + :class:`~linear_model.PoissonRegressor` and :class:`~linear_model.TweedieRegressor` + are faster for ``solvers="lbfgs"``. + :pr:`<PRID>`, :pr:`<PRID>` and :pr:`<PRID>` by + :user:`<NAME>`. + - |Enhancement| Rename parameter `base_estimator` to `estimator` in :class:`linear_model.RANSACRegressor` to improve readability and consistency. `base_estimator` is deprecated and will be removed in 1.3. @@ -590,6 +596,12 @@ Changelog sub-problem while now all of them are recorded. :pr:`<PRID>` by :user:`<NAME>`. +- |Fix| The property `family` of :class:`linear_model.TweedieRegressor` is not + validated in `__init__` anymore. Instead, this (private) property is deprecated in + :class:`linear_model.GammaRegressor`, :class:`linear_model.PoissonRegressor` and + :class:`linear_model.TweedieRegressor`, and will be removed in 1.3. + :pr:`<PRID>` by :user:`<NAME>`. + - |Enhancement| :class:`linear_model.BayesianRidge` and :class:`linear_model.ARDRegression` now preserve float32 dtype. :pr:`<PRID>` by :user:`<NAME>` and :pr:`<PRID>` by :user:`<NAME>`.
scikit-learn/scikit-learn
scikit-learn__scikit-learn-21278
https://github.com/scikit-learn/scikit-learn/pull/21278
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index c4f16f4404963..39255056d4e91 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -113,6 +113,10 @@ Changelog :pr:`20880` by :user:`Guillaume Lemaitre <glemaitre>` and :user:`András Simon <simonandras>`. +- |Enhancement| :func:`utils.validation.check_array` returns a float + ndarray with `np.nan` when passed a `Float32` or `Float64` pandas extension + array with `pd.NA`. :pr:`21278` by `Thomas Fan`_. + Code and Documentation Contributors ----------------------------------- diff --git a/sklearn/utils/validation.py b/sklearn/utils/validation.py index a2693a44a9f8b..48dca589b2def 100644 --- a/sklearn/utils/validation.py +++ b/sklearn/utils/validation.py @@ -483,6 +483,33 @@ def _ensure_no_complex_data(array): raise ValueError("Complex data not supported\n{}\n".format(array)) +def _pandas_dtype_needs_early_conversion(pd_dtype): + """Return True if pandas extension pd_dtype need to be converted early.""" + try: + from pandas.api.types import ( + is_extension_array_dtype, + is_float_dtype, + is_integer_dtype, + is_sparse, + ) + except ImportError: + return False + + if is_sparse(pd_dtype) or not is_extension_array_dtype(pd_dtype): + # Sparse arrays will be converted later in `check_array` + # Only handle extension arrays for interger and floats + return False + elif is_float_dtype(pd_dtype): + # Float ndarrays can normally support nans. They need to be converted + # first to map pd.NA to np.nan + return True + elif is_integer_dtype(pd_dtype): + # XXX: Warn when converting from a high integer to a float + return True + + return False + + def check_array( array, accept_sparse=False, @@ -605,7 +632,7 @@ def check_array( # check if the object contains several dtypes (typically a pandas # DataFrame), and store them. If not, store None. dtypes_orig = None - has_pd_integer_array = False + pandas_requires_conversion = False if hasattr(array, "dtypes") and hasattr(array.dtypes, "__array__"): # throw warning if columns are sparse. If all columns are sparse, then # array.sparse exists and sparsity will be preserved (later). @@ -618,42 +645,17 @@ def check_array( "It will be converted to a dense numpy array." ) - dtypes_orig = list(array.dtypes) - # pandas boolean dtype __array__ interface coerces bools to objects - for i, dtype_iter in enumerate(dtypes_orig): + dtypes_orig = [] + for dtype_iter in array.dtypes: if dtype_iter.kind == "b": - dtypes_orig[i] = np.dtype(object) - elif dtype_iter.name.startswith(("Int", "UInt")): - # name looks like an Integer Extension Array, now check for - # the dtype - with suppress(ImportError): - from pandas import ( - Int8Dtype, - Int16Dtype, - Int32Dtype, - Int64Dtype, - UInt8Dtype, - UInt16Dtype, - UInt32Dtype, - UInt64Dtype, - ) - - if isinstance( - dtype_iter, - ( - Int8Dtype, - Int16Dtype, - Int32Dtype, - Int64Dtype, - UInt8Dtype, - UInt16Dtype, - UInt32Dtype, - UInt64Dtype, - ), - ): - has_pd_integer_array = True - - if all(isinstance(dtype, np.dtype) for dtype in dtypes_orig): + # pandas boolean dtype __array__ interface coerces bools to objects + dtype_iter = np.dtype(object) + elif _pandas_dtype_needs_early_conversion(dtype_iter): + pandas_requires_conversion = True + + dtypes_orig.append(dtype_iter) + + if all(isinstance(dtype_iter, np.dtype) for dtype_iter in dtypes_orig): dtype_orig = np.result_type(*dtypes_orig) if dtype_numeric: @@ -672,9 +674,12 @@ def check_array( # list of accepted types. dtype = dtype[0] - if has_pd_integer_array: - # If there are any pandas integer extension arrays, + if pandas_requires_conversion: + # pandas dataframe requires conversion earlier to handle extension dtypes with + # nans array = array.astype(dtype) + # Since we converted here, we do not need to convert again later + dtype = None if force_all_finite not in (True, False, "allow-nan"): raise ValueError(
diff --git a/sklearn/utils/tests/test_validation.py b/sklearn/utils/tests/test_validation.py index 167118fb4ff8f..00c6cf85dda4d 100644 --- a/sklearn/utils/tests/test_validation.py +++ b/sklearn/utils/tests/test_validation.py @@ -390,7 +390,9 @@ def test_check_array_dtype_numeric_errors(X): check_array(X, dtype="numeric") [email protected]("pd_dtype", ["Int8", "Int16", "UInt8", "UInt16"]) [email protected]( + "pd_dtype", ["Int8", "Int16", "UInt8", "UInt16", "Float32", "Float64"] +) @pytest.mark.parametrize( "dtype, expected_dtype", [ @@ -400,14 +402,18 @@ def test_check_array_dtype_numeric_errors(X): ], ) def test_check_array_pandas_na_support(pd_dtype, dtype, expected_dtype): - # Test pandas IntegerArray with pd.NA + # Test pandas numerical extension arrays with pd.NA pd = pytest.importorskip("pandas", minversion="1.0") + if pd_dtype in {"Float32", "Float64"}: + # Extension dtypes with Floats was added in 1.2 + pd = pytest.importorskip("pandas", minversion="1.2") + X_np = np.array( [[1, 2, 3, np.nan, np.nan], [np.nan, np.nan, 8, 4, 6], [1, 2, 3, 4, 5]] ).T - # Creates dataframe with IntegerArrays with pd.NA + # Creates dataframe with numerical extension arrays with pd.NA X = pd.DataFrame(X_np, dtype=pd_dtype, columns=["a", "b", "c"]) # column c has no nans X["c"] = X["c"].astype("float")
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex c4f16f4404963..39255056d4e91 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -113,6 +113,10 @@ Changelog\n :pr:`20880` by :user:`Guillaume Lemaitre <glemaitre>`\n and :user:`András Simon <simonandras>`.\n \n+- |Enhancement| :func:`utils.validation.check_array` returns a float\n+ ndarray with `np.nan` when passed a `Float32` or `Float64` pandas extension\n+ array with `pd.NA`. :pr:`21278` by `Thomas Fan`_.\n+\n Code and Documentation Contributors\n -----------------------------------\n \n" } ]
1.01
958ccc5bb1d43594eafe825e387e3e9876ac8893
[ "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_raise_exception[csr]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[tuple-float]", "sklearn/utils/tests/test_validation.py::test_check_sparse_pandas_sp_format[True]", "sklearn/utils/tests/test_validation.py::test_check_array_memmap[True]", "sklearn/utils/tests/test_validation.py::test_num_features[list]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_scalars[str]", "sklearn/utils/tests/test_validation.py::test_check_non_negative[bsr_matrix]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[byte-uint16]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[False-X0-Input contains NaN, infinity or a value too large for.*int]", "sklearn/utils/tests/test_validation.py::test_check_non_negative[csr_matrix]", "sklearn/utils/tests/test_validation.py::test_check_non_negative[asarray]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[series-float]", "sklearn/utils/tests/test_validation.py::test_check_is_fitted_with_attributes[tuple]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[list-float]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[float64-float64-Int16]", "sklearn/utils/tests/test_validation.py::test_check_array_dtype_numeric_errors[X2]", "sklearn/utils/tests/test_validation.py::test_check_array_numeric_warns[X4]", "sklearn/utils/tests/test_validation.py::test_num_features[array]", "sklearn/utils/tests/test_validation.py::test_check_sparse_pandas_sp_format[coo]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[int32-long]", "sklearn/utils/tests/test_validation.py::test_check_array_dtype_numeric_errors[X3]", "sklearn/utils/tests/test_validation.py::test_as_float_array", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[uint8-int8]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[int16-int32]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[array-int]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_valid[asarray-nan-allow-nan]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_valid[asarray-inf-False]", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_valid[True-insignificant neg float64]", "sklearn/utils/tests/test_validation.py::test_deprecate_positional_args_warns_for_class", "sklearn/utils/tests/test_validation.py::test_check_scalar_invalid[1-test_name1-float-2-4-neither-err_msg0]", "sklearn/utils/tests/test_validation.py::test_check_non_negative[dok_matrix]", "sklearn/utils/tests/test_validation.py::test_get_feature_names_invalid_dtypes_warns[multi-index]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_valid[csr_matrix-nan-allow-nan]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_no_exception[coo]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[uint-uint64-unsignedinteger]", "sklearn/utils/tests/test_validation.py::test_num_features[sparse_csr]", "sklearn/utils/tests/test_validation.py::test_check_array_series", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[int8-byte-integer]", "sklearn/utils/tests/test_validation.py::test_check_array_dtype_numeric_errors[X0]", "sklearn/utils/tests/test_validation.py::test_check_X_y_informative_error", "sklearn/utils/tests/test_validation.py::test_check_feature_names_in", "sklearn/utils/tests/test_validation.py::test_num_features_errors_scalars[float]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_sparse_no_exception", "sklearn/utils/tests/test_validation.py::test_check_sparse_pandas_sp_format[csr]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[array-str]", "sklearn/utils/tests/test_validation.py::test_check_array_dtype_numeric_errors[X1]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_no_exception[bsr]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[list-int]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[asarray-nan-True-Input contains NaN, infinity]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[tuple-str]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[float16-float32]", "sklearn/utils/tests/test_validation.py::test_np_matrix", "sklearn/utils/tests/test_validation.py::test_check_sample_weight", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[True-X0-Input contains NaN, infinity or a value too large for.*int]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_raise_exception[csc]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[intc-int32-integer]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[tuple-bool]", "sklearn/utils/tests/test_validation.py::test_check_non_negative[lil_matrix]", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_raise[csc_matrix]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[longdouble-float16]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[csr_matrix-nan-1-Input contains NaN, infinity]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[dtype0-float32-Int16]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_no_exception[csc]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_valid[csr_matrix-inf-False]", "sklearn/utils/tests/test_validation.py::test_check_is_fitted_with_is_fitted", "sklearn/utils/tests/test_validation.py::test_check_array_numeric_warns[X3]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[array-float]", "sklearn/utils/tests/test_validation.py::test_as_float_array_nan[X1]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[int64-longlong-integer]", "sklearn/utils/tests/test_validation.py::test_check_array_numeric_warns[X1]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[tuple-dict]", "sklearn/utils/tests/test_validation.py::test_suppress_validation", "sklearn/utils/tests/test_validation.py::test_check_is_fitted_attributes", "sklearn/utils/tests/test_validation.py::test_num_features[tuple]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[csr_matrix-nan-True-Input contains NaN, infinity]", "sklearn/utils/tests/test_validation.py::test_deprecate_positional_args_warns_for_function", "sklearn/utils/tests/test_validation.py::test_num_features[dataframe]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[float32-double]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[float64-float64-UInt16]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[False-X2-Input contains NaN, infinity or a value too large for.*int]", "sklearn/utils/tests/test_validation.py::test_check_array_deprecated_matrix", "sklearn/utils/tests/test_validation.py::test_num_features[sparse_csc]", "sklearn/utils/tests/test_validation.py::test_check_array_dtype_warning", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_valid[asarray-nan-False]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[dtype0-float32-UInt8]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[uintc-uint32-unsignedinteger]", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_equals[array]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[uint32-uint64]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[False-X3-cannot convert float NaN to integer]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[numeric-float64-UInt16]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[list-str]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_no_exception[csr]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[series-dict]", "sklearn/utils/tests/test_validation.py::test_check_sparse_pandas_sp_format[bsr]", "sklearn/utils/tests/test_validation.py::test_check_scalar_invalid[5-test_name3-int-2-4-neither-err_msg2]", "sklearn/utils/tests/test_validation.py::test_check_array", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_valid[csr_matrix-nan-False]", "sklearn/utils/tests/test_validation.py::test_check_array_min_samples_and_features_messages", "sklearn/utils/tests/test_validation.py::test_check_is_fitted", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[dtype0-float32-Int8]", "sklearn/utils/tests/test_validation.py::test_check_fit_params[indices1]", "sklearn/utils/tests/test_validation.py::test_check_scalar_invalid[2-test_name4-int-2-4-right-err_msg3]", "sklearn/utils/tests/test_validation.py::test_check_non_negative[coo_matrix]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[array-bool]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[True-X1-Input contains NaN, infinity or a value too large for.*int]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[list-dict]", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_valid[True-insignificant neg]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[asarray-inf-True-Input contains NaN, infinity]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_invalid[significant neg]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[tuple-int]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[csr_matrix-nan-allow-inf-force_all_finite should be a bool or \"allow-nan\"]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[True-X2-Input contains NaN, infinity or a value too large for.*int]", "sklearn/utils/tests/test_validation.py::test_check_is_fitted_with_attributes[list]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[dtype0-float32-UInt16]", "sklearn/utils/tests/test_validation.py::test_check_sparse_pandas_sp_format[csc]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[asarray-nan-allow-inf-force_all_finite should be a bool or \"allow-nan\"]", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_raise[csr_matrix]", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_valid[True-insignificant_imag]", "sklearn/utils/tests/test_validation.py::test_deprecate_positional_args_warns_for_function_version", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_invalid[significant neg float32]", "sklearn/utils/tests/test_validation.py::test_check_array_complex_data_error", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_not_equals[array]", "sklearn/utils/tests/test_validation.py::test_check_non_negative[csc_matrix]", "sklearn/utils/tests/test_validation.py::test_retrieve_samples_from_non_standard_shape", "sklearn/utils/tests/test_validation.py::test_get_feature_names_numpy", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[array-dict]", "sklearn/utils/tests/test_validation.py::test_check_scalar_invalid[4-test_name5-int-2-4-left-err_msg4]", "sklearn/utils/tests/test_validation.py::test_as_float_array_nan[X0]", "sklearn/utils/tests/test_validation.py::test_check_array_numeric_warns[X0]", "sklearn/utils/tests/test_validation.py::test_memmap", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_raise_exception[bsr]", "sklearn/utils/tests/test_validation.py::test_check_consistent_length", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[float64-float64-UInt8]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[int0-long-integer]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[uint16-ushort-unsignedinteger]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[asarray-nan-1-Input contains NaN, infinity]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[float64-float64-Int8]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[asarray-inf-allow-nan-Input contains infinity]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[int-long-integer]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_dtype_casting", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[numeric-float64-Int8]", "sklearn/utils/tests/test_validation.py::test_check_non_negative[dia_matrix]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[list-bool]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[series-bool]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_scalars[bool]", "sklearn/utils/tests/test_validation.py::test_check_array_numeric_warns[X2]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_dtype_object_conversion", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_invalid[all negative]", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_valid[True-insignificant pos]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[series-str]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[float16-half-floating]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[csr_matrix-inf-True-Input contains NaN, infinity]", "sklearn/utils/tests/test_validation.py::test_has_fit_parameter", "sklearn/utils/tests/test_validation.py::test_num_features_errors_scalars[int]", "sklearn/utils/tests/test_validation.py::test_check_fit_params[None]", "sklearn/utils/tests/test_validation.py::test_check_array_memmap[False]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[True-X3-cannot convert float NaN to integer]", "sklearn/utils/tests/test_validation.py::test_get_feature_names_invalid_dtypes_warns[mixed]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[longfloat-longdouble-floating]", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_equals[csr_matrix]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[ushort-uint32]", "sklearn/utils/tests/test_validation.py::test_check_symmetric", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[uintp-ulonglong-unsignedinteger]", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_invalid[significant_imag]", "sklearn/utils/tests/test_validation.py::test_check_is_fitted_with_attributes[single]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[series-int]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[csr_matrix-inf-allow-nan-Input contains infinity]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_raise_exception[coo]", "sklearn/utils/tests/test_validation.py::test_ordering", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_not_equals[csr_matrix]", "sklearn/utils/tests/test_validation.py::test_check_array_on_mock_dataframe", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_equals[csc_matrix]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_sparse_type_exception", "sklearn/utils/tests/test_validation.py::test_check_scalar_invalid[4-test_name6-int-2-4-bad parameter value-err_msg5]", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_invalid[significant neg float64]", "sklearn/utils/tests/test_validation.py::test_check_feature_names_in_pandas", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[int_-intp-integer]", "sklearn/utils/tests/test_validation.py::test_check_dataframe_fit_attribute", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[ubyte-uint8-unsignedinteger]", "sklearn/utils/tests/test_validation.py::test_check_scalar_invalid[1-test_name2-int-2-4-neither-err_msg1]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[numeric-float64-UInt8]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[False-X1-Input contains NaN, infinity or a value too large for.*int]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[double-float64-floating]", "sklearn/utils/tests/test_validation.py::test_check_dataframe_mixed_float_dtypes", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[short-int16-integer]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[numeric-float64-Int16]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[single-float32-floating]", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_not_equals[csc_matrix]", "sklearn/utils/tests/test_validation.py::test_check_array_dtype_stability", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_valid[True-insignificant neg float32]", "sklearn/utils/tests/test_validation.py::test_get_feature_names_pandas" ]
[ "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[numeric-float64-Float64]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[dtype0-float32-Float64]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[float64-float64-Float32]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[numeric-float64-Float32]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[float64-float64-Float64]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[dtype0-float32-Float32]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex c4f16f4404963..39255056d4e91 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -113,6 +113,10 @@ Changelog\n :pr:`<PRID>` by :user:`<NAME>`\n and :user:`<NAME>`.\n \n+- |Enhancement| :func:`utils.validation.check_array` returns a float\n+ ndarray with `np.nan` when passed a `Float32` or `Float64` pandas extension\n+ array with `pd.NA`. :pr:`<PRID>` by `<NAME>`_.\n+\n Code and Documentation Contributors\n -----------------------------------\n \n" } ]
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index c4f16f4404963..39255056d4e91 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -113,6 +113,10 @@ Changelog :pr:`<PRID>` by :user:`<NAME>` and :user:`<NAME>`. +- |Enhancement| :func:`utils.validation.check_array` returns a float + ndarray with `np.nan` when passed a `Float32` or `Float64` pandas extension + array with `pd.NA`. :pr:`<PRID>` by `<NAME>`_. + Code and Documentation Contributors -----------------------------------
scikit-learn/scikit-learn
scikit-learn__scikit-learn-22212
https://github.com/scikit-learn/scikit-learn/pull/22212
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index c0f705a8ceef7..a9d4013b9b375 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -423,6 +423,11 @@ Changelog ndarray with `np.nan` when passed a `Float32` or `Float64` pandas extension array with `pd.NA`. :pr:`21278` by `Thomas Fan`_. +- |Enhancement| Adds :term:`get_feature_names_out` to + :class:`neighbors.RadiusNeighborsTransformer`, :class:`neighbors.KNeighborsTransformer` + and :class:`neighbors.NeighborhoodComponentsAnalysis`. :pr:`22212` by + :user : `Meekail Zain <micky774>`. + - |Fix| :class:`neighbors.KernelDensity` now validates input parameters in `fit` instead of `__init__`. :pr:`21430` by :user:`Desislava Vasileva <DessyVV>` and :user:`Lucy Jimenez <LucyJimenez>`. diff --git a/sklearn/neighbors/_graph.py b/sklearn/neighbors/_graph.py index 13c91f4f31339..1371d3234bbb4 100644 --- a/sklearn/neighbors/_graph.py +++ b/sklearn/neighbors/_graph.py @@ -7,7 +7,7 @@ from ._base import KNeighborsMixin, RadiusNeighborsMixin from ._base import NeighborsBase from ._unsupervised import NearestNeighbors -from ..base import TransformerMixin +from ..base import TransformerMixin, _ClassNamePrefixFeaturesOutMixin from ..utils.validation import check_is_fitted @@ -223,7 +223,9 @@ def radius_neighbors_graph( return X.radius_neighbors_graph(query, radius, mode) -class KNeighborsTransformer(KNeighborsMixin, TransformerMixin, NeighborsBase): +class KNeighborsTransformer( + _ClassNamePrefixFeaturesOutMixin, KNeighborsMixin, TransformerMixin, NeighborsBase +): """Transform X into a (weighted) graph of k nearest neighbors. The transformed data is a sparse graph as returned by kneighbors_graph. @@ -389,7 +391,9 @@ def fit(self, X, y=None): self : KNeighborsTransformer The fitted k-nearest neighbors transformer. """ - return self._fit(X) + self._fit(X) + self._n_features_out = self.n_samples_fit_ + return self def transform(self, X): """Compute the (weighted) graph of Neighbors for points in X. @@ -445,7 +449,12 @@ def _more_tags(self): } -class RadiusNeighborsTransformer(RadiusNeighborsMixin, TransformerMixin, NeighborsBase): +class RadiusNeighborsTransformer( + _ClassNamePrefixFeaturesOutMixin, + RadiusNeighborsMixin, + TransformerMixin, + NeighborsBase, +): """Transform X into a (weighted) graph of neighbors nearer than a radius. The transformed data is a sparse graph as returned by @@ -614,7 +623,9 @@ def fit(self, X, y=None): self : RadiusNeighborsTransformer The fitted radius neighbors transformer. """ - return self._fit(X) + self._fit(X) + self._n_features_out = self.n_samples_fit_ + return self def transform(self, X): """Compute the (weighted) graph of Neighbors for points in X. diff --git a/sklearn/neighbors/_nca.py b/sklearn/neighbors/_nca.py index db1d8246e87df..13c92fdc872ba 100644 --- a/sklearn/neighbors/_nca.py +++ b/sklearn/neighbors/_nca.py @@ -15,7 +15,7 @@ from scipy.optimize import minimize from ..utils.extmath import softmax from ..metrics import pairwise_distances -from ..base import BaseEstimator, TransformerMixin +from ..base import BaseEstimator, TransformerMixin, _ClassNamePrefixFeaturesOutMixin from ..preprocessing import LabelEncoder from ..decomposition import PCA from ..utils.multiclass import check_classification_targets @@ -24,7 +24,9 @@ from ..exceptions import ConvergenceWarning -class NeighborhoodComponentsAnalysis(TransformerMixin, BaseEstimator): +class NeighborhoodComponentsAnalysis( + _ClassNamePrefixFeaturesOutMixin, TransformerMixin, BaseEstimator +): """Neighborhood Components Analysis. Neighborhood Component Analysis (NCA) is a machine learning algorithm for @@ -249,6 +251,7 @@ def fit(self, X, y): # Reshape the solution found by the optimizer self.components_ = opt_result.x.reshape(-1, X.shape[1]) + self._n_features_out = self.components_.shape[1] # Stop timer t_train = time.time() - t_train
diff --git a/sklearn/neighbors/tests/test_graph.py b/sklearn/neighbors/tests/test_graph.py index b51f40ac18e36..fb593485d17a8 100644 --- a/sklearn/neighbors/tests/test_graph.py +++ b/sklearn/neighbors/tests/test_graph.py @@ -1,8 +1,10 @@ import numpy as np +import pytest from sklearn.metrics import euclidean_distances from sklearn.neighbors import KNeighborsTransformer, RadiusNeighborsTransformer from sklearn.neighbors._base import _is_sorted_by_data +from sklearn.utils._testing import assert_array_equal def test_transformer_result(): @@ -77,3 +79,23 @@ def test_explicit_diagonal(): # Using transform on new data should not always have zero diagonal X2t = nnt.transform(X2) assert not _has_explicit_diagonal(X2t) + + [email protected]("Klass", [KNeighborsTransformer, RadiusNeighborsTransformer]) +def test_graph_feature_names_out(Klass): + """Check `get_feature_names_out` for transformers defined in `_graph.py`.""" + + n_samples_fit = 20 + n_features = 10 + rng = np.random.RandomState(42) + X = rng.randn(n_samples_fit, n_features) + + est = Klass().fit(X) + names_out = est.get_feature_names_out() + + class_name_lower = Klass.__name__.lower() + expected_names_out = np.array( + [f"{class_name_lower}{i}" for i in range(est.n_samples_fit_)], + dtype=object, + ) + assert_array_equal(names_out, expected_names_out) diff --git a/sklearn/neighbors/tests/test_nca.py b/sklearn/neighbors/tests/test_nca.py index f9d7e5503a2c8..ec0f71e4c1e9f 100644 --- a/sklearn/neighbors/tests/test_nca.py +++ b/sklearn/neighbors/tests/test_nca.py @@ -554,3 +554,20 @@ def test_parameters_valid_types(param, value): y = iris_target nca.fit(X, y) + + +def test_nca_feature_names_out(): + """Check `get_feature_names_out` for `NeighborhoodComponentsAnalysis`.""" + + X = iris_data + y = iris_target + + est = NeighborhoodComponentsAnalysis().fit(X, y) + names_out = est.get_feature_names_out() + + class_name_lower = est.__class__.__name__.lower() + expected_names_out = np.array( + [f"{class_name_lower}{i}" for i in range(est.components_.shape[1])], + dtype=object, + ) + assert_array_equal(names_out, expected_names_out) diff --git a/sklearn/tests/test_common.py b/sklearn/tests/test_common.py index a8178a4219485..de00fd713c5c7 100644 --- a/sklearn/tests/test_common.py +++ b/sklearn/tests/test_common.py @@ -386,7 +386,6 @@ def test_pandas_column_name_consistency(estimator): "kernel_approximation", "preprocessing", "manifold", - "neighbors", "neural_network", ]
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex c0f705a8ceef7..a9d4013b9b375 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -423,6 +423,11 @@ Changelog\n ndarray with `np.nan` when passed a `Float32` or `Float64` pandas extension\n array with `pd.NA`. :pr:`21278` by `Thomas Fan`_.\n \n+- |Enhancement| Adds :term:`get_feature_names_out` to\n+ :class:`neighbors.RadiusNeighborsTransformer`, :class:`neighbors.KNeighborsTransformer`\n+ and :class:`neighbors.NeighborhoodComponentsAnalysis`. :pr:`22212` by\n+ :user : `Meekail Zain <micky774>`.\n+\n - |Fix| :class:`neighbors.KernelDensity` now validates input parameters in `fit`\n instead of `__init__`. :pr:`21430` by :user:`Desislava Vasileva <DessyVV>` and\n :user:`Lucy Jimenez <LucyJimenez>`.\n" } ]
1.01
9816b35d05e139f1fcc1a5541a1398205280d75a
[ "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-5-5-11]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-7-5-11]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-7-7-5]", "sklearn/neighbors/tests/test_nca.py::test_params_validation", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-5-7-7]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-11-3-3]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-7-11-11]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-11-11-3]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-5-11-11]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-5-3-3]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-11-7-11]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-11-11-5]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-5-11-3]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-5-7-3]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-11-11-5]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-7-11-11]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-5-11-11]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-7-3-7]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-11-3-5]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-11-11-11]", "sklearn/neighbors/tests/test_nca.py::test_init_transformation", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-11-3-7]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-11-3-5]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-7-7-3]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-7-3-5]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-5-7-3]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-11-5-11]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-7-11-7]", "sklearn/neighbors/tests/test_nca.py::test_verbose[random]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-5-11-7]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-11-5-11]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-5-5-5]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-7-7-11]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-11-7-7]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-7-7-5]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-7-11-5]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-11-11-5]", "sklearn/neighbors/tests/test_nca.py::test_warm_start_validation", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-11-3-3]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-7-11-3]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-11-5-5]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-7-11-7]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-7-3-11]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-5-3-3]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-7-11-7]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-7-5-3]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-7-7-11]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-11-7-3]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-11-5-3]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-5-11-7]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-5-5-3]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-11-5-3]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-7-7-11]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-11-5-7]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-5-3-5]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-7-3-11]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-5-5-11]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-11-7-7]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-11-7-7]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-7-11-3]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-5-5-3]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-11-7-3]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-11-3-11]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-5-7-5]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-7-5-3]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-11-5-5]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-11-5-3]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-7-5-5]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-5-7-3]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-7-5-11]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-5-3-11]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-5-5-11]", "sklearn/neighbors/tests/test_nca.py::test_parameters_valid_types[n_components-value0]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-5-7-5]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-7-11-7]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-5-3-7]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-11-7-11]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-5-5-3]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-5-7-7]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-7-7-7]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-5-7-7]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-7-11-3]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-7-5-7]", "sklearn/neighbors/tests/test_graph.py::test_explicit_diagonal", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-11-5-11]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-5-3-5]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-5-5-3]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-5-11-3]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-7-3-7]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-11-3-11]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-11-5-7]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-5-3-7]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-11-11-11]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-7-5-3]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-7-11-11]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-5-5-11]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-7-7-7]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-11-7-5]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-5-11-11]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-11-5-3]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-7-5-5]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-5-11-5]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-11-7-5]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-5-5-5]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-11-3-5]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-5-3-11]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-11-11-7]", "sklearn/neighbors/tests/test_nca.py::test_one_class", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-5-5-7]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-11-7-3]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-11-11-7]", "sklearn/neighbors/tests/test_nca.py::test_expected_transformation_shape", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-7-11-11]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-11-11-11]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-5-5-7]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-5-11-7]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-11-11-5]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-5-5-5]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-5-3-3]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-7-3-3]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-5-3-7]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-11-5-7]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-11-7-5]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-11-11-3]", "sklearn/neighbors/tests/test_nca.py::test_verbose[identity]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-7-5-7]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-11-11-7]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-5-7-3]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-7-3-5]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-5-7-11]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-7-5-11]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-5-3-11]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-11-3-7]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-7-11-3]", "sklearn/neighbors/tests/test_nca.py::test_transformation_dimensions", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-7-7-5]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-7-3-5]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-7-11-5]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-7-5-7]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-7-5-5]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-5-3-5]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-5-11-5]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-5-11-11]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-7-11-5]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-7-11-5]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-11-7-7]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-11-3-7]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-5-11-5]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-11-5-7]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-11-5-5]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-5-7-5]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-11-7-11]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-7-5-11]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-7-7-3]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-11-3-7]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-7-3-3]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-11-3-11]", "sklearn/neighbors/tests/test_nca.py::test_parameters_valid_types[tol-value2]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-11-7-3]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-11-3-11]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-11-11-11]", "sklearn/neighbors/tests/test_graph.py::test_transformer_result", "sklearn/neighbors/tests/test_nca.py::test_warm_start_effectiveness", "sklearn/neighbors/tests/test_nca.py::test_n_components", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-11-3-3]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-7-7-7]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-7-3-11]", "sklearn/neighbors/tests/test_nca.py::test_simple_example", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-7-5-7]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-7-3-7]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-5-3-7]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-5-5-7]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-5-7-7]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-7-7-11]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-7-3-7]", "sklearn/neighbors/tests/test_nca.py::test_callback", "sklearn/neighbors/tests/test_nca.py::test_verbose[lda]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-11-5-11]", "sklearn/neighbors/tests/test_nca.py::test_parameters_valid_types[max_iter-value1]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-11-3-5]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-7-3-3]", "sklearn/neighbors/tests/test_nca.py::test_finite_differences", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-7-7-5]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-5-3-3]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-11-11-3]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-5-5-7]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-5-11-7]", "sklearn/neighbors/tests/test_nca.py::test_no_verbose", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-5-3-5]", "sklearn/neighbors/tests/test_nca.py::test_singleton_class", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-5-11-3]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-11-7-11]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-7-7-3]", "sklearn/neighbors/tests/test_nca.py::test_verbose[precomputed]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-7-5-3]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-5-7-11]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-11-11-3]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-5-11-3]", "sklearn/neighbors/tests/test_nca.py::test_verbose[pca]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-11-7-5]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-5-5-5]", "sklearn/neighbors/tests/test_nca.py::test_toy_example_collapse_points", "sklearn/neighbors/tests/test_nca.py::test_convergence_warning", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-5-7-11]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-7-3-3]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-11-3-3]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-5-7-11]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[7-7-3-11]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-11-11-7]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-5-3-11]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-7-7-7]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-5-7-5]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-5-11-5]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[11-11-5-5]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-7-5-5]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[5-7-3-5]", "sklearn/neighbors/tests/test_nca.py::test_auto_init[3-7-7-3]" ]
[ "sklearn/neighbors/tests/test_graph.py::test_graph_feature_names_out[KNeighborsTransformer]", "sklearn/neighbors/tests/test_graph.py::test_graph_feature_names_out[RadiusNeighborsTransformer]", "sklearn/neighbors/tests/test_nca.py::test_nca_feature_names_out" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex c0f705a8ceef7..a9d4013b9b375 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -423,6 +423,11 @@ Changelog\n ndarray with `np.nan` when passed a `Float32` or `Float64` pandas extension\n array with `pd.NA`. :pr:`<PRID>` by `<NAME>`_.\n \n+- |Enhancement| Adds :term:`get_feature_names_out` to\n+ :class:`neighbors.RadiusNeighborsTransformer`, :class:`neighbors.KNeighborsTransformer`\n+ and :class:`neighbors.NeighborhoodComponentsAnalysis`. :pr:`<PRID>` by\n+ :user : `Meekail Zain <micky774>`.\n+\n - |Fix| :class:`neighbors.KernelDensity` now validates input parameters in `fit`\n instead of `__init__`. :pr:`<PRID>` by :user:`<NAME>` and\n :user:`<NAME>`.\n" } ]
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index c0f705a8ceef7..a9d4013b9b375 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -423,6 +423,11 @@ Changelog ndarray with `np.nan` when passed a `Float32` or `Float64` pandas extension array with `pd.NA`. :pr:`<PRID>` by `<NAME>`_. +- |Enhancement| Adds :term:`get_feature_names_out` to + :class:`neighbors.RadiusNeighborsTransformer`, :class:`neighbors.KNeighborsTransformer` + and :class:`neighbors.NeighborhoodComponentsAnalysis`. :pr:`<PRID>` by + :user : `Meekail Zain <micky774>`. + - |Fix| :class:`neighbors.KernelDensity` now validates input parameters in `fit` instead of `__init__`. :pr:`<PRID>` by :user:`<NAME>` and :user:`<NAME>`.
scikit-learn/scikit-learn
scikit-learn__scikit-learn-21316
https://github.com/scikit-learn/scikit-learn/pull/21316
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index c4f16f4404963..c34c9779e12ec 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -113,6 +113,10 @@ Changelog :pr:`20880` by :user:`Guillaume Lemaitre <glemaitre>` and :user:`András Simon <simonandras>`. +- |Enhancement| :func:`utils.estimator_html_repr` shows a more helpful error + message when running in a jupyter notebook that is not trusted. :pr:`21316` + by `Thomas Fan`_. + Code and Documentation Contributors ----------------------------------- diff --git a/sklearn/utils/_estimator_html_repr.py b/sklearn/utils/_estimator_html_repr.py index b2d38b9e97ab3..1f5c339c12771 100644 --- a/sklearn/utils/_estimator_html_repr.py +++ b/sklearn/utils/_estimator_html_repr.py @@ -309,6 +309,9 @@ def _write_estimator_html( display: inline-block; position: relative; } +#$id div.sk-text-repr-fallback { + display: none; +} """.replace( " ", "" ).replace( @@ -335,16 +338,33 @@ def estimator_html_repr(estimator): container_id = "sk-" + str(uuid.uuid4()) style_template = Template(_STYLE) style_with_id = style_template.substitute(id=container_id) + estimator_str = str(estimator) + + # The fallback message is shown by default and loading the CSS sets + # div.sk-text-repr-fallback to display: none to hide the fallback message. + # + # If the notebook is trusted, the CSS is loaded which hides the fallback + # message. If the notebook is not trusted, then the CSS is not loaded and the + # fallback message is shown by default. + # + # The reverse logic applies to HTML repr div.sk-container. + # div.sk-container is hidden by default and the loading the CSS displays it. + fallback_msg = ( + "Please rerun this cell to show the HTML repr or trust the notebook." + ) out.write( f"<style>{style_with_id}</style>" f'<div id="{container_id}" class"sk-top-container">' - '<div class="sk-container">' + '<div class="sk-text-repr-fallback">' + f"<pre>{html.escape(estimator_str)}</pre><b>{fallback_msg}</b>" + "</div>" + '<div class="sk-container" hidden>' ) _write_estimator_html( out, estimator, estimator.__class__.__name__, - str(estimator), + estimator_str, first_call=True, ) out.write("</div></div>")
diff --git a/sklearn/utils/tests/test_estimator_html_repr.py b/sklearn/utils/tests/test_estimator_html_repr.py index f22c03f20bdd7..9d474ad10fe10 100644 --- a/sklearn/utils/tests/test_estimator_html_repr.py +++ b/sklearn/utils/tests/test_estimator_html_repr.py @@ -1,4 +1,5 @@ from contextlib import closing +import html from io import StringIO import pytest @@ -278,3 +279,14 @@ def test_one_estimator_print_change_only(print_changed_only): pca_repr = str(pca) html_output = estimator_html_repr(pca) assert pca_repr in html_output + + +def test_fallback_exists(): + """Check that repr fallback is in the HTML.""" + pca = PCA(n_components=10) + html_output = estimator_html_repr(pca) + + assert ( + f'<div class="sk-text-repr-fallback"><pre>{html.escape(str(pca))}' + in html_output + )
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex c4f16f4404963..c34c9779e12ec 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -113,6 +113,10 @@ Changelog\n :pr:`20880` by :user:`Guillaume Lemaitre <glemaitre>`\n and :user:`András Simon <simonandras>`.\n \n+- |Enhancement| :func:`utils.estimator_html_repr` shows a more helpful error\n+ message when running in a jupyter notebook that is not trusted. :pr:`21316`\n+ by `Thomas Fan`_.\n+\n Code and Documentation Contributors\n -----------------------------------\n \n" } ]
1.01
a343963d961225be25468ca64b54896dcba48e87
[ "sklearn/utils/tests/test_estimator_html_repr.py::test_stacking_regressor[None]", "sklearn/utils/tests/test_estimator_html_repr.py::test_get_visual_block_single_str_none[passthrough]", "sklearn/utils/tests/test_estimator_html_repr.py::test_write_label_html[True]", "sklearn/utils/tests/test_estimator_html_repr.py::test_get_visual_block_pipeline", "sklearn/utils/tests/test_estimator_html_repr.py::test_stacking_classsifer[None]", "sklearn/utils/tests/test_estimator_html_repr.py::test_write_label_html[False]", "sklearn/utils/tests/test_estimator_html_repr.py::test_one_estimator_print_change_only[False]", "sklearn/utils/tests/test_estimator_html_repr.py::test_get_visual_block_voting", "sklearn/utils/tests/test_estimator_html_repr.py::test_duck_typing_nested_estimator", "sklearn/utils/tests/test_estimator_html_repr.py::test_birch_duck_typing_meta", "sklearn/utils/tests/test_estimator_html_repr.py::test_estimator_html_repr_pipeline", "sklearn/utils/tests/test_estimator_html_repr.py::test_one_estimator_print_change_only[True]", "sklearn/utils/tests/test_estimator_html_repr.py::test_stacking_classsifer[final_estimator1]", "sklearn/utils/tests/test_estimator_html_repr.py::test_get_visual_block_single_str_none[None]", "sklearn/utils/tests/test_estimator_html_repr.py::test_get_visual_block_single_str_none[drop]", "sklearn/utils/tests/test_estimator_html_repr.py::test_stacking_regressor[final_estimator1]", "sklearn/utils/tests/test_estimator_html_repr.py::test_get_visual_block_single_estimator", "sklearn/utils/tests/test_estimator_html_repr.py::test_get_visual_block_feature_union", "sklearn/utils/tests/test_estimator_html_repr.py::test_get_visual_block_column_transformer", "sklearn/utils/tests/test_estimator_html_repr.py::test_ovo_classifier_duck_typing_meta" ]
[ "sklearn/utils/tests/test_estimator_html_repr.py::test_fallback_exists" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex c4f16f4404963..c34c9779e12ec 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -113,6 +113,10 @@ Changelog\n :pr:`<PRID>` by :user:`<NAME>`\n and :user:`<NAME>`.\n \n+- |Enhancement| :func:`utils.estimator_html_repr` shows a more helpful error\n+ message when running in a jupyter notebook that is not trusted. :pr:`<PRID>`\n+ by `<NAME>`_.\n+\n Code and Documentation Contributors\n -----------------------------------\n \n" } ]
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index c4f16f4404963..c34c9779e12ec 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -113,6 +113,10 @@ Changelog :pr:`<PRID>` by :user:`<NAME>` and :user:`<NAME>`. +- |Enhancement| :func:`utils.estimator_html_repr` shows a more helpful error + message when running in a jupyter notebook that is not trusted. :pr:`<PRID>` + by `<NAME>`_. + Code and Documentation Contributors -----------------------------------
scikit-learn/scikit-learn
scikit-learn__scikit-learn-17443
https://github.com/scikit-learn/scikit-learn/pull/17443
diff --git a/doc/modules/calibration.rst b/doc/modules/calibration.rst index d0a9737dac612..1fcd1d501d100 100644 --- a/doc/modules/calibration.rst +++ b/doc/modules/calibration.rst @@ -30,11 +30,25 @@ approximately 80% actually belong to the positive class. Calibration curves ------------------ -The following plot compares how well the probabilistic predictions of -different classifiers are calibrated, using :func:`calibration_curve`. +Calibration curves (also known as reliability diagrams) compare how well the +probabilistic predictions of a binary classifier are calibrated. It plots +the true frequency of the positive label against its predicted probability, +for binned predictions. The x axis represents the average predicted probability in each bin. The y axis is the *fraction of positives*, i.e. the proportion of samples whose -class is the positive class (in each bin). +class is the positive class (in each bin). The top calibration curve plot +is created with :func:`CalibrationDisplay.from_estimators`, which uses +:func:`calibration_curve` to calculate the per bin average predicted +probabilities and fraction of positives. +:func:`CalibrationDisplay.from_estimator` +takes as input a fitted classifier, which is used to calculate the predicted +probabilities. The classifier thus must have :term:`predict_proba` method. For +the few classifiers that do not have a :term:`predict_proba` method, it is +possible to use :class:`CalibratedClassifierCV` to calibrate the classifier +outputs to probabilities. + +The bottom histogram gives some insight into the behavior of each classifier +by showing the number of samples in each predicted probability bin. .. figure:: ../auto_examples/calibration/images/sphx_glr_plot_compare_calibration_001.png :target: ../auto_examples/calibration/plot_compare_calibration.html @@ -161,6 +175,8 @@ mean a better calibrated model. :class:`CalibratedClassifierCV` supports the use of two 'calibration' regressors: 'sigmoid' and 'isotonic'. +.. _sigmoid_regressor: + Sigmoid ^^^^^^^ diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst index 3edd8adee8191..3848a189c35d4 100644 --- a/doc/modules/classes.rst +++ b/doc/modules/classes.rst @@ -1123,7 +1123,7 @@ See the :ref:`visualizations` section of the user guide for further details. metrics.DetCurveDisplay metrics.PrecisionRecallDisplay metrics.RocCurveDisplay - + calibration.CalibrationDisplay .. _mixture_ref: diff --git a/doc/visualizations.rst b/doc/visualizations.rst index a2d40408b403f..65612b2787d84 100644 --- a/doc/visualizations.rst +++ b/doc/visualizations.rst @@ -65,6 +65,7 @@ values of the curves. * :ref:`sphx_glr_auto_examples_miscellaneous_plot_roc_curve_visualization_api.py` * :ref:`sphx_glr_auto_examples_miscellaneous_plot_partial_dependence_visualization_api.py` * :ref:`sphx_glr_auto_examples_miscellaneous_plot_display_object_visualization.py` + * :ref:`sphx_glr_auto_examples_calibration_plot_compare_calibration.py` Available Plotting Utilities ============================ @@ -90,6 +91,7 @@ Display Objects .. autosummary:: + calibration.CalibrationDisplay inspection.PartialDependenceDisplay metrics.ConfusionMatrixDisplay metrics.DetCurveDisplay diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index d9f63cc62add4..001c3350fb056 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -152,6 +152,9 @@ Changelog :class:`calibration.CalibratedClassifierCV` can now properly be used on prefitted pipelines. :pr:`19641` by :user:`Alek Lefebvre <AlekLefebvre>`. +- |Feature| :func:`calibration.CalibrationDisplay` added to plot + calibration curves. :pr:`17443` by :user:`Lucy Liu <lucyleeow>`. + - |Fix| Fixed an error when using a ::class:`ensemble.VotingClassifier` as `base_estimator` in ::class:`calibration.CalibratedClassifierCV`. :pr:`20087` by :user:`Clément Fauchereau <clement-f>`. diff --git a/examples/calibration/plot_calibration_curve.py b/examples/calibration/plot_calibration_curve.py index b397bb79a2ba2..d4bfda5a3a55d 100644 --- a/examples/calibration/plot_calibration_curve.py +++ b/examples/calibration/plot_calibration_curve.py @@ -5,131 +5,305 @@ When performing classification one often wants to predict not only the class label, but also the associated probability. This probability gives some -kind of confidence on the prediction. This example demonstrates how to display -how well calibrated the predicted probabilities are and how to calibrate an -uncalibrated classifier. - -The experiment is performed on an artificial dataset for binary classification -with 100,000 samples (1,000 of them are used for model fitting) with 20 -features. Of the 20 features, only 2 are informative and 10 are redundant. The -first figure shows the estimated probabilities obtained with logistic -regression, Gaussian naive Bayes, and Gaussian naive Bayes with both isotonic -calibration and sigmoid calibration. The calibration performance is evaluated -with Brier score, reported in the legend (the smaller the better). One can -observe here that logistic regression is well calibrated while raw Gaussian -naive Bayes performs very badly. This is because of the redundant features -which violate the assumption of feature-independence and result in an overly -confident classifier, which is indicated by the typical transposed-sigmoid -curve. - -Calibration of the probabilities of Gaussian naive Bayes with isotonic -regression can fix this issue as can be seen from the nearly diagonal -calibration curve. Sigmoid calibration also improves the brier score slightly, -albeit not as strongly as the non-parametric isotonic regression. This can be -attributed to the fact that we have plenty of calibration data such that the -greater flexibility of the non-parametric model can be exploited. - -The second figure shows the calibration curve of a linear support-vector -classifier (LinearSVC). LinearSVC shows the opposite behavior as Gaussian -naive Bayes: the calibration curve has a sigmoid curve, which is typical for -an under-confident classifier. In the case of LinearSVC, this is caused by the -margin property of the hinge loss, which lets the model focus on hard samples -that are close to the decision boundary (the support vectors). - -Both kinds of calibration can fix this issue and yield nearly identical -results. This shows that sigmoid calibration can deal with situations where -the calibration curve of the base classifier is sigmoid (e.g., for LinearSVC) -but not where it is transposed-sigmoid (e.g., Gaussian naive Bayes). +kind of confidence on the prediction. This example demonstrates how to +visualize how well calibrated the predicted probabilities are using calibration +curves, also known as reliability diagrams. Calibration of an uncalibrated +classifier will also be demonstrated. """ print(__doc__) +# %% # Author: Alexandre Gramfort <[email protected]> # Jan Hendrik Metzen <[email protected]> -# License: BSD Style. +# License: BSD 3 clause. +# +# Dataset +# ------- +# +# We will use a synthetic binary classification dataset with 100,000 samples +# and 20 features. Of the 20 features, only 2 are informative, 10 are +# redundant (random combinations of the informative features) and the +# remaining 8 are uninformative (random numbers). Of the 100,000 samples, 1,000 +# will be used for model fitting and the rest for testing. + +from sklearn.datasets import make_classification +from sklearn.model_selection import train_test_split + +X, y = make_classification(n_samples=100_000, n_features=20, n_informative=2, + n_redundant=10, random_state=42) + +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.99, + random_state=42) + +# %% +# Calibration curves +# ------------------ +# +# Gaussian Naive Bayes +# ^^^^^^^^^^^^^^^^^^^^ +# +# First, we will compare: +# +# * :class:`~sklearn.linear_model.LogisticRegression` (used as baseline +# since very often, properly regularized logistic regression is well +# calibrated by default thanks to the use of the log-loss) +# * Uncalibrated :class:`~sklearn.naive_bayes.GaussianNB` +# * :class:`~sklearn.naive_bayes.GaussianNB` with isotonic and sigmoid +# calibration (see :ref:`User Guide <calibration>`) +# +# Calibration curves for all 4 conditions are plotted below, with the average +# predicted probability for each bin on the x-axis and the fraction of positive +# classes in each bin on the y-axis. import matplotlib.pyplot as plt +from matplotlib.gridspec import GridSpec -from sklearn import datasets -from sklearn.naive_bayes import GaussianNB -from sklearn.svm import LinearSVC +from sklearn.calibration import CalibratedClassifierCV, CalibrationDisplay from sklearn.linear_model import LogisticRegression -from sklearn.metrics import (brier_score_loss, precision_score, recall_score, - f1_score) -from sklearn.calibration import CalibratedClassifierCV, calibration_curve -from sklearn.model_selection import train_test_split +from sklearn.naive_bayes import GaussianNB +lr = LogisticRegression(C=1.) +gnb = GaussianNB() +gnb_isotonic = CalibratedClassifierCV(gnb, cv=2, method='isotonic') +gnb_sigmoid = CalibratedClassifierCV(gnb, cv=2, method='sigmoid') -# Create dataset of classification task with many redundant and few -# informative features -X, y = datasets.make_classification(n_samples=100000, n_features=20, - n_informative=2, n_redundant=10, - random_state=42) +clf_list = [(lr, 'Logistic'), + (gnb, 'Naive Bayes'), + (gnb_isotonic, 'Naive Bayes + Isotonic'), + (gnb_sigmoid, 'Naive Bayes + Sigmoid')] -X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.99, - random_state=42) +# %% +fig = plt.figure(figsize=(10, 10)) +gs = GridSpec(4, 2) +colors = plt.cm.get_cmap('Dark2') + +ax_calibration_curve = fig.add_subplot(gs[:2, :2]) +calibration_displays = {} +for i, (clf, name) in enumerate(clf_list): + clf.fit(X_train, y_train) + display = CalibrationDisplay.from_estimator( + clf, X_test, y_test, n_bins=10, name=name, ax=ax_calibration_curve, + color=colors(i) + ) + calibration_displays[name] = display + +ax_calibration_curve.grid() +ax_calibration_curve.set_title('Calibration plots (Naive Bayes)') + +# Add histogram +grid_positions = [(2, 0), (2, 1), (3, 0), (3, 1)] +for i, (_, name) in enumerate(clf_list): + row, col = grid_positions[i] + ax = fig.add_subplot(gs[row, col]) + + ax.hist( + calibration_displays[name].y_prob, range=(0, 1), bins=10, label=name, + color=colors(i) + ) + ax.set(title=name, xlabel="Mean predicted probability", ylabel="Count") + +plt.tight_layout() +plt.show() + +# %% +# Uncalibrated :class:`~sklearn.naive_bayes.GaussianNB` is poorly calibrated +# because of +# the redundant features which violate the assumption of feature-independence +# and result in an overly confident classifier, which is indicated by the +# typical transposed-sigmoid curve. Calibration of the probabilities of +# :class:`~sklearn.naive_bayes.GaussianNB` with :ref:`isotonic` can fix +# this issue as can be seen from the nearly diagonal calibration curve. +# :ref:sigmoid regression `<sigmoid_regressor>` also improves calibration +# slightly, +# albeit not as strongly as the non-parametric isotonic regression. This can be +# attributed to the fact that we have plenty of calibration data such that the +# greater flexibility of the non-parametric model can be exploited. +# +# Below we will make a quantitative analysis considering several classification +# metrics: :ref:`brier_score_loss`, :ref:`log_loss`, +# :ref:`precision, recall, F1 score <precision_recall_f_measure_metrics>` and +# :ref:`ROC AUC <roc_metrics>`. + +from collections import defaultdict + +import pandas as pd + +from sklearn.metrics import (precision_score, recall_score, f1_score, + brier_score_loss, log_loss, roc_auc_score) + +scores = defaultdict(list) +for i, (clf, name) in enumerate(clf_list): + clf.fit(X_train, y_train) + y_prob = clf.predict_proba(X_test) + y_pred = clf.predict(X_test) + scores["Classifier"].append(name) + + for metric in [brier_score_loss, log_loss]: + score_name = metric.__name__.replace("_", " ").replace("score", "").capitalize() + scores[score_name].append(metric(y_test, y_prob[:, 1])) + + for metric in [precision_score, recall_score, f1_score, roc_auc_score]: + score_name = metric.__name__.replace("_", " ").replace("score", "").capitalize() + scores[score_name].append(metric(y_test, y_pred)) + + score_df = pd.DataFrame(scores).set_index("Classifier") + score_df.round(decimals=3) +score_df -def plot_calibration_curve(est, name, fig_index): - """Plot calibration curve for est w/o and with calibration. """ - # Calibrated with isotonic calibration - isotonic = CalibratedClassifierCV(est, cv=2, method='isotonic') +# %% +# Notice that although calibration improves the :ref:`brier_score_loss` (a +# metric composed +# of calibration term and refinement term) and :ref:`log_loss`, it does not +# significantly alter the prediction accuracy measures (precision, recall and +# F1 score). +# This is because calibration should not significantly change prediction +# probabilities at the location of the decision threshold (at x = 0.5 on the +# graph). Calibration should however, make the predicted probabilities more +# accurate and thus more useful for making allocation decisions under +# uncertainty. +# Further, ROC AUC, should not change at all because calibration is a +# monotonic transformation. Indeed, no rank metrics are affected by +# calibration. +# +# Linear support vector classifier +# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +# Next, we will compare: +# +# * :class:`~sklearn.linear_model.LogisticRegression` (baseline) +# * Uncalibrated :class:`~sklearn.svm.LinearSVC`. Since SVC does not output +# probabilities by default, we naively scale the output of the +# :term:`decision_function` into [0, 1] by applying min-max scaling. +# * :class:`~sklearn.svm.LinearSVC` with isotonic and sigmoid +# calibration (see :ref:`User Guide <calibration>`) - # Calibrated with sigmoid calibration - sigmoid = CalibratedClassifierCV(est, cv=2, method='sigmoid') +import numpy as np + +from sklearn.svm import LinearSVC - # Logistic regression with no calibration as baseline - lr = LogisticRegression(C=1.) - fig = plt.figure(fig_index, figsize=(10, 10)) - ax1 = plt.subplot2grid((3, 1), (0, 0), rowspan=2, fig=fig) - ax2 = plt.subplot2grid((3, 1), (2, 0), fig=fig) +class NaivelyCalibratedLinearSVC(LinearSVC): + """LinearSVC with `predict_proba` method that naively scales + `decision_function` output for binary classification.""" - ax1.plot([0, 1], [0, 1], "k:", label="Perfectly calibrated") - for clf, name in [(lr, 'Logistic'), - (est, name), - (isotonic, name + ' + Isotonic'), - (sigmoid, name + ' + Sigmoid')]: - clf.fit(X_train, y_train) - y_pred = clf.predict(X_test) - if hasattr(clf, "predict_proba"): - prob_pos = clf.predict_proba(X_test)[:, 1] - else: # use decision function - prob_pos = clf.decision_function(X_test) - prob_pos = \ - (prob_pos - prob_pos.min()) / (prob_pos.max() - prob_pos.min()) + def fit(self, X, y): + super().fit(X, y) + df = self.decision_function(X) + self.df_min_ = df.min() + self.df_max_ = df.max() - clf_score = brier_score_loss(y_test, prob_pos, pos_label=y.max()) - print("%s:" % name) - print("\tBrier: %1.3f" % (clf_score)) - print("\tPrecision: %1.3f" % precision_score(y_test, y_pred)) - print("\tRecall: %1.3f" % recall_score(y_test, y_pred)) - print("\tF1: %1.3f\n" % f1_score(y_test, y_pred)) + def predict_proba(self, X): + """Min-max scale output of `decision_function` to [0, 1].""" + df = self.decision_function(X) + calibrated_df = (df - self.df_min_) / (self.df_max_ - self.df_min_) + proba_pos_class = np.clip(calibrated_df, 0, 1) + proba_neg_class = 1 - proba_pos_class + proba = np.c_[proba_neg_class, proba_pos_class] + return proba - fraction_of_positives, mean_predicted_value = \ - calibration_curve(y_test, prob_pos, n_bins=10) - ax1.plot(mean_predicted_value, fraction_of_positives, "s-", - label="%s (%1.3f)" % (name, clf_score)) +# %% - ax2.hist(prob_pos, range=(0, 1), bins=10, label=name, - histtype="step", lw=2) +lr = LogisticRegression(C=1.) +svc = NaivelyCalibratedLinearSVC(max_iter=10_000) +svc_isotonic = CalibratedClassifierCV(svc, cv=2, method='isotonic') +svc_sigmoid = CalibratedClassifierCV(svc, cv=2, method='sigmoid') - ax1.set_ylabel("Fraction of positives") - ax1.set_ylim([-0.05, 1.05]) - ax1.legend(loc="lower right") - ax1.set_title('Calibration plots (reliability curve)') +clf_list = [(lr, 'Logistic'), + (svc, 'SVC'), + (svc_isotonic, 'SVC + Isotonic'), + (svc_sigmoid, 'SVC + Sigmoid')] - ax2.set_xlabel("Mean predicted value") - ax2.set_ylabel("Count") - ax2.legend(loc="upper center", ncol=2) +# %% +fig = plt.figure(figsize=(10, 10)) +gs = GridSpec(4, 2) - plt.tight_layout() +ax_calibration_curve = fig.add_subplot(gs[:2, :2]) +calibration_displays = {} +for i, (clf, name) in enumerate(clf_list): + clf.fit(X_train, y_train) + display = CalibrationDisplay.from_estimator( + clf, X_test, y_test, n_bins=10, name=name, ax=ax_calibration_curve, + color=colors(i) + ) + calibration_displays[name] = display +ax_calibration_curve.grid() +ax_calibration_curve.set_title('Calibration plots (SVC)') -# Plot calibration curve for Gaussian Naive Bayes -plot_calibration_curve(GaussianNB(), "Naive Bayes", 1) +# Add histogram +grid_positions = [(2, 0), (2, 1), (3, 0), (3, 1)] +for i, (_, name) in enumerate(clf_list): + row, col = grid_positions[i] + ax = fig.add_subplot(gs[row, col]) -# Plot calibration curve for Linear SVC -plot_calibration_curve(LinearSVC(max_iter=10000), "SVC", 2) + ax.hist( + calibration_displays[name].y_prob, range=(0, 1), bins=10, label=name, + color=colors(i) + ) + ax.set(title=name, xlabel="Mean predicted probability", ylabel="Count") +plt.tight_layout() plt.show() + +# %% +# :class:`~sklearn.svm.LinearSVC` shows the opposite +# behavior to :class:`~sklearn.naive_bayes.GaussianNB`; the calibration +# curve has a sigmoid shape, which is typical for an under-confident +# classifier. In the case of :class:`~sklearn.svm.LinearSVC`, this is caused +# by the margin property of the hinge loss, which focuses on samples that are +# close to the decision boundary (support vectors). Samples that are far +# away from the decision boundary do not impact the hinge loss. It thus makes +# sense that :class:`~sklearn.svm.LinearSVC` does not try to separate samples +# in the high confidence region regions. This leads to flatter calibration +# curves near 0 and 1 and is empirically shown with a variety of datasets +# in Niculescu-Mizil & Caruana [1]_. +# +# Both kinds of calibration (sigmoid and isotonic) can fix this issue and +# yield similar results. +# +# As before, we show the :ref:`brier_score_loss`, :ref:`log_loss`, +# :ref:`precision, recall, F1 score <precision_recall_f_measure_metrics>` and +# :ref:`ROC AUC <roc_metrics>`. + +scores = defaultdict(list) +for i, (clf, name) in enumerate(clf_list): + clf.fit(X_train, y_train) + y_prob = clf.predict_proba(X_test) + y_pred = clf.predict(X_test) + scores["Classifier"].append(name) + + for metric in [brier_score_loss, log_loss]: + score_name = metric.__name__.replace("_", " ").replace("score", "").capitalize() + scores[score_name].append(metric(y_test, y_prob[:, 1])) + + for metric in [precision_score, recall_score, f1_score, roc_auc_score]: + score_name = metric.__name__.replace("_", " ").replace("score", "").capitalize() + scores[score_name].append(metric(y_test, y_pred)) + + score_df = pd.DataFrame(scores).set_index("Classifier") + score_df.round(decimals=3) + +score_df + +# %% +# As with :class:`~sklearn.naive_bayes.GaussianNB` above, calibration improves +# both :ref:`brier_score_loss` and :ref:`log_loss` but does not alter the +# prediction accuracy measures (precision, recall and F1 score) much. +# +# Summary +# ------- +# +# Parametric sigmoid calibration can deal with situations where the calibration +# curve of the base classifier is sigmoid (e.g., for +# :class:`~sklearn.svm.LinearSVC`) but not where it is transposed-sigmoid +# (e.g., :class:`~sklearn.naive_bayes.GaussianNB`). Non-parametric +# isotonic calibration can deal with both situations but may require more +# data to produce good results. +# +# References +# ---------- +# +# .. [1] `Predicting Good Probabilities with Supervised Learning +# <https://dl.acm.org/doi/pdf/10.1145/1102351.1102430>`_, +# A. Niculescu-Mizil & R. Caruana, ICML 2005 diff --git a/examples/calibration/plot_compare_calibration.py b/examples/calibration/plot_compare_calibration.py index a8599aecc16af..7ee4eaf4da7df 100644 --- a/examples/calibration/plot_compare_calibration.py +++ b/examples/calibration/plot_compare_calibration.py @@ -4,119 +4,192 @@ ======================================== Well calibrated classifiers are probabilistic classifiers for which the output -of the predict_proba method can be directly interpreted as a confidence level. -For instance a well calibrated (binary) classifier should classify the samples -such that among the samples to which it gave a predict_proba value close to -0.8, approx. 80% actually belong to the positive class. - -LogisticRegression returns well calibrated predictions as it directly -optimizes log-loss. In contrast, the other methods return biased probabilities, -with different biases per method: - -* GaussianNaiveBayes tends to push probabilities to 0 or 1 (note the counts in - the histograms). This is mainly because it makes the assumption that features - are conditionally independent given the class, which is not the case in this - dataset which contains 2 redundant features. - -* RandomForestClassifier shows the opposite behavior: the histograms show - peaks at approx. 0.2 and 0.9 probability, while probabilities close to 0 or 1 - are very rare. An explanation for this is given by Niculescu-Mizil and Caruana - [1]_: "Methods such as bagging and random forests that average predictions - from a base set of models can have difficulty making predictions near 0 and 1 - because variance in the underlying base models will bias predictions that - should be near zero or one away from these values. Because predictions are - restricted to the interval [0,1], errors caused by variance tend to be one- - sided near zero and one. For example, if a model should predict p = 0 for a - case, the only way bagging can achieve this is if all bagged trees predict - zero. If we add noise to the trees that bagging is averaging over, this noise - will cause some trees to predict values larger than 0 for this case, thus - moving the average prediction of the bagged ensemble away from 0. We observe - this effect most strongly with random forests because the base-level trees - trained with random forests have relatively high variance due to feature - subsetting." As a result, the calibration curve shows a characteristic - sigmoid shape, indicating that the classifier could trust its "intuition" - more and return probabilities closer to 0 or 1 typically. - -* Support Vector Classification (SVC) shows an even more sigmoid curve as - the RandomForestClassifier, which is typical for maximum-margin methods - (compare Niculescu-Mizil and Caruana [1]_), which focus on hard samples - that are close to the decision boundary (the support vectors). - -.. topic:: References: - - .. [1] Predicting Good Probabilities with Supervised Learning, - A. Niculescu-Mizil & R. Caruana, ICML 2005 +of :term:`predict_proba` can be directly interpreted as a confidence level. +For instance, a well calibrated (binary) classifier should classify the samples +such that for the samples to which it gave a :term:`predict_proba` value close +to 0.8, approximately 80% actually belong to the positive class. + +In this example we will compare the calibration of four different +models: :ref:`Logistic_regression`, :ref:`gaussian_naive_bayes`, +:ref:`Random Forest Classifier <forest>` and :ref:`Linear SVM +<svm_classification>`. """ -print(__doc__) +# %% # Author: Jan Hendrik Metzen <[email protected]> -# License: BSD Style. +# License: BSD 3 clause. +# +# Dataset +# ------- +# +# We will use a synthetic binary classification dataset with 100,000 samples +# and 20 features. Of the 20 features, only 2 are informative, 2 are +# redundant (random combinations of the informative features) and the +# remaining 16 are uninformative (random numbers). Of the 100,000 samples, +# 100 will be used for model fitting and the remaining for testing. + +from sklearn.datasets import make_classification +from sklearn.model_selection import train_test_split + +X, y = make_classification( + n_samples=100_000, n_features=20, n_informative=2, n_redundant=2, + random_state=42 +) -import numpy as np -np.random.seed(0) +train_samples = 100 # Samples used for training the models +X_train, X_test, y_train, y_test = train_test_split( + X, y, shuffle=False, test_size=100_000 - train_samples, +) + +# %% +# Calibration curves +# ------------------ +# +# Below, we train each of the four models with the small training dataset, then +# plot calibration curves (also known as reliability diagrams) using +# predicted probabilities of the test dataset. Calibration curves are created +# by binning predicted probabilities, then plotting the mean predicted +# probability in each bin against the observed frequency ('fraction of +# positives'). Below the calibration curve, we plot a histogram showing +# the distribution of the predicted probabilities or more specifically, +# the number of samples in each predicted probability bin. -import matplotlib.pyplot as plt +import numpy as np -from sklearn import datasets -from sklearn.naive_bayes import GaussianNB -from sklearn.linear_model import LogisticRegression -from sklearn.ensemble import RandomForestClassifier from sklearn.svm import LinearSVC -from sklearn.calibration import calibration_curve -X, y = datasets.make_classification(n_samples=100000, n_features=20, - n_informative=2, n_redundant=2) -train_samples = 100 # Samples used for training the models +class NaivelyCalibratedLinearSVC(LinearSVC): + """LinearSVC with `predict_proba` method that naively scales + `decision_function` output.""" + + def fit(self, X, y): + super().fit(X, y) + df = self.decision_function(X) + self.df_min_ = df.min() + self.df_max_ = df.max() -X_train = X[:train_samples] -X_test = X[train_samples:] -y_train = y[:train_samples] -y_test = y[train_samples:] + def predict_proba(self, X): + """Min-max scale output of `decision_function` to [0,1].""" + df = self.decision_function(X) + calibrated_df = (df - self.df_min_) / (self.df_max_ - self.df_min_) + proba_pos_class = np.clip(calibrated_df, 0, 1) + proba_neg_class = 1 - proba_pos_class + proba = np.c_[proba_neg_class, proba_pos_class] + return proba + + +# %% + +from sklearn.calibration import CalibrationDisplay +from sklearn.ensemble import RandomForestClassifier +from sklearn.linear_model import LogisticRegression +from sklearn.naive_bayes import GaussianNB # Create classifiers lr = LogisticRegression() gnb = GaussianNB() -svc = LinearSVC(C=1.0) +svc = NaivelyCalibratedLinearSVC(C=1.0) rfc = RandomForestClassifier() +clf_list = [(lr, 'Logistic'), + (gnb, 'Naive Bayes'), + (svc, 'SVC'), + (rfc, 'Random forest')] + +# %% -# ############################################################################# -# Plot calibration plots +import matplotlib.pyplot as plt +from matplotlib.gridspec import GridSpec -plt.figure(figsize=(10, 10)) -ax1 = plt.subplot2grid((3, 1), (0, 0), rowspan=2) -ax2 = plt.subplot2grid((3, 1), (2, 0)) +fig = plt.figure(figsize=(10, 10)) +gs = GridSpec(4, 2) +colors = plt.cm.get_cmap('Dark2') -ax1.plot([0, 1], [0, 1], "k:", label="Perfectly calibrated") -for clf, name in [(lr, 'Logistic'), - (gnb, 'Naive Bayes'), - (svc, 'Support Vector Classification'), - (rfc, 'Random Forest')]: +ax_calibration_curve = fig.add_subplot(gs[:2, :2]) +calibration_displays = {} +for i, (clf, name) in enumerate(clf_list): clf.fit(X_train, y_train) - if hasattr(clf, "predict_proba"): - prob_pos = clf.predict_proba(X_test)[:, 1] - else: # use decision function - prob_pos = clf.decision_function(X_test) - prob_pos = \ - (prob_pos - prob_pos.min()) / (prob_pos.max() - prob_pos.min()) - fraction_of_positives, mean_predicted_value = \ - calibration_curve(y_test, prob_pos, n_bins=10) - - ax1.plot(mean_predicted_value, fraction_of_positives, "s-", - label="%s" % (name, )) - - ax2.hist(prob_pos, range=(0, 1), bins=10, label=name, - histtype="step", lw=2) - -ax1.set_ylabel("Fraction of positives") -ax1.set_ylim([-0.05, 1.05]) -ax1.legend(loc="lower right") -ax1.set_title('Calibration plots (reliability curve)') - -ax2.set_xlabel("Mean predicted value") -ax2.set_ylabel("Count") -ax2.legend(loc="upper center", ncol=2) + display = CalibrationDisplay.from_estimator( + clf, X_test, y_test, n_bins=10, name=name, ax=ax_calibration_curve, + color=colors(i) + ) + calibration_displays[name] = display + +ax_calibration_curve.grid() +ax_calibration_curve.set_title('Calibration plots') + +# Add histogram +grid_positions = [(2, 0), (2, 1), (3, 0), (3, 1)] +for i, (_, name) in enumerate(clf_list): + row, col = grid_positions[i] + ax = fig.add_subplot(gs[row, col]) + + ax.hist( + calibration_displays[name].y_prob, range=(0, 1), bins=10, label=name, + color=colors(i) + ) + ax.set(title=name, xlabel="Mean predicted probability", ylabel="Count") plt.tight_layout() plt.show() + +# %% +# :class:`~sklearn.linear_model.LogisticRegression` returns well calibrated +# predictions as it directly optimizes log-loss. In contrast, the other methods +# return biased probabilities, with different biases for each method: +# +# * :class:`~sklearn.naive_bayes.GaussianNB` tends to push +# probabilities to 0 or 1 (see histogram). This is mainly +# because the naive Bayes equation only provides correct estimate of +# probabilities when the assumption that features are conditionally +# independent holds [2]_. However, features tend to be positively correlated +# and is the case with this dataset, which contains 2 features +# generated as random linear combinations of the informative features. These +# correlated features are effectively being 'counted twice', resulting in +# pushing the predicted probabilities towards 0 and 1 [3]_. +# +# * :class:`~sklearn.ensemble.RandomForestClassifier` shows the opposite +# behavior: the histograms show peaks at approx. 0.2 and 0.9 probability, +# while probabilities close to 0 or 1 are very rare. An explanation for this +# is given by Niculescu-Mizil and Caruana [1]_: "Methods such as bagging and +# random forests that average predictions from a base set of models can have +# difficulty making predictions near 0 and 1 because variance in the +# underlying base models will bias predictions that should be near zero or +# one away from these values. Because predictions are restricted to the +# interval [0,1], errors caused by variance tend to be one- sided near zero +# and one. For example, if a model should predict p = 0 for a case, the only +# way bagging can achieve this is if all bagged trees predict zero. If we add +# noise to the trees that bagging is averaging over, this noise will cause +# some trees to predict values larger than 0 for this case, thus moving the +# average prediction of the bagged ensemble away from 0. We observe this +# effect most strongly with random forests because the base-level trees +# trained with random forests have relatively high variance due to feature +# subsetting." As a result, the calibration curve shows a characteristic +# sigmoid shape, indicating that the classifier is under-confident +# and could return probabilities closer to 0 or 1. +# +# * To show the performance of :class:`~sklearn.svm.LinearSVC`, we naively +# scale the output of the :term:`decision_function` into [0, 1] by applying +# min-max scaling, since SVC does not output probabilities by default. +# :class:`~sklearn.svm.LinearSVC` shows an +# even more sigmoid curve than the +# :class:`~sklearn.ensemble.RandomForestClassifier`, which is typical for +# maximum-margin methods [1]_ as they focus on difficult to classify samples +# that are close to the decision boundary (the support vectors). +# +# References +# ---------- +# +# .. [1] `Predicting Good Probabilities with Supervised Learning +# <https://dl.acm.org/doi/pdf/10.1145/1102351.1102430>`_, +# A. Niculescu-Mizil & R. Caruana, ICML 2005 +# .. [2] `Beyond independence: Conditions for the optimality of the simple +# bayesian classifier +# <https://www.ics.uci.edu/~pazzani/Publications/mlc96-pedro.pdf>`_ +# Domingos, P., & Pazzani, M., Proc. 13th Intl. Conf. Machine Learning. +# 1996. +# .. [3] `Obtaining calibrated probability estimates from decision trees and +# naive Bayesian classifiers +# <http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.29.3039&rep=rep1&type=pdf>`_ +# Zadrozny, Bianca, and Charles Elkan. Icml. Vol. 1. 2001. diff --git a/sklearn/calibration.py b/sklearn/calibration.py index 126cbbcbe9c88..95cd6731bb182 100644 --- a/sklearn/calibration.py +++ b/sklearn/calibration.py @@ -25,12 +25,14 @@ RegressorMixin, clone, MetaEstimatorMixin, + is_classifier, ) from .preprocessing import label_binarize, LabelEncoder from .utils import ( column_or_1d, deprecated, indexable, + check_matplotlib_support, ) from .utils.multiclass import check_classification_targets @@ -41,6 +43,7 @@ from .isotonic import IsotonicRegression from .svm import LinearSVC from .model_selection import check_cv, cross_val_predict +from .metrics._plot.base import _get_response class CalibratedClassifierCV(ClassifierMixin, MetaEstimatorMixin, BaseEstimator): @@ -943,3 +946,351 @@ def calibration_curve(y_true, y_prob, *, normalize=False, n_bins=5, strategy="un prob_pred = bin_sums[nonzero] / bin_total[nonzero] return prob_true, prob_pred + + +class CalibrationDisplay: + """Calibration curve (also known as reliability diagram) visualization. + + It is recommended to use + :func:`~sklearn.calibration.CalibrationDisplay.from_estimator` or + :func:`~sklearn.calibration.CalibrationDisplay.from_predictions` + to create a `CalibrationDisplay`. All parameters are stored as attributes. + + Read more about calibration in the :ref:`User Guide <calibration>` and + more about the scikit-learn visualization API in :ref:`visualizations`. + + .. versionadded:: 1.0 + + Parameters + ----------- + prob_true : ndarray of shape (n_bins,) + The proportion of samples whose class is the positive class (fraction + of positives), in each bin. + + prob_pred : ndarray of shape (n_bins,) + The mean predicted probability in each bin. + + y_prob : ndarray of shape (n_samples,) + Probability estimates for the positive class, for each sample. + + name : str, default=None + Name for labeling curve. + + Attributes + ---------- + line_ : matplotlib Artist + Calibration curve. + + ax_ : matplotlib Axes + Axes with calibration curve. + + figure_ : matplotlib Figure + Figure containing the curve. + + See Also + -------- + calibration_curve : Compute true and predicted probabilities for a + calibration curve. + CalibrationDisplay.from_predictions : Plot calibration curve using true + and predicted labels. + CalibrationDisplay.from_estimator : Plot calibration curve using an + estimator and data. + + Examples + -------- + >>> from sklearn.datasets import make_classification + >>> from sklearn.model_selection import train_test_split + >>> from sklearn.linear_model import LogisticRegression + >>> from sklearn.calibration import calibration_curve, CalibrationDisplay + >>> X, y = make_classification(random_state=0) + >>> X_train, X_test, y_train, y_test = train_test_split( + ... X, y, random_state=0) + >>> clf = LogisticRegression(random_state=0) + >>> clf.fit(X_train, y_train) + LogisticRegression(random_state=0) + >>> y_prob = clf.predict_proba(X_test)[:, 1] + >>> prob_true, prob_pred = calibration_curve(y_test, y_prob, n_bins=10) + >>> disp = CalibrationDisplay(prob_true, prob_pred, y_prob) + >>> disp.plot() + <...> + """ + + def __init__(self, prob_true, prob_pred, y_prob, *, name=None): + self.prob_true = prob_true + self.prob_pred = prob_pred + self.y_prob = y_prob + self.name = name + + def plot(self, *, ax=None, name=None, ref_line=True, **kwargs): + """Plot visualization. + + Extra keyword arguments will be passed to + :func:`matplotlib.pyplot.plot`. + + Parameters + ---------- + ax : Matplotlib Axes, default=None + Axes object to plot on. If `None`, a new figure and axes is + created. + + name : str, default=None + Name for labeling curve. + + ref_line : bool, default=True + If `True`, plots a reference line representing a perfectly + calibrated classifier. + + **kwargs : dict + Keyword arguments to be passed to :func:`matplotlib.pyplot.plot`. + + Returns + ------- + display : :class:`~sklearn.calibration.CalibrationDisplay` + Object that stores computed values. + """ + check_matplotlib_support("CalibrationDisplay.plot") + import matplotlib.pyplot as plt + + if ax is None: + fig, ax = plt.subplots() + + name = self.name if name is None else name + self.name = name + + line_kwargs = {} + if name is not None: + line_kwargs["label"] = name + line_kwargs.update(**kwargs) + + ref_line_label = "Perfectly calibrated" + existing_ref_line = ref_line_label in ax.get_legend_handles_labels()[1] + if ref_line and not existing_ref_line: + ax.plot([0, 1], [0, 1], "k:", label=ref_line_label) + self.line_ = ax.plot(self.prob_pred, self.prob_true, "s-", **line_kwargs)[0] + + if "label" in line_kwargs: + ax.legend(loc="lower right") + + ax.set(xlabel="Mean predicted probability", ylabel="Fraction of positives") + + self.ax_ = ax + self.figure_ = ax.figure + return self + + @classmethod + def from_estimator( + cls, + estimator, + X, + y, + *, + n_bins=5, + strategy="uniform", + name=None, + ref_line=True, + ax=None, + **kwargs, + ): + """Plot calibration curve using an binary classifier and data. + + Calibration curve, also known as reliability diagram, uses inputs + from a binary classifier and plots the average predicted probability + for each bin against the fraction of positive classes, on the + y-axis. + + Extra keyword arguments will be passed to + :func:`matplotlib.pyplot.plot`. + + Read more about calibration in the :ref:`User Guide <calibration>` and + more about the scikit-learn visualization API in :ref:`visualizations`. + + .. versionadded:: 1.0 + + Parameters + ---------- + estimator : estimator instance + Fitted classifier or a fitted :class:`~sklearn.pipeline.Pipeline` + in which the last estimator is a classifier. The classifier must + have a :term:`predict_proba` method. + + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Input values. + + y : array-like of shape (n_samples,) + Binary target values. + + n_bins : int, default=5 + Number of bins to discretize the [0, 1] interval into when + calculating the calibration curve. A bigger number requires more + data. + + strategy : {'uniform', 'quantile'}, default='uniform' + Strategy used to define the widths of the bins. + + - `'uniform'`: The bins have identical widths. + - `'quantile'`: The bins have the same number of samples and depend + on predicted probabilities. + + name : str, default=None + Name for labeling curve. If `None`, the name of the estimator is + used. + + ref_line : bool, default=True + If `True`, plots a reference line representing a perfectly + calibrated classifier. + + ax : matplotlib axes, default=None + Axes object to plot on. If `None`, a new figure and axes is + created. + + **kwargs : dict + Keyword arguments to be passed to :func:`matplotlib.pyplot.plot`. + + Returns + ------- + display : :class:`~sklearn.calibration.CalibrationDisplay`. + Object that stores computed values. + + See Also + -------- + CalibrationDisplay.from_predictions : Plot calibration curve using true + and predicted labels. + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> from sklearn.datasets import make_classification + >>> from sklearn.model_selection import train_test_split + >>> from sklearn.linear_model import LogisticRegression + >>> from sklearn.calibration import CalibrationDisplay + >>> X, y = make_classification(random_state=0) + >>> X_train, X_test, y_train, y_test = train_test_split( + ... X, y, random_state=0) + >>> clf = LogisticRegression(random_state=0) + >>> clf.fit(X_train, y_train) + LogisticRegression(random_state=0) + >>> disp = CalibrationDisplay.from_estimator(clf, X_test, y_test) + >>> plt.show() + """ + method_name = f"{cls.__name__}.from_estimator" + check_matplotlib_support(method_name) + + if not is_classifier(estimator): + raise ValueError("'estimator' should be a fitted classifier.") + + # FIXME: `pos_label` should not be set to None + # We should allow any int or string in `calibration_curve`. + y_prob, _ = _get_response( + X, estimator, response_method="predict_proba", pos_label=None + ) + + name = name if name is not None else estimator.__class__.__name__ + return cls.from_predictions( + y, + y_prob, + n_bins=n_bins, + strategy=strategy, + name=name, + ref_line=ref_line, + ax=ax, + **kwargs, + ) + + @classmethod + def from_predictions( + cls, + y_true, + y_prob, + *, + n_bins=5, + strategy="uniform", + name=None, + ref_line=True, + ax=None, + **kwargs, + ): + """Plot calibration curve using true labels and predicted probabilities. + + Calibration curve, also known as reliability diagram, uses inputs + from a binary classifier and plots the average predicted probability + for each bin against the fraction of positive classes, on the + y-axis. + + Extra keyword arguments will be passed to + :func:`matplotlib.pyplot.plot`. + + Read more about calibration in the :ref:`User Guide <calibration>` and + more about the scikit-learn visualization API in :ref:`visualizations`. + + .. versionadded:: 1.0 + + Parameters + ---------- + y_true : array-like of shape (n_samples,) + True labels. + + y_prob : array-like of shape (n_samples,) + The predicted probabilities of the positive class. + + n_bins : int, default=5 + Number of bins to discretize the [0, 1] interval into when + calculating the calibration curve. A bigger number requires more + data. + + strategy : {'uniform', 'quantile'}, default='uniform' + Strategy used to define the widths of the bins. + + - `'uniform'`: The bins have identical widths. + - `'quantile'`: The bins have the same number of samples and depend + on predicted probabilities. + + name : str, default=None + Name for labeling curve. + + ref_line : bool, default=True + If `True`, plots a reference line representing a perfectly + calibrated classifier. + + ax : matplotlib axes, default=None + Axes object to plot on. If `None`, a new figure and axes is + created. + + **kwargs : dict + Keyword arguments to be passed to :func:`matplotlib.pyplot.plot`. + + Returns + ------- + display : :class:`~sklearn.calibration.CalibrationDisplay`. + Object that stores computed values. + + See Also + -------- + CalibrationDisplay.from_estimator : Plot calibration curve using an + estimator and data. + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> from sklearn.datasets import make_classification + >>> from sklearn.model_selection import train_test_split + >>> from sklearn.linear_model import LogisticRegression + >>> from sklearn.calibration import CalibrationDisplay + >>> X, y = make_classification(random_state=0) + >>> X_train, X_test, y_train, y_test = train_test_split( + ... X, y, random_state=0) + >>> clf = LogisticRegression(random_state=0) + >>> clf.fit(X_train, y_train) + LogisticRegression(random_state=0) + >>> y_prob = clf.predict_proba(X_test)[:, 1] + >>> disp = CalibrationDisplay.from_predictions(y_test, y_prob) + >>> plt.show() + """ + method_name = f"{cls.__name__}.from_estimator" + check_matplotlib_support(method_name) + + prob_true, prob_pred = calibration_curve( + y_true, y_prob, n_bins=n_bins, strategy=strategy + ) + + disp = cls(prob_true=prob_true, prob_pred=prob_pred, y_prob=y_prob, name=name) + return disp.plot(ax=ax, ref_line=ref_line, **kwargs) diff --git a/sklearn/metrics/_plot/base.py b/sklearn/metrics/_plot/base.py index 103fcffbd9187..8f5552ffd6808 100644 --- a/sklearn/metrics/_plot/base.py +++ b/sklearn/metrics/_plot/base.py @@ -101,8 +101,12 @@ def _get_response(X, estimator, response_method, pos_label=None): ) if y_pred.ndim != 1: # `predict_proba` - if y_pred.shape[1] != 2: - raise ValueError(classification_error) + y_pred_shape = y_pred.shape[1] + if y_pred_shape != 2: + raise ValueError( + f"{classification_error} fit on multiclass ({y_pred_shape} classes)" + " data" + ) if pos_label is None: pos_label = estimator.classes_[1] y_pred = y_pred[:, 1]
diff --git a/sklearn/tests/test_calibration.py b/sklearn/tests/test_calibration.py index 4fe08c27fb19e..8decff0cc96d5 100644 --- a/sklearn/tests/test_calibration.py +++ b/sklearn/tests/test_calibration.py @@ -18,7 +18,7 @@ ) from sklearn.utils.extmath import softmax from sklearn.exceptions import NotFittedError -from sklearn.datasets import make_classification, make_blobs +from sklearn.datasets import make_classification, make_blobs, load_iris from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import KFold, cross_val_predict from sklearn.naive_bayes import MultinomialNB @@ -27,15 +27,18 @@ RandomForestRegressor, VotingClassifier, ) +from sklearn.linear_model import LogisticRegression, LinearRegression +from sklearn.tree import DecisionTreeClassifier from sklearn.svm import LinearSVC +from sklearn.pipeline import Pipeline, make_pipeline +from sklearn.preprocessing import StandardScaler from sklearn.isotonic import IsotonicRegression from sklearn.feature_extraction import DictVectorizer -from sklearn.pipeline import Pipeline from sklearn.impute import SimpleImputer from sklearn.metrics import brier_score_loss from sklearn.calibration import CalibratedClassifierCV, _CalibratedClassifier from sklearn.calibration import _sigmoid_calibration, _SigmoidCalibration -from sklearn.calibration import calibration_curve +from sklearn.calibration import calibration_curve, CalibrationDisplay @pytest.fixture(scope="module") @@ -618,3 +621,167 @@ def test_calibration_votingclassifier(): calib_clf = CalibratedClassifierCV(base_estimator=vote, cv="prefit") # smoke test: should not raise an error calib_clf.fit(X, y) + + [email protected](scope="module") +def iris_data(): + return load_iris(return_X_y=True) + + [email protected](scope="module") +def iris_data_binary(iris_data): + X, y = iris_data + return X[y < 2], y[y < 2] + + +def test_calibration_display_validation(pyplot, iris_data, iris_data_binary): + X, y = iris_data + X_binary, y_binary = iris_data_binary + + reg = LinearRegression().fit(X, y) + msg = "'estimator' should be a fitted classifier" + with pytest.raises(ValueError, match=msg): + CalibrationDisplay.from_estimator(reg, X, y) + + clf = LinearSVC().fit(X, y) + msg = "response method predict_proba is not defined in" + with pytest.raises(ValueError, match=msg): + CalibrationDisplay.from_estimator(clf, X, y) + + clf = LogisticRegression() + with pytest.raises(NotFittedError): + CalibrationDisplay.from_estimator(clf, X, y) + + [email protected]("constructor_name", ["from_estimator", "from_predictions"]) +def test_calibration_display_non_binary(pyplot, iris_data, constructor_name): + X, y = iris_data + clf = DecisionTreeClassifier() + clf.fit(X, y) + y_prob = clf.predict_proba(X) + + if constructor_name == "from_estimator": + msg = "to be a binary classifier, but got" + with pytest.raises(ValueError, match=msg): + CalibrationDisplay.from_estimator(clf, X, y) + else: + msg = "y should be a 1d array, got an array of shape" + with pytest.raises(ValueError, match=msg): + CalibrationDisplay.from_predictions(y, y_prob) + + [email protected]("n_bins", [5, 10]) [email protected]("strategy", ["uniform", "quantile"]) +def test_calibration_display_compute(pyplot, iris_data_binary, n_bins, strategy): + # Ensure `CalibrationDisplay.from_predictions` and `calibration_curve` + # compute the same results. Also checks attributes of the + # CalibrationDisplay object. + X, y = iris_data_binary + + lr = LogisticRegression().fit(X, y) + + viz = CalibrationDisplay.from_estimator( + lr, X, y, n_bins=n_bins, strategy=strategy, alpha=0.8 + ) + + y_prob = lr.predict_proba(X)[:, 1] + prob_true, prob_pred = calibration_curve( + y, y_prob, n_bins=n_bins, strategy=strategy + ) + + assert_allclose(viz.prob_true, prob_true) + assert_allclose(viz.prob_pred, prob_pred) + assert_allclose(viz.y_prob, y_prob) + + assert viz.name == "LogisticRegression" + + # cannot fail thanks to pyplot fixture + import matplotlib as mpl # noqa + + assert isinstance(viz.line_, mpl.lines.Line2D) + assert viz.line_.get_alpha() == 0.8 + assert isinstance(viz.ax_, mpl.axes.Axes) + assert isinstance(viz.figure_, mpl.figure.Figure) + + assert viz.ax_.get_xlabel() == "Mean predicted probability" + assert viz.ax_.get_ylabel() == "Fraction of positives" + assert viz.line_.get_label() == "LogisticRegression" + + +def test_plot_calibration_curve_pipeline(pyplot, iris_data_binary): + # Ensure pipelines are supported by CalibrationDisplay.from_estimator + X, y = iris_data_binary + clf = make_pipeline(StandardScaler(), LogisticRegression()) + clf.fit(X, y) + viz = CalibrationDisplay.from_estimator(clf, X, y) + assert clf.__class__.__name__ in viz.line_.get_label() + assert viz.name == clf.__class__.__name__ + + [email protected]( + "name, expected_label", [(None, "_line1"), ("my_est", "my_est")] +) +def test_calibration_display_default_labels(pyplot, name, expected_label): + prob_true = np.array([0, 1, 1, 0]) + prob_pred = np.array([0.2, 0.8, 0.8, 0.4]) + y_prob = np.array([]) + + viz = CalibrationDisplay(prob_true, prob_pred, y_prob, name=name) + viz.plot() + assert viz.line_.get_label() == expected_label + + +def test_calibration_display_label_class_plot(pyplot): + # Checks that when instantiating `CalibrationDisplay` class then calling + # `plot`, `self.name` is the one given in `plot` + prob_true = np.array([0, 1, 1, 0]) + prob_pred = np.array([0.2, 0.8, 0.8, 0.4]) + y_prob = np.array([]) + + name = "name one" + viz = CalibrationDisplay(prob_true, prob_pred, y_prob, name=name) + assert viz.name == name + name = "name two" + viz.plot(name=name) + assert viz.name == name + assert viz.line_.get_label() == name + + [email protected]("constructor_name", ["from_estimator", "from_predictions"]) +def test_calibration_display_name_multiple_calls( + constructor_name, pyplot, iris_data_binary +): + # Check that the `name` used when calling + # `CalibrationDisplay.from_predictions` or + # `CalibrationDisplay.from_estimator` is used when multiple + # `CalibrationDisplay.viz.plot()` calls are made. + X, y = iris_data_binary + clf_name = "my hand-crafted name" + clf = LogisticRegression().fit(X, y) + y_prob = clf.predict_proba(X)[:, 1] + + constructor = getattr(CalibrationDisplay, constructor_name) + params = (clf, X, y) if constructor_name == "from_estimator" else (y, y_prob) + + viz = constructor(*params, name=clf_name) + assert viz.name == clf_name + pyplot.close("all") + viz.plot() + assert clf_name == viz.line_.get_label() + pyplot.close("all") + clf_name = "another_name" + viz.plot(name=clf_name) + assert clf_name == viz.line_.get_label() + + +def test_calibration_display_ref_line(pyplot, iris_data_binary): + # Check that `ref_line` only appears once + X, y = iris_data_binary + lr = LogisticRegression().fit(X, y) + dt = DecisionTreeClassifier().fit(X, y) + + viz = CalibrationDisplay.from_estimator(lr, X, y) + viz2 = CalibrationDisplay.from_estimator(dt, X, y, ax=viz.ax_) + + labels = viz2.ax_.get_legend_handles_labels()[1] + assert labels.count("Perfectly calibrated") == 1
[ { "path": "doc/modules/calibration.rst", "old_path": "a/doc/modules/calibration.rst", "new_path": "b/doc/modules/calibration.rst", "metadata": "diff --git a/doc/modules/calibration.rst b/doc/modules/calibration.rst\nindex d0a9737dac612..1fcd1d501d100 100644\n--- a/doc/modules/calibration.rst\n+++ b/doc/modules/calibration.rst\n@@ -30,11 +30,25 @@ approximately 80% actually belong to the positive class.\n Calibration curves\n ------------------\n \n-The following plot compares how well the probabilistic predictions of\n-different classifiers are calibrated, using :func:`calibration_curve`.\n+Calibration curves (also known as reliability diagrams) compare how well the\n+probabilistic predictions of a binary classifier are calibrated. It plots\n+the true frequency of the positive label against its predicted probability,\n+for binned predictions.\n The x axis represents the average predicted probability in each bin. The\n y axis is the *fraction of positives*, i.e. the proportion of samples whose\n-class is the positive class (in each bin).\n+class is the positive class (in each bin). The top calibration curve plot\n+is created with :func:`CalibrationDisplay.from_estimators`, which uses\n+:func:`calibration_curve` to calculate the per bin average predicted\n+probabilities and fraction of positives.\n+:func:`CalibrationDisplay.from_estimator`\n+takes as input a fitted classifier, which is used to calculate the predicted\n+probabilities. The classifier thus must have :term:`predict_proba` method. For\n+the few classifiers that do not have a :term:`predict_proba` method, it is\n+possible to use :class:`CalibratedClassifierCV` to calibrate the classifier\n+outputs to probabilities.\n+\n+The bottom histogram gives some insight into the behavior of each classifier\n+by showing the number of samples in each predicted probability bin.\n \n .. figure:: ../auto_examples/calibration/images/sphx_glr_plot_compare_calibration_001.png\n :target: ../auto_examples/calibration/plot_compare_calibration.html\n@@ -161,6 +175,8 @@ mean a better calibrated model.\n :class:`CalibratedClassifierCV` supports the use of two 'calibration'\n regressors: 'sigmoid' and 'isotonic'.\n \n+.. _sigmoid_regressor:\n+\n Sigmoid\n ^^^^^^^\n \n" }, { "path": "doc/modules/classes.rst", "old_path": "a/doc/modules/classes.rst", "new_path": "b/doc/modules/classes.rst", "metadata": "diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst\nindex 3edd8adee8191..3848a189c35d4 100644\n--- a/doc/modules/classes.rst\n+++ b/doc/modules/classes.rst\n@@ -1123,7 +1123,7 @@ See the :ref:`visualizations` section of the user guide for further details.\n metrics.DetCurveDisplay\n metrics.PrecisionRecallDisplay\n metrics.RocCurveDisplay\n-\n+ calibration.CalibrationDisplay\n \n .. _mixture_ref:\n \n" }, { "path": "doc/visualizations.rst", "old_path": "a/doc/visualizations.rst", "new_path": "b/doc/visualizations.rst", "metadata": "diff --git a/doc/visualizations.rst b/doc/visualizations.rst\nindex a2d40408b403f..65612b2787d84 100644\n--- a/doc/visualizations.rst\n+++ b/doc/visualizations.rst\n@@ -65,6 +65,7 @@ values of the curves.\n * :ref:`sphx_glr_auto_examples_miscellaneous_plot_roc_curve_visualization_api.py`\n * :ref:`sphx_glr_auto_examples_miscellaneous_plot_partial_dependence_visualization_api.py`\n * :ref:`sphx_glr_auto_examples_miscellaneous_plot_display_object_visualization.py`\n+ * :ref:`sphx_glr_auto_examples_calibration_plot_compare_calibration.py`\n \n Available Plotting Utilities\n ============================\n@@ -90,6 +91,7 @@ Display Objects\n \n .. autosummary::\n \n+ calibration.CalibrationDisplay\n inspection.PartialDependenceDisplay\n metrics.ConfusionMatrixDisplay\n metrics.DetCurveDisplay\n" }, { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex d9f63cc62add4..001c3350fb056 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -152,6 +152,9 @@ Changelog\n :class:`calibration.CalibratedClassifierCV` can now properly be used on\n prefitted pipelines. :pr:`19641` by :user:`Alek Lefebvre <AlekLefebvre>`.\n \n+- |Feature| :func:`calibration.CalibrationDisplay` added to plot\n+ calibration curves. :pr:`17443` by :user:`Lucy Liu <lucyleeow>`.\n+\n - |Fix| Fixed an error when using a ::class:`ensemble.VotingClassifier`\n as `base_estimator` in ::class:`calibration.CalibratedClassifierCV`.\n :pr:`20087` by :user:`Clément Fauchereau <clement-f>`.\n" } ]
1.00
c3db2cdbf5244229af2c5eb54f9216a69f77a146
[]
[ "sklearn/tests/test_calibration.py::test_calibration[True-isotonic]", "sklearn/tests/test_calibration.py::test_parallel_execution[False-isotonic]", "sklearn/tests/test_calibration.py::test_calibration_ensemble_false[isotonic]", "sklearn/tests/test_calibration.py::test_calibration_attributes[clf0-2]", "sklearn/tests/test_calibration.py::test_plot_calibration_curve_pipeline", "sklearn/tests/test_calibration.py::test_calibration_display_label_class_plot", "sklearn/tests/test_calibration.py::test_calibration_nan_imputer[False]", "sklearn/tests/test_calibration.py::test_calibration_multiclass[1-True-isotonic]", "sklearn/tests/test_calibration.py::test_calibration_display_name_multiple_calls[from_predictions]", "sklearn/tests/test_calibration.py::test_calibration_nan_imputer[True]", "sklearn/tests/test_calibration.py::test_sigmoid_calibration", "sklearn/tests/test_calibration.py::test_calibration_accepts_ndarray[X0]", "sklearn/tests/test_calibration.py::test_calibration_attributes[clf1-prefit]", "sklearn/tests/test_calibration.py::test_calibration_curve", "sklearn/tests/test_calibration.py::test_parallel_execution[False-sigmoid]", "sklearn/tests/test_calibration.py::test_sample_weight[True-isotonic]", "sklearn/tests/test_calibration.py::test_calibration_display_non_binary[from_estimator]", "sklearn/tests/test_calibration.py::test_calibration_display_non_binary[from_predictions]", "sklearn/tests/test_calibration.py::test_calibration_multiclass[0-True-isotonic]", "sklearn/tests/test_calibration.py::test_calibration_multiclass[0-False-sigmoid]", "sklearn/tests/test_calibration.py::test_calibration_multiclass[1-False-sigmoid]", "sklearn/tests/test_calibration.py::test_calibration[False-isotonic]", "sklearn/tests/test_calibration.py::test_sample_weight[True-sigmoid]", "sklearn/tests/test_calibration.py::test_calibration_ensemble_false[sigmoid]", "sklearn/tests/test_calibration.py::test_calibration_inconsistent_prefit_n_features_in", "sklearn/tests/test_calibration.py::test_calibration_display_validation", "sklearn/tests/test_calibration.py::test_calibration_display_compute[quantile-5]", "sklearn/tests/test_calibration.py::test_calibrated_classifier_cv_deprecation", "sklearn/tests/test_calibration.py::test_parallel_execution[True-sigmoid]", "sklearn/tests/test_calibration.py::test_calibration_cv_splitter[True]", "sklearn/tests/test_calibration.py::test_calibration_less_classes[True]", "sklearn/tests/test_calibration.py::test_calibration_prob_sum[False]", "sklearn/tests/test_calibration.py::test_calibration_cv_splitter[False]", "sklearn/tests/test_calibration.py::test_calibration_bad_method[False]", "sklearn/tests/test_calibration.py::test_calibration_multiclass[0-True-sigmoid]", "sklearn/tests/test_calibration.py::test_calibration_votingclassifier", "sklearn/tests/test_calibration.py::test_calibration_display_compute[uniform-5]", "sklearn/tests/test_calibration.py::test_calibration_regressor[False]", "sklearn/tests/test_calibration.py::test_calibration_prefit", "sklearn/tests/test_calibration.py::test_calibration_multiclass[0-False-isotonic]", "sklearn/tests/test_calibration.py::test_calibration_display_compute[quantile-10]", "sklearn/tests/test_calibration.py::test_calibration_multiclass[1-True-sigmoid]", "sklearn/tests/test_calibration.py::test_calibration_display_compute[uniform-10]", "sklearn/tests/test_calibration.py::test_calibration_zero_probability", "sklearn/tests/test_calibration.py::test_parallel_execution[True-isotonic]", "sklearn/tests/test_calibration.py::test_calibration_accepts_ndarray[X1]", "sklearn/tests/test_calibration.py::test_calibration_less_classes[False]", "sklearn/tests/test_calibration.py::test_calibration_dict_pipeline", "sklearn/tests/test_calibration.py::test_calibration[True-sigmoid]", "sklearn/tests/test_calibration.py::test_calibration_multiclass[1-False-isotonic]", "sklearn/tests/test_calibration.py::test_calibration[False-sigmoid]", "sklearn/tests/test_calibration.py::test_calibration_display_name_multiple_calls[from_estimator]", "sklearn/tests/test_calibration.py::test_calibration_prob_sum[True]", "sklearn/tests/test_calibration.py::test_calibration_display_ref_line", "sklearn/tests/test_calibration.py::test_calibration_display_default_labels[my_est-my_est]", "sklearn/tests/test_calibration.py::test_calibration_default_estimator", "sklearn/tests/test_calibration.py::test_calibration_bad_method[True]", "sklearn/tests/test_calibration.py::test_calibration_regressor[True]", "sklearn/tests/test_calibration.py::test_sample_weight[False-sigmoid]", "sklearn/tests/test_calibration.py::test_sample_weight[False-isotonic]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/modules/calibration.rst", "old_path": "a/doc/modules/calibration.rst", "new_path": "b/doc/modules/calibration.rst", "metadata": "diff --git a/doc/modules/calibration.rst b/doc/modules/calibration.rst\nindex d0a9737dac612..1fcd1d501d100 100644\n--- a/doc/modules/calibration.rst\n+++ b/doc/modules/calibration.rst\n@@ -30,11 +30,25 @@ approximately 80% actually belong to the positive class.\n Calibration curves\n ------------------\n \n-The following plot compares how well the probabilistic predictions of\n-different classifiers are calibrated, using :func:`calibration_curve`.\n+Calibration curves (also known as reliability diagrams) compare how well the\n+probabilistic predictions of a binary classifier are calibrated. It plots\n+the true frequency of the positive label against its predicted probability,\n+for binned predictions.\n The x axis represents the average predicted probability in each bin. The\n y axis is the *fraction of positives*, i.e. the proportion of samples whose\n-class is the positive class (in each bin).\n+class is the positive class (in each bin). The top calibration curve plot\n+is created with :func:`CalibrationDisplay.from_estimators`, which uses\n+:func:`calibration_curve` to calculate the per bin average predicted\n+probabilities and fraction of positives.\n+:func:`CalibrationDisplay.from_estimator`\n+takes as input a fitted classifier, which is used to calculate the predicted\n+probabilities. The classifier thus must have :term:`predict_proba` method. For\n+the few classifiers that do not have a :term:`predict_proba` method, it is\n+possible to use :class:`CalibratedClassifierCV` to calibrate the classifier\n+outputs to probabilities.\n+\n+The bottom histogram gives some insight into the behavior of each classifier\n+by showing the number of samples in each predicted probability bin.\n \n .. figure:: ../auto_examples/calibration/images/sphx_glr_plot_compare_calibration_001.png\n :target: ../auto_examples/calibration/plot_compare_calibration.html\n@@ -161,6 +175,8 @@ mean a better calibrated model.\n :class:`CalibratedClassifierCV` supports the use of two 'calibration'\n regressors: 'sigmoid' and 'isotonic'.\n \n+.. _sigmoid_regressor:\n+\n Sigmoid\n ^^^^^^^\n \n" }, { "path": "doc/modules/classes.rst", "old_path": "a/doc/modules/classes.rst", "new_path": "b/doc/modules/classes.rst", "metadata": "diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst\nindex 3edd8adee8191..3848a189c35d4 100644\n--- a/doc/modules/classes.rst\n+++ b/doc/modules/classes.rst\n@@ -1123,7 +1123,7 @@ See the :ref:`visualizations` section of the user guide for further details.\n metrics.DetCurveDisplay\n metrics.PrecisionRecallDisplay\n metrics.RocCurveDisplay\n-\n+ calibration.CalibrationDisplay\n \n .. _mixture_ref:\n \n" }, { "path": "doc/visualizations.rst", "old_path": "a/doc/visualizations.rst", "new_path": "b/doc/visualizations.rst", "metadata": "diff --git a/doc/visualizations.rst b/doc/visualizations.rst\nindex a2d40408b403f..65612b2787d84 100644\n--- a/doc/visualizations.rst\n+++ b/doc/visualizations.rst\n@@ -65,6 +65,7 @@ values of the curves.\n * :ref:`sphx_glr_auto_examples_miscellaneous_plot_roc_curve_visualization_api.py`\n * :ref:`sphx_glr_auto_examples_miscellaneous_plot_partial_dependence_visualization_api.py`\n * :ref:`sphx_glr_auto_examples_miscellaneous_plot_display_object_visualization.py`\n+ * :ref:`sphx_glr_auto_examples_calibration_plot_compare_calibration.py`\n \n Available Plotting Utilities\n ============================\n@@ -90,6 +91,7 @@ Display Objects\n \n .. autosummary::\n \n+ calibration.CalibrationDisplay\n inspection.PartialDependenceDisplay\n metrics.ConfusionMatrixDisplay\n metrics.DetCurveDisplay\n" }, { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex d9f63cc62add4..001c3350fb056 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -152,6 +152,9 @@ Changelog\n :class:`calibration.CalibratedClassifierCV` can now properly be used on\n prefitted pipelines. :pr:`<PRID>` by :user:`<NAME>`.\n \n+- |Feature| :func:`calibration.CalibrationDisplay` added to plot\n+ calibration curves. :pr:`<PRID>` by :user:`<NAME>`.\n+\n - |Fix| Fixed an error when using a ::class:`ensemble.VotingClassifier`\n as `base_estimator` in ::class:`calibration.CalibratedClassifierCV`.\n :pr:`<PRID>` by :user:`<NAME>`.\n" } ]
diff --git a/doc/modules/calibration.rst b/doc/modules/calibration.rst index d0a9737dac612..1fcd1d501d100 100644 --- a/doc/modules/calibration.rst +++ b/doc/modules/calibration.rst @@ -30,11 +30,25 @@ approximately 80% actually belong to the positive class. Calibration curves ------------------ -The following plot compares how well the probabilistic predictions of -different classifiers are calibrated, using :func:`calibration_curve`. +Calibration curves (also known as reliability diagrams) compare how well the +probabilistic predictions of a binary classifier are calibrated. It plots +the true frequency of the positive label against its predicted probability, +for binned predictions. The x axis represents the average predicted probability in each bin. The y axis is the *fraction of positives*, i.e. the proportion of samples whose -class is the positive class (in each bin). +class is the positive class (in each bin). The top calibration curve plot +is created with :func:`CalibrationDisplay.from_estimators`, which uses +:func:`calibration_curve` to calculate the per bin average predicted +probabilities and fraction of positives. +:func:`CalibrationDisplay.from_estimator` +takes as input a fitted classifier, which is used to calculate the predicted +probabilities. The classifier thus must have :term:`predict_proba` method. For +the few classifiers that do not have a :term:`predict_proba` method, it is +possible to use :class:`CalibratedClassifierCV` to calibrate the classifier +outputs to probabilities. + +The bottom histogram gives some insight into the behavior of each classifier +by showing the number of samples in each predicted probability bin. .. figure:: ../auto_examples/calibration/images/sphx_glr_plot_compare_calibration_001.png :target: ../auto_examples/calibration/plot_compare_calibration.html @@ -161,6 +175,8 @@ mean a better calibrated model. :class:`CalibratedClassifierCV` supports the use of two 'calibration' regressors: 'sigmoid' and 'isotonic'. +.. _sigmoid_regressor: + Sigmoid ^^^^^^^ diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst index 3edd8adee8191..3848a189c35d4 100644 --- a/doc/modules/classes.rst +++ b/doc/modules/classes.rst @@ -1123,7 +1123,7 @@ See the :ref:`visualizations` section of the user guide for further details. metrics.DetCurveDisplay metrics.PrecisionRecallDisplay metrics.RocCurveDisplay - + calibration.CalibrationDisplay .. _mixture_ref: diff --git a/doc/visualizations.rst b/doc/visualizations.rst index a2d40408b403f..65612b2787d84 100644 --- a/doc/visualizations.rst +++ b/doc/visualizations.rst @@ -65,6 +65,7 @@ values of the curves. * :ref:`sphx_glr_auto_examples_miscellaneous_plot_roc_curve_visualization_api.py` * :ref:`sphx_glr_auto_examples_miscellaneous_plot_partial_dependence_visualization_api.py` * :ref:`sphx_glr_auto_examples_miscellaneous_plot_display_object_visualization.py` + * :ref:`sphx_glr_auto_examples_calibration_plot_compare_calibration.py` Available Plotting Utilities ============================ @@ -90,6 +91,7 @@ Display Objects .. autosummary:: + calibration.CalibrationDisplay inspection.PartialDependenceDisplay metrics.ConfusionMatrixDisplay metrics.DetCurveDisplay diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index d9f63cc62add4..001c3350fb056 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -152,6 +152,9 @@ Changelog :class:`calibration.CalibratedClassifierCV` can now properly be used on prefitted pipelines. :pr:`<PRID>` by :user:`<NAME>`. +- |Feature| :func:`calibration.CalibrationDisplay` added to plot + calibration curves. :pr:`<PRID>` by :user:`<NAME>`. + - |Fix| Fixed an error when using a ::class:`ensemble.VotingClassifier` as `base_estimator` in ::class:`calibration.CalibratedClassifierCV`. :pr:`<PRID>` by :user:`<NAME>`.
scikit-learn/scikit-learn
scikit-learn__scikit-learn-20117
https://github.com/scikit-learn/scikit-learn/pull/20117
diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index 34e9f0670ba81..ba8d93f181059 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -150,6 +150,11 @@ Changelog - |Efficiency| :class:`cluster.MiniBatchKMeans` is now faster in multicore settings. :pr:`17622` by :user:`Jérémie du Boisberranger <jeremiedbb>`. +- |Enhancement| The `predict` and `fit_predict` methods of + :class:`cluster.AffinityPropagation` now accept sparse data type for input + data. + :pr:`20117` by :user:`Venkatachalam Natchiappan <venkyyuvy>` + - |Fix| Fixed a bug in :class:`cluster.MiniBatchKMeans` where the sample weights were partially ignored when the input is sparse. :pr:`17622` by :user:`Jérémie du Boisberranger <jeremiedbb>`. diff --git a/sklearn/cluster/_affinity_propagation.py b/sklearn/cluster/_affinity_propagation.py index ccae0b7538b58..59620ab31f63d 100644 --- a/sklearn/cluster/_affinity_propagation.py +++ b/sklearn/cluster/_affinity_propagation.py @@ -436,7 +436,7 @@ def predict(self, X): Cluster labels. """ check_is_fitted(self) - X = self._validate_data(X, reset=False) + X = self._validate_data(X, reset=False, accept_sparse='csr') if not hasattr(self, "cluster_centers_"): raise ValueError("Predict method is not supported when " "affinity='precomputed'.")
diff --git a/sklearn/cluster/tests/test_affinity_propagation.py b/sklearn/cluster/tests/test_affinity_propagation.py index ae2806bf38e59..a42a8112782a5 100644 --- a/sklearn/cluster/tests/test_affinity_propagation.py +++ b/sklearn/cluster/tests/test_affinity_propagation.py @@ -238,6 +238,25 @@ def test_affinity_propagation_float32(): assert_array_equal(afp.labels_, expected) +def test_sparse_input_for_predict(): + # Test to make sure sparse inputs are accepted for predict + # (non-regression test for issue #20049) + af = AffinityPropagation(affinity="euclidean", random_state=42) + af.fit(X) + labels = af.predict(csr_matrix((2, 2))) + assert_array_equal(labels, (2, 2)) + + +def test_sparse_input_for_fit_predict(): + # Test to make sure sparse inputs are accepted for fit_predict + # (non-regression test for issue #20049) + af = AffinityPropagation(affinity="euclidean", random_state=42) + rng = np.random.RandomState(42) + X = csr_matrix(rng.randint(0, 2, size=(5, 5))) + labels = af.fit_predict(X) + assert_array_equal(labels, (0, 1, 1, 2, 3)) + + # TODO: Remove in 1.1 def test_affinity_propagation_pairwise_is_deprecated(): afp = AffinityPropagation(affinity='precomputed')
[ { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 34e9f0670ba81..ba8d93f181059 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -150,6 +150,11 @@ Changelog\n - |Efficiency| :class:`cluster.MiniBatchKMeans` is now faster in multicore\n settings. :pr:`17622` by :user:`Jérémie du Boisberranger <jeremiedbb>`.\n \n+- |Enhancement| The `predict` and `fit_predict` methods of\n+ :class:`cluster.AffinityPropagation` now accept sparse data type for input\n+ data.\n+ :pr:`20117` by :user:`Venkatachalam Natchiappan <venkyyuvy>`\n+\n - |Fix| Fixed a bug in :class:`cluster.MiniBatchKMeans` where the sample\n weights were partially ignored when the input is sparse. :pr:`17622` by\n :user:`Jérémie du Boisberranger <jeremiedbb>`.\n" } ]
1.00
c67518350f91072f9d37ed09c5ef7edf555b6cf6
[ "sklearn/cluster/tests/test_affinity_propagation.py::test_affinity_propagation_predict", "sklearn/cluster/tests/test_affinity_propagation.py::test_affinity_propagation_fit_non_convergence", "sklearn/cluster/tests/test_affinity_propagation.py::test_affinity_propagation_predict_error", "sklearn/cluster/tests/test_affinity_propagation.py::test_equal_similarities_and_preferences", "sklearn/cluster/tests/test_affinity_propagation.py::test_affinity_propagation_float32", "sklearn/cluster/tests/test_affinity_propagation.py::test_affinity_propagation_predict_non_convergence", "sklearn/cluster/tests/test_affinity_propagation.py::test_sparse_input_for_fit_predict", "sklearn/cluster/tests/test_affinity_propagation.py::test_affinity_propagation_pairwise_is_deprecated", "sklearn/cluster/tests/test_affinity_propagation.py::test_affinity_propagation_non_convergence_regressiontest", "sklearn/cluster/tests/test_affinity_propagation.py::test_affinity_propagation_random_state", "sklearn/cluster/tests/test_affinity_propagation.py::test_affinity_propagation" ]
[ "sklearn/cluster/tests/test_affinity_propagation.py::test_sparse_input_for_predict" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 34e9f0670ba81..ba8d93f181059 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -150,6 +150,11 @@ Changelog\n - |Efficiency| :class:`cluster.MiniBatchKMeans` is now faster in multicore\n settings. :pr:`<PRID>` by :user:`<NAME>`.\n \n+- |Enhancement| The `predict` and `fit_predict` methods of\n+ :class:`cluster.AffinityPropagation` now accept sparse data type for input\n+ data.\n+ :pr:`<PRID>` by :user:`<NAME>`\n+\n - |Fix| Fixed a bug in :class:`cluster.MiniBatchKMeans` where the sample\n weights were partially ignored when the input is sparse. :pr:`<PRID>` by\n :user:`<NAME>`.\n" } ]
diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index 34e9f0670ba81..ba8d93f181059 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -150,6 +150,11 @@ Changelog - |Efficiency| :class:`cluster.MiniBatchKMeans` is now faster in multicore settings. :pr:`<PRID>` by :user:`<NAME>`. +- |Enhancement| The `predict` and `fit_predict` methods of + :class:`cluster.AffinityPropagation` now accept sparse data type for input + data. + :pr:`<PRID>` by :user:`<NAME>` + - |Fix| Fixed a bug in :class:`cluster.MiniBatchKMeans` where the sample weights were partially ignored when the input is sparse. :pr:`<PRID>` by :user:`<NAME>`.
scikit-learn/scikit-learn
scikit-learn__scikit-learn-21298
https://github.com/scikit-learn/scikit-learn/pull/21298
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index f755aeba20030..7792fa14b13a5 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -113,10 +113,10 @@ Changelog - |Fix| :class:`decomposition.FastICA` now validates input parameters in `fit` instead of `__init__`. :pr:`21432` by :user:`Hannah Bohle <hhnnhh>` and :user:`Maren Westermann <marenwestermann>`. - + - |Fix| :class:`decomposition.FactorAnalysis` now validates input parameters in `fit` instead of `__init__`. - :pr:`21713` by :user:`Haya <HayaAlmutairi>` and + :pr:`21713` by :user:`Haya <HayaAlmutairi>` and :user:`Krum Arnaudov <krumeto>`. - |Fix| :class:`decomposition.KernelPCA` now validates input parameters in @@ -257,6 +257,10 @@ Changelog message when running in a jupyter notebook that is not trusted. :pr:`21316` by `Thomas Fan`_. +- |Enhancement| :func:`utils.estimator_html_repr` displays an arrow on the top + left corner of the HTML representation to show how the elements are + clickable. :pr:`21298` by `Thomas Fan`_. + :mod:`sklearn.neighbors` ........................ diff --git a/sklearn/utils/_estimator_html_repr.py b/sklearn/utils/_estimator_html_repr.py index d0e61a3abe3c6..c1bb1801cd9e6 100644 --- a/sklearn/utils/_estimator_html_repr.py +++ b/sklearn/utils/_estimator_html_repr.py @@ -70,13 +70,14 @@ def _write_label_html( if name_details is not None: name_details = html.escape(str(name_details)) + label_class = "sk-toggleable__label sk-toggleable__label-arrow" + checked_str = "checked" if checked else "" est_id = uuid.uuid4() out.write( '<input class="sk-toggleable__control sk-hidden--visually" ' f'id="{est_id}" type="checkbox" {checked_str}>' - f'<label class="sk-toggleable__label" for="{est_id}">' - f"{name}</label>" + f'<label for="{est_id}" class="{label_class}">{name}</label>' f'<div class="sk-toggleable__content"><pre>{name_details}' "</pre></div>" ) @@ -179,6 +180,18 @@ def _write_estimator_html( box-sizing: border-box; text-align: center; } +#$id label.sk-toggleable__label-arrow:before { + content: "▸"; + float: left; + margin-right: 0.25em; + color: #696969; +} +#$id label.sk-toggleable__label-arrow:hover:before { + color: black; +} +#$id div.sk-estimator:hover label.sk-toggleable__label-arrow:before { + color: black; +} #$id div.sk-toggleable__content { max-height: 0; max-width: 0; @@ -197,6 +210,9 @@ def _write_estimator_html( max-width: 100%; overflow: auto; } +#$id input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before { + content: "▾"; +} #$id div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label { background-color: #d4ebff; } @@ -310,7 +326,7 @@ def _write_estimator_html( /* jupyter's `normalize.less` sets `[hidden] { display: none; }` but bootstrap.min.css set `[hidden] { display: none !important; }` so we also need the `!important` here to be able to override the - default hidden behavior on the sphinx rendered scikit-learn.org. + default hidden behavior on the sphinx rendered scikit-learn.org. See: https://github.com/scikit-learn/scikit-learn/issues/21755 */ display: inline-block !important; position: relative;
diff --git a/sklearn/utils/tests/test_estimator_html_repr.py b/sklearn/utils/tests/test_estimator_html_repr.py index 90300a9bef948..39731860fdd3f 100644 --- a/sklearn/utils/tests/test_estimator_html_repr.py +++ b/sklearn/utils/tests/test_estimator_html_repr.py @@ -18,6 +18,7 @@ from sklearn.cluster import Birch from sklearn.cluster import AgglomerativeClustering from sklearn.preprocessing import OneHotEncoder +from sklearn.preprocessing import StandardScaler from sklearn.svm import LinearSVC from sklearn.svm import LinearSVR from sklearn.tree import DecisionTreeClassifier @@ -292,3 +293,14 @@ def test_fallback_exists(): f'<div class="sk-text-repr-fallback"><pre>{html.escape(str(pca))}' in html_output ) + + +def test_show_arrow_pipeline(): + """Show arrow in pipeline for top level in pipeline""" + pipe = Pipeline([("scale", StandardScaler()), ("log_Reg", LogisticRegression())]) + + html_output = estimator_html_repr(pipe) + assert ( + 'class="sk-toggleable__label sk-toggleable__label-arrow">Pipeline' + in html_output + )
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex f755aeba20030..7792fa14b13a5 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -113,10 +113,10 @@ Changelog\n \n - |Fix| :class:`decomposition.FastICA` now validates input parameters in `fit` instead of `__init__`.\n :pr:`21432` by :user:`Hannah Bohle <hhnnhh>` and :user:`Maren Westermann <marenwestermann>`.\n- \n+\n - |Fix| :class:`decomposition.FactorAnalysis` now validates input parameters\n in `fit` instead of `__init__`.\n- :pr:`21713` by :user:`Haya <HayaAlmutairi>` and \n+ :pr:`21713` by :user:`Haya <HayaAlmutairi>` and\n :user:`Krum Arnaudov <krumeto>`.\n \n - |Fix| :class:`decomposition.KernelPCA` now validates input parameters in\n@@ -257,6 +257,10 @@ Changelog\n message when running in a jupyter notebook that is not trusted. :pr:`21316`\n by `Thomas Fan`_.\n \n+- |Enhancement| :func:`utils.estimator_html_repr` displays an arrow on the top\n+ left corner of the HTML representation to show how the elements are\n+ clickable. :pr:`21298` by `Thomas Fan`_.\n+\n :mod:`sklearn.neighbors`\n ........................\n \n" } ]
1.01
863bbc07b307ee1af0f0d7d794b9fb9d59ac3e1c
[ "sklearn/utils/tests/test_estimator_html_repr.py::test_fallback_exists", "sklearn/utils/tests/test_estimator_html_repr.py::test_stacking_regressor[None]", "sklearn/utils/tests/test_estimator_html_repr.py::test_get_visual_block_single_str_none[passthrough]", "sklearn/utils/tests/test_estimator_html_repr.py::test_write_label_html[True]", "sklearn/utils/tests/test_estimator_html_repr.py::test_get_visual_block_pipeline", "sklearn/utils/tests/test_estimator_html_repr.py::test_stacking_classsifer[None]", "sklearn/utils/tests/test_estimator_html_repr.py::test_write_label_html[False]", "sklearn/utils/tests/test_estimator_html_repr.py::test_one_estimator_print_change_only[False]", "sklearn/utils/tests/test_estimator_html_repr.py::test_get_visual_block_voting", "sklearn/utils/tests/test_estimator_html_repr.py::test_duck_typing_nested_estimator", "sklearn/utils/tests/test_estimator_html_repr.py::test_birch_duck_typing_meta", "sklearn/utils/tests/test_estimator_html_repr.py::test_estimator_html_repr_pipeline", "sklearn/utils/tests/test_estimator_html_repr.py::test_one_estimator_print_change_only[True]", "sklearn/utils/tests/test_estimator_html_repr.py::test_stacking_classsifer[final_estimator1]", "sklearn/utils/tests/test_estimator_html_repr.py::test_get_visual_block_single_str_none[None]", "sklearn/utils/tests/test_estimator_html_repr.py::test_get_visual_block_single_str_none[drop]", "sklearn/utils/tests/test_estimator_html_repr.py::test_stacking_regressor[final_estimator1]", "sklearn/utils/tests/test_estimator_html_repr.py::test_get_visual_block_single_estimator", "sklearn/utils/tests/test_estimator_html_repr.py::test_get_visual_block_feature_union", "sklearn/utils/tests/test_estimator_html_repr.py::test_get_visual_block_column_transformer", "sklearn/utils/tests/test_estimator_html_repr.py::test_ovo_classifier_duck_typing_meta" ]
[ "sklearn/utils/tests/test_estimator_html_repr.py::test_show_arrow_pipeline" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex f755aeba20030..7792fa14b13a5 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -113,10 +113,10 @@ Changelog\n \n - |Fix| :class:`decomposition.FastICA` now validates input parameters in `fit` instead of `__init__`.\n :pr:`<PRID>` by :user:`<NAME>` and :user:`<NAME>`.\n- \n+\n - |Fix| :class:`decomposition.FactorAnalysis` now validates input parameters\n in `fit` instead of `__init__`.\n- :pr:`<PRID>` by :user:`<NAME>` and \n+ :pr:`<PRID>` by :user:`<NAME>` and\n :user:`<NAME>`.\n \n - |Fix| :class:`decomposition.KernelPCA` now validates input parameters in\n@@ -257,6 +257,10 @@ Changelog\n message when running in a jupyter notebook that is not trusted. :pr:`<PRID>`\n by `<NAME>`_.\n \n+- |Enhancement| :func:`utils.estimator_html_repr` displays an arrow on the top\n+ left corner of the HTML representation to show how the elements are\n+ clickable. :pr:`<PRID>` by `<NAME>`_.\n+\n :mod:`sklearn.neighbors`\n ........................\n \n" } ]
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index f755aeba20030..7792fa14b13a5 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -113,10 +113,10 @@ Changelog - |Fix| :class:`decomposition.FastICA` now validates input parameters in `fit` instead of `__init__`. :pr:`<PRID>` by :user:`<NAME>` and :user:`<NAME>`. - + - |Fix| :class:`decomposition.FactorAnalysis` now validates input parameters in `fit` instead of `__init__`. - :pr:`<PRID>` by :user:`<NAME>` and + :pr:`<PRID>` by :user:`<NAME>` and :user:`<NAME>`. - |Fix| :class:`decomposition.KernelPCA` now validates input parameters in @@ -257,6 +257,10 @@ Changelog message when running in a jupyter notebook that is not trusted. :pr:`<PRID>` by `<NAME>`_. +- |Enhancement| :func:`utils.estimator_html_repr` displays an arrow on the top + left corner of the HTML representation to show how the elements are + clickable. :pr:`<PRID>` by `<NAME>`_. + :mod:`sklearn.neighbors` ........................
scikit-learn/scikit-learn
scikit-learn__scikit-learn-20880
https://github.com/scikit-learn/scikit-learn/pull/20880
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 1639b4b691c65..fba40e25a9e7e 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -38,9 +38,20 @@ Changelog :pr:`123456` by :user:`Joe Bloggs <joeongithub>`. where 123456 is the *pull request* number, not the issue number. - -:mod:`sklearn.decomposition` -............................ +:mod:`sklearn.utils` +.................... + +- |Enhancement| :func:`utils.validation._check_sample_weight` can perform a + non-negativity check on the sample weights. It can be turned on + using the only_non_negative bool parameter. + Estimators that check for non-negative weights are updated: + :func:`linear_model.LinearRegression` (here the previous + error message was misleading), + :func:`ensemble.AdaBoostClassifier`, + :func:`ensemble.AdaBoostRegressor`, + :func:`neighbors.KernelDensity`. + :pr:`20880` by :user:`Guillaume Lemaitre <glemaitre>` + and :user:`András Simon <simonandras>`. Code and Documentation Contributors diff --git a/sklearn/ensemble/_weight_boosting.py b/sklearn/ensemble/_weight_boosting.py index 77ef449ba1933..a47937880d91c 100644 --- a/sklearn/ensemble/_weight_boosting.py +++ b/sklearn/ensemble/_weight_boosting.py @@ -123,10 +123,10 @@ def fit(self, X, y, sample_weight=None): y_numeric=is_regressor(self), ) - sample_weight = _check_sample_weight(sample_weight, X, np.float64, copy=True) + sample_weight = _check_sample_weight( + sample_weight, X, np.float64, copy=True, only_non_negative=True + ) sample_weight /= sample_weight.sum() - if np.any(sample_weight < 0): - raise ValueError("sample_weight cannot contain negative weights") # Check parameters self._validate_estimator() @@ -136,7 +136,7 @@ def fit(self, X, y, sample_weight=None): self.estimator_weights_ = np.zeros(self.n_estimators, dtype=np.float64) self.estimator_errors_ = np.ones(self.n_estimators, dtype=np.float64) - # Initializion of the random number instance that will be used to + # Initialization of the random number instance that will be used to # generate a seed at each iteration random_state = check_random_state(self.random_state) diff --git a/sklearn/linear_model/_base.py b/sklearn/linear_model/_base.py index 79d6f321cb124..8b5102ecdd403 100644 --- a/sklearn/linear_model/_base.py +++ b/sklearn/linear_model/_base.py @@ -663,7 +663,9 @@ def fit(self, X, y, sample_weight=None): ) if sample_weight is not None: - sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype) + sample_weight = _check_sample_weight( + sample_weight, X, dtype=X.dtype, only_non_negative=True + ) X, y, X_offset, y_offset, X_scale = self._preprocess_data( X, diff --git a/sklearn/neighbors/_kde.py b/sklearn/neighbors/_kde.py index 328a13371bafd..0ac0ea7226b90 100644 --- a/sklearn/neighbors/_kde.py +++ b/sklearn/neighbors/_kde.py @@ -191,9 +191,9 @@ def fit(self, X, y=None, sample_weight=None): X = self._validate_data(X, order="C", dtype=DTYPE) if sample_weight is not None: - sample_weight = _check_sample_weight(sample_weight, X, DTYPE) - if sample_weight.min() <= 0: - raise ValueError("sample_weight must have positive values") + sample_weight = _check_sample_weight( + sample_weight, X, DTYPE, only_non_negative=True + ) kwargs = self.metric_params if kwargs is None: diff --git a/sklearn/utils/validation.py b/sklearn/utils/validation.py index 87f957b931073..d45f246b233f8 100644 --- a/sklearn/utils/validation.py +++ b/sklearn/utils/validation.py @@ -1492,7 +1492,9 @@ def _check_psd_eigenvalues(lambdas, enable_warnings=False): return lambdas -def _check_sample_weight(sample_weight, X, dtype=None, copy=False): +def _check_sample_weight( + sample_weight, X, dtype=None, copy=False, only_non_negative=False +): """Validate sample weights. Note that passing sample_weight=None will output an array of ones. @@ -1503,17 +1505,22 @@ def _check_sample_weight(sample_weight, X, dtype=None, copy=False): Parameters ---------- sample_weight : {ndarray, Number or None}, shape (n_samples,) - Input sample weights. + Input sample weights. X : {ndarray, list, sparse matrix} Input data. + only_non_negative : bool, default=False, + Whether or not the weights are expected to be non-negative. + + .. versionadded:: 1.0 + dtype : dtype, default=None - dtype of the validated `sample_weight`. - If None, and the input `sample_weight` is an array, the dtype of the - input is preserved; otherwise an array with the default numpy dtype - is be allocated. If `dtype` is not one of `float32`, `float64`, - `None`, the output will be of dtype `float64`. + dtype of the validated `sample_weight`. + If None, and the input `sample_weight` is an array, the dtype of the + input is preserved; otherwise an array with the default numpy dtype + is be allocated. If `dtype` is not one of `float32`, `float64`, + `None`, the output will be of dtype `float64`. copy : bool, default=False If True, a copy of sample_weight will be created. @@ -1521,7 +1528,7 @@ def _check_sample_weight(sample_weight, X, dtype=None, copy=False): Returns ------- sample_weight : ndarray of shape (n_samples,) - Validated sample weight. It is guaranteed to be "C" contiguous. + Validated sample weight. It is guaranteed to be "C" contiguous. """ n_samples = _num_samples(X) @@ -1553,6 +1560,9 @@ def _check_sample_weight(sample_weight, X, dtype=None, copy=False): ) ) + if only_non_negative: + check_non_negative(sample_weight, "`sample_weight`") + return sample_weight
diff --git a/sklearn/ensemble/tests/test_weight_boosting.py b/sklearn/ensemble/tests/test_weight_boosting.py index 6927d47c11cfe..159f83abf24c4 100755 --- a/sklearn/ensemble/tests/test_weight_boosting.py +++ b/sklearn/ensemble/tests/test_weight_boosting.py @@ -576,6 +576,6 @@ def test_adaboost_negative_weight_error(model, X, y): sample_weight = np.ones_like(y) sample_weight[-1] = -10 - err_msg = "sample_weight cannot contain negative weight" + err_msg = "Negative values in data passed to `sample_weight`" with pytest.raises(ValueError, match=err_msg): model.fit(X, y, sample_weight=sample_weight) diff --git a/sklearn/neighbors/tests/test_kde.py b/sklearn/neighbors/tests/test_kde.py index 84f7623c8dbf1..d4fb775c44826 100644 --- a/sklearn/neighbors/tests/test_kde.py +++ b/sklearn/neighbors/tests/test_kde.py @@ -209,7 +209,7 @@ def test_sample_weight_invalid(): data = np.reshape([1.0, 2.0, 3.0], (-1, 1)) sample_weight = [0.1, -0.2, 0.3] - expected_err = "sample_weight must have positive values" + expected_err = "Negative values in data passed to `sample_weight`" with pytest.raises(ValueError, match=expected_err): kde.fit(data, sample_weight=sample_weight) diff --git a/sklearn/utils/tests/test_validation.py b/sklearn/utils/tests/test_validation.py index d1409d6129812..2cbbaac35a31b 100644 --- a/sklearn/utils/tests/test_validation.py +++ b/sklearn/utils/tests/test_validation.py @@ -52,8 +52,8 @@ FLOAT_DTYPES, _get_feature_names, _check_feature_names_in, + _check_fit_params, ) -from sklearn.utils.validation import _check_fit_params from sklearn.base import BaseEstimator import sklearn @@ -1253,6 +1253,14 @@ def test_check_sample_weight(): sample_weight = _check_sample_weight(None, X, dtype=X.dtype) assert sample_weight.dtype == np.float64 + # check negative weight when only_non_negative=True + X = np.ones((5, 2)) + sample_weight = np.ones(_num_samples(X)) + sample_weight[-1] = -10 + err_msg = "Negative values in data passed to `sample_weight`" + with pytest.raises(ValueError, match=err_msg): + _check_sample_weight(sample_weight, X, only_non_negative=True) + @pytest.mark.parametrize("toarray", [np.array, sp.csr_matrix, sp.csc_matrix]) def test_allclose_dense_sparse_equals(toarray):
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 1639b4b691c65..fba40e25a9e7e 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -38,9 +38,20 @@ Changelog\n :pr:`123456` by :user:`Joe Bloggs <joeongithub>`.\n where 123456 is the *pull request* number, not the issue number.\n \n-\n-:mod:`sklearn.decomposition`\n-............................\n+:mod:`sklearn.utils`\n+....................\n+\n+- |Enhancement| :func:`utils.validation._check_sample_weight` can perform a\n+ non-negativity check on the sample weights. It can be turned on\n+ using the only_non_negative bool parameter.\n+ Estimators that check for non-negative weights are updated:\n+ :func:`linear_model.LinearRegression` (here the previous\n+ error message was misleading),\n+ :func:`ensemble.AdaBoostClassifier`,\n+ :func:`ensemble.AdaBoostRegressor`,\n+ :func:`neighbors.KernelDensity`.\n+ :pr:`20880` by :user:`Guillaume Lemaitre <glemaitre>`\n+ and :user:`András Simon <simonandras>`.\n \n \n Code and Documentation Contributors\n" } ]
1.01
89d66b39a0949c01beee5eb9739e192b8bcac7bd
[ "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_raise_exception[csr]", "sklearn/neighbors/tests/test_kde.py::test_kernel_density[0.01-linear]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[tuple-float]", "sklearn/utils/tests/test_validation.py::test_check_sparse_pandas_sp_format[True]", "sklearn/utils/tests/test_validation.py::test_check_array_memmap[True]", "sklearn/utils/tests/test_validation.py::test_num_features[list]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_scalars[str]", "sklearn/utils/tests/test_validation.py::test_check_non_negative[bsr_matrix]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[byte-uint16]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[False-X0-Input contains NaN, infinity or a value too large for.*int]", "sklearn/neighbors/tests/test_kde.py::test_kde_algorithm_metric_choice[euclidean-kd_tree]", "sklearn/utils/tests/test_validation.py::test_check_non_negative[csr_matrix]", "sklearn/ensemble/tests/test_weight_boosting.py::test_staged_predict[SAMME.R]", "sklearn/ensemble/tests/test_weight_boosting.py::test_classification_toy[SAMME]", "sklearn/utils/tests/test_validation.py::test_check_non_negative[asarray]", "sklearn/neighbors/tests/test_kde.py::test_kernel_density[0.01-gaussian]", "sklearn/neighbors/tests/test_kde.py::test_kernel_density[0.01-tophat]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[series-float]", "sklearn/utils/tests/test_validation.py::test_check_is_fitted_with_attributes[tuple]", "sklearn/ensemble/tests/test_weight_boosting.py::test_error", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[list-float]", "sklearn/neighbors/tests/test_kde.py::test_kde_badargs", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[float64-float64-Int16]", "sklearn/utils/tests/test_validation.py::test_check_array_dtype_numeric_errors[X2]", "sklearn/utils/tests/test_validation.py::test_check_array_numeric_warns[X4]", "sklearn/utils/tests/test_validation.py::test_num_features[array]", "sklearn/utils/tests/test_validation.py::test_check_sparse_pandas_sp_format[coo]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[int32-long]", "sklearn/neighbors/tests/test_kde.py::test_kde_algorithm_metric_choice[minkowski-auto]", "sklearn/utils/tests/test_validation.py::test_check_array_dtype_numeric_errors[X3]", "sklearn/neighbors/tests/test_kde.py::test_pickling[sample_weight1]", "sklearn/neighbors/tests/test_kde.py::test_check_is_fitted[score_samples]", "sklearn/utils/tests/test_validation.py::test_as_float_array", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[uint8-int8]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[int16-int32]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[array-int]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_valid[asarray-nan-allow-nan]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_valid[asarray-inf-False]", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_valid[True-insignificant neg float64]", "sklearn/neighbors/tests/test_kde.py::test_kde_algorithm_metric_choice[chebyshev-ball_tree]", "sklearn/neighbors/tests/test_kde.py::test_kernel_density[0.01-epanechnikov]", "sklearn/utils/tests/test_validation.py::test_deprecate_positional_args_warns_for_class", "sklearn/neighbors/tests/test_kde.py::test_kernel_density_sampling", "sklearn/utils/tests/test_validation.py::test_check_scalar_invalid[1-test_name1-float-2-4-neither-err_msg0]", "sklearn/neighbors/tests/test_kde.py::test_kde_sample_weights", "sklearn/utils/tests/test_validation.py::test_check_non_negative[dok_matrix]", "sklearn/neighbors/tests/test_kde.py::test_kernel_density[0.1-exponential]", "sklearn/ensemble/tests/test_weight_boosting.py::test_importances", "sklearn/utils/tests/test_validation.py::test_get_feature_names_invalid_dtypes_warns[multi-index]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_valid[csr_matrix-nan-allow-nan]", "sklearn/neighbors/tests/test_kde.py::test_kernel_density[1-cosine]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_no_exception[coo]", "sklearn/ensemble/tests/test_weight_boosting.py::test_adaboost_consistent_predict[SAMME]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[uint-uint64-unsignedinteger]", "sklearn/utils/tests/test_validation.py::test_check_array_series", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[int8-byte-integer]", "sklearn/utils/tests/test_validation.py::test_num_features[sparse_csr]", "sklearn/neighbors/tests/test_kde.py::test_kernel_density[1-tophat]", "sklearn/neighbors/tests/test_kde.py::test_kde_algorithm_metric_choice[chebyshev-auto]", "sklearn/utils/tests/test_validation.py::test_check_array_dtype_numeric_errors[X0]", "sklearn/utils/tests/test_validation.py::test_check_X_y_informative_error", "sklearn/utils/tests/test_validation.py::test_check_feature_names_in", "sklearn/utils/tests/test_validation.py::test_num_features_errors_scalars[float]", "sklearn/neighbors/tests/test_kde.py::test_kde_algorithm_metric_choice[minkowski-kd_tree]", "sklearn/ensemble/tests/test_weight_boosting.py::test_regression_toy", "sklearn/neighbors/tests/test_kde.py::test_kde_score", "sklearn/ensemble/tests/test_weight_boosting.py::test_diabetes[linear]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_sparse_no_exception", "sklearn/utils/tests/test_validation.py::test_check_sparse_pandas_sp_format[csr]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[array-str]", "sklearn/utils/tests/test_validation.py::test_check_array_dtype_numeric_errors[X1]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_no_exception[bsr]", "sklearn/ensemble/tests/test_weight_boosting.py::test_sparse_regression", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[list-int]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[asarray-nan-True-Input contains NaN, infinity]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[tuple-str]", "sklearn/ensemble/tests/test_weight_boosting.py::test_sparse_classification", "sklearn/utils/tests/test_validation.py::test_np_matrix", "sklearn/neighbors/tests/test_kde.py::test_kernel_density[0.1-gaussian]", "sklearn/ensemble/tests/test_weight_boosting.py::test_diabetes[exponential]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[True-X0-Input contains NaN, infinity or a value too large for.*int]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_raise_exception[csc]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[intc-int32-integer]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[tuple-bool]", "sklearn/neighbors/tests/test_kde.py::test_kernel_density[0.1-tophat]", "sklearn/ensemble/tests/test_weight_boosting.py::test_samme_proba", "sklearn/utils/tests/test_validation.py::test_check_non_negative[lil_matrix]", "sklearn/neighbors/tests/test_kde.py::test_kde_algorithm_metric_choice[manhattan-auto]", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_raise[csc_matrix]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[csr_matrix-nan-1-Input contains NaN, infinity]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[dtype0-float32-Int16]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_no_exception[csc]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_valid[csr_matrix-inf-False]", "sklearn/utils/tests/test_validation.py::test_check_is_fitted_with_is_fitted", "sklearn/ensemble/tests/test_weight_boosting.py::test_adaboostregressor_sample_weight", "sklearn/utils/tests/test_validation.py::test_check_array_numeric_warns[X3]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[array-float]", "sklearn/ensemble/tests/test_weight_boosting.py::test_diabetes[square]", "sklearn/ensemble/tests/test_weight_boosting.py::test_classification_toy[SAMME.R]", "sklearn/utils/tests/test_validation.py::test_as_float_array_nan[X1]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[int64-longlong-integer]", "sklearn/utils/tests/test_validation.py::test_check_array_numeric_warns[X1]", "sklearn/neighbors/tests/test_kde.py::test_kernel_density[1-gaussian]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[tuple-dict]", "sklearn/neighbors/tests/test_kde.py::test_kernel_density[0.01-cosine]", "sklearn/utils/tests/test_validation.py::test_suppress_validation", "sklearn/ensemble/tests/test_weight_boosting.py::test_iris", "sklearn/utils/tests/test_validation.py::test_check_is_fitted_attributes", "sklearn/neighbors/tests/test_kde.py::test_kde_algorithm_metric_choice[haversine-auto]", "sklearn/utils/tests/test_validation.py::test_num_features[tuple]", "sklearn/neighbors/tests/test_kde.py::test_kernel_density[0.01-exponential]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[csr_matrix-nan-True-Input contains NaN, infinity]", "sklearn/utils/tests/test_validation.py::test_deprecate_positional_args_warns_for_function", "sklearn/utils/tests/test_validation.py::test_num_features[dataframe]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[float64-float64-UInt16]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[False-X2-Input contains NaN, infinity or a value too large for.*int]", "sklearn/utils/tests/test_validation.py::test_check_array_deprecated_matrix", "sklearn/utils/tests/test_validation.py::test_num_features[sparse_csc]", "sklearn/utils/tests/test_validation.py::test_check_array_dtype_warning", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_valid[asarray-nan-False]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[dtype0-float32-UInt8]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[uintc-uint32-unsignedinteger]", "sklearn/neighbors/tests/test_kde.py::test_kde_pipeline_gridsearch", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_equals[array]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[False-X3-cannot convert float NaN to integer]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[numeric-float64-UInt16]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[uint32-uint64]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[list-str]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_no_exception[csr]", "sklearn/neighbors/tests/test_kde.py::test_pickling[None]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[series-dict]", "sklearn/utils/tests/test_validation.py::test_check_sparse_pandas_sp_format[bsr]", "sklearn/utils/tests/test_validation.py::test_check_scalar_invalid[5-test_name3-int-2-4-neither-err_msg2]", "sklearn/utils/tests/test_validation.py::test_check_array", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_valid[csr_matrix-nan-False]", "sklearn/utils/tests/test_validation.py::test_check_array_min_samples_and_features_messages", "sklearn/utils/tests/test_validation.py::test_check_is_fitted", "sklearn/neighbors/tests/test_kde.py::test_kernel_density[1-linear]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[dtype0-float32-Int8]", "sklearn/utils/tests/test_validation.py::test_check_fit_params[indices1]", "sklearn/utils/tests/test_validation.py::test_check_scalar_invalid[2-test_name4-int-2-4-right-err_msg3]", "sklearn/ensemble/tests/test_weight_boosting.py::test_pickle", "sklearn/utils/tests/test_validation.py::test_check_non_negative[coo_matrix]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[array-bool]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[True-X1-Input contains NaN, infinity or a value too large for.*int]", "sklearn/neighbors/tests/test_kde.py::test_kde_algorithm_metric_choice[euclidean-auto]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[list-dict]", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_valid[True-insignificant neg]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[asarray-inf-True-Input contains NaN, infinity]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object", "sklearn/neighbors/tests/test_kde.py::test_kde_algorithm_metric_choice[manhattan-kd_tree]", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_invalid[significant neg]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[tuple-int]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[csr_matrix-nan-allow-inf-force_all_finite should be a bool or \"allow-nan\"]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[True-X2-Input contains NaN, infinity or a value too large for.*int]", "sklearn/utils/tests/test_validation.py::test_check_is_fitted_with_attributes[list]", "sklearn/neighbors/tests/test_kde.py::test_kde_algorithm_metric_choice[manhattan-ball_tree]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[dtype0-float32-UInt16]", "sklearn/utils/tests/test_validation.py::test_check_sparse_pandas_sp_format[csc]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[asarray-nan-allow-inf-force_all_finite should be a bool or \"allow-nan\"]", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_raise[csr_matrix]", "sklearn/neighbors/tests/test_kde.py::test_kernel_density[1-exponential]", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_valid[True-insignificant_imag]", "sklearn/utils/tests/test_validation.py::test_deprecate_positional_args_warns_for_function_version", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_invalid[significant neg float32]", "sklearn/utils/tests/test_validation.py::test_check_array_complex_data_error", "sklearn/neighbors/tests/test_kde.py::test_kernel_density[0.1-cosine]", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_not_equals[array]", "sklearn/utils/tests/test_validation.py::test_check_non_negative[csc_matrix]", "sklearn/utils/tests/test_validation.py::test_retrieve_samples_from_non_standard_shape", "sklearn/utils/tests/test_validation.py::test_get_feature_names_numpy", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[array-dict]", "sklearn/utils/tests/test_validation.py::test_check_scalar_invalid[4-test_name5-int-2-4-left-err_msg4]", "sklearn/ensemble/tests/test_weight_boosting.py::test_adaboostclassifier_without_sample_weight[SAMME]", "sklearn/utils/tests/test_validation.py::test_as_float_array_nan[X0]", "sklearn/utils/tests/test_validation.py::test_check_array_numeric_warns[X0]", "sklearn/utils/tests/test_validation.py::test_memmap", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_raise_exception[bsr]", "sklearn/utils/tests/test_validation.py::test_check_consistent_length", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[float64-float64-UInt8]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[int0-long-integer]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[uint16-ushort-unsignedinteger]", "sklearn/ensemble/tests/test_weight_boosting.py::test_adaboostclassifier_without_sample_weight[SAMME.R]", "sklearn/ensemble/tests/test_weight_boosting.py::test_multidimensional_X", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[asarray-nan-1-Input contains NaN, infinity]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[asarray-inf-allow-nan-Input contains infinity]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[float64-float64-Int8]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[int-long-integer]", "sklearn/ensemble/tests/test_weight_boosting.py::test_adaboost_consistent_predict[SAMME.R]", "sklearn/ensemble/tests/test_weight_boosting.py::test_sample_weights_infinite", "sklearn/neighbors/tests/test_kde.py::test_kde_algorithm_metric_choice[chebyshev-kd_tree]", "sklearn/ensemble/tests/test_weight_boosting.py::test_sample_weight_adaboost_regressor", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_dtype_casting", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[numeric-float64-Int8]", "sklearn/utils/tests/test_validation.py::test_check_non_negative[dia_matrix]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[list-bool]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[series-bool]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_scalars[bool]", "sklearn/neighbors/tests/test_kde.py::test_kde_algorithm_metric_choice[haversine-kd_tree]", "sklearn/utils/tests/test_validation.py::test_check_array_numeric_warns[X2]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_dtype_object_conversion", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_invalid[all negative]", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_valid[True-insignificant pos]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[series-str]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[csr_matrix-inf-True-Input contains NaN, infinity]", "sklearn/utils/tests/test_validation.py::test_has_fit_parameter", "sklearn/utils/tests/test_validation.py::test_num_features_errors_scalars[int]", "sklearn/neighbors/tests/test_kde.py::test_check_is_fitted[sample]", "sklearn/utils/tests/test_validation.py::test_check_fit_params[None]", "sklearn/utils/tests/test_validation.py::test_check_array_memmap[False]", "sklearn/neighbors/tests/test_kde.py::test_kernel_density[0.1-epanechnikov]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[True-X3-cannot convert float NaN to integer]", "sklearn/ensemble/tests/test_weight_boosting.py::test_base_estimator", "sklearn/ensemble/tests/test_weight_boosting.py::test_staged_predict[SAMME]", "sklearn/utils/tests/test_validation.py::test_get_feature_names_invalid_dtypes_warns[mixed]", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_equals[csr_matrix]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[ushort-uint32]", "sklearn/utils/tests/test_validation.py::test_check_symmetric", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[uintp-ulonglong-unsignedinteger]", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_invalid[significant_imag]", "sklearn/utils/tests/test_validation.py::test_check_is_fitted_with_attributes[single]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[series-int]", "sklearn/neighbors/tests/test_kde.py::test_kernel_density[1-epanechnikov]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[csr_matrix-inf-allow-nan-Input contains infinity]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_raise_exception[coo]", "sklearn/utils/tests/test_validation.py::test_ordering", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_not_equals[csr_matrix]", "sklearn/utils/tests/test_validation.py::test_check_array_on_mock_dataframe", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_equals[csc_matrix]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_sparse_type_exception", "sklearn/utils/tests/test_validation.py::test_check_scalar_invalid[4-test_name6-int-2-4-bad parameter value-err_msg5]", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_invalid[significant neg float64]", "sklearn/ensemble/tests/test_weight_boosting.py::test_oneclass_adaboost_proba", "sklearn/utils/tests/test_validation.py::test_check_feature_names_in_pandas", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[int_-intp-integer]", "sklearn/utils/tests/test_validation.py::test_check_dataframe_fit_attribute", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[ubyte-uint8-unsignedinteger]", "sklearn/utils/tests/test_validation.py::test_check_scalar_invalid[1-test_name2-int-2-4-neither-err_msg1]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[numeric-float64-UInt8]", "sklearn/neighbors/tests/test_kde.py::test_kde_algorithm_metric_choice[haversine-ball_tree]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[False-X1-Input contains NaN, infinity or a value too large for.*int]", "sklearn/utils/tests/test_validation.py::test_check_dataframe_mixed_float_dtypes", "sklearn/neighbors/tests/test_kde.py::test_kernel_density[0.1-linear]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[short-int16-integer]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[numeric-float64-Int16]", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_not_equals[csc_matrix]", "sklearn/neighbors/tests/test_kde.py::test_kde_algorithm_metric_choice[euclidean-ball_tree]", "sklearn/ensemble/tests/test_weight_boosting.py::test_gridsearch", "sklearn/utils/tests/test_validation.py::test_check_array_dtype_stability", "sklearn/neighbors/tests/test_kde.py::test_kde_algorithm_metric_choice[minkowski-ball_tree]", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_valid[True-insignificant neg float32]", "sklearn/utils/tests/test_validation.py::test_get_feature_names_pandas" ]
[ "sklearn/ensemble/tests/test_weight_boosting.py::test_adaboost_negative_weight_error[model0-X0-y0]", "sklearn/ensemble/tests/test_weight_boosting.py::test_adaboost_negative_weight_error[model1-X1-y1]", "sklearn/utils/tests/test_validation.py::test_check_sample_weight", "sklearn/neighbors/tests/test_kde.py::test_sample_weight_invalid" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 1639b4b691c65..fba40e25a9e7e 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -38,9 +38,20 @@ Changelog\n :pr:`<PRID>` by :user:`<NAME>`.\n where <PRID> is the *pull request* number, not the issue number.\n \n-\n-:mod:`sklearn.decomposition`\n-............................\n+:mod:`sklearn.utils`\n+....................\n+\n+- |Enhancement| :func:`utils.validation._check_sample_weight` can perform a\n+ non-negativity check on the sample weights. It can be turned on\n+ using the only_non_negative bool parameter.\n+ Estimators that check for non-negative weights are updated:\n+ :func:`linear_model.LinearRegression` (here the previous\n+ error message was misleading),\n+ :func:`ensemble.AdaBoostClassifier`,\n+ :func:`ensemble.AdaBoostRegressor`,\n+ :func:`neighbors.KernelDensity`.\n+ :pr:`<PRID>` by :user:`<NAME>`\n+ and :user:`<NAME>`.\n \n \n Code and Documentation Contributors\n" } ]
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 1639b4b691c65..fba40e25a9e7e 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -38,9 +38,20 @@ Changelog :pr:`<PRID>` by :user:`<NAME>`. where <PRID> is the *pull request* number, not the issue number. - -:mod:`sklearn.decomposition` -............................ +:mod:`sklearn.utils` +.................... + +- |Enhancement| :func:`utils.validation._check_sample_weight` can perform a + non-negativity check on the sample weights. It can be turned on + using the only_non_negative bool parameter. + Estimators that check for non-negative weights are updated: + :func:`linear_model.LinearRegression` (here the previous + error message was misleading), + :func:`ensemble.AdaBoostClassifier`, + :func:`ensemble.AdaBoostRegressor`, + :func:`neighbors.KernelDensity`. + :pr:`<PRID>` by :user:`<NAME>` + and :user:`<NAME>`. Code and Documentation Contributors
scikit-learn/scikit-learn
scikit-learn__scikit-learn-18393
https://github.com/scikit-learn/scikit-learn/pull/18393
diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index be894774f5a27..a54abb78730a4 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -102,6 +102,13 @@ Changelog - |Enhancement| :func:`datasets.fetch_kddcup99` raises a better message when the cached file is invalid. :pr:`19669` `Thomas Fan`_. +:mod:`sklearn.compose` +...................... + +- |Enhancement| :class:`compose.ColumnTransformer` now records the output + of each transformer in `output_indices_`. :pr:`18393` by + :user:`Luca Bittarello <lbittarello>`. + :mod:`sklearn.decomposition` ............................ diff --git a/sklearn/compose/_column_transformer.py b/sklearn/compose/_column_transformer.py index c0444fe2d6cda..da4a2dd93507c 100644 --- a/sklearn/compose/_column_transformer.py +++ b/sklearn/compose/_column_transformer.py @@ -134,6 +134,12 @@ class ColumnTransformer(TransformerMixin, _BaseComposition): sparse matrix or a dense numpy array, which depends on the output of the individual transformers and the `sparse_threshold` keyword. + output_indices_ : dict + A dictionary from each transformer name to a slice, where the slice + corresponds to indices in the transformed output. This is useful to + inspect which transformer is responsible for which transformed + feature(s). + Notes ----- The order of the columns in the transformed feature matrix follows the @@ -408,6 +414,28 @@ def _validate_output(self, result): "The output of the '{0}' transformer should be 2D (scipy " "matrix, array, or pandas DataFrame).".format(name)) + def _record_output_indices(self, Xs): + """ + Record which transformer produced which column. + """ + idx = 0 + self.output_indices_ = {} + + for transformer_idx, (name, _, _, _) in enumerate( + self._iter(fitted=True, replace_strings=True) + ): + n_columns = Xs[transformer_idx].shape[1] + self.output_indices_[name] = slice(idx, idx + n_columns) + idx += n_columns + + # `_iter` only generates transformers that have a non empty + # selection. Here we set empty slices for transformers that + # generate no output, which are safe for indexing + all_names = [t[0] for t in self.transformers] + ['remainder'] + for name in all_names: + if name not in self.output_indices_: + self.output_indices_[name] = slice(0, 0) + def _log_message(self, name, idx, total): if not self.verbose: return None @@ -518,6 +546,7 @@ def fit_transform(self, X, y=None): self._update_fitted_transformers(transformers) self._validate_output(Xs) + self._record_output_indices(Xs) return self._hstack(list(Xs))
diff --git a/sklearn/compose/tests/test_column_transformer.py b/sklearn/compose/tests/test_column_transformer.py index ae2e25b68210f..f7c1874d4a1b7 100644 --- a/sklearn/compose/tests/test_column_transformer.py +++ b/sklearn/compose/tests/test_column_transformer.py @@ -225,7 +225,7 @@ def test_column_transformer_dataframe(): assert len(both.transformers_) == 1 assert both.transformers_[-1][0] != 'remainder' - # ensure pandas object is passes through + # ensure pandas object is passed through class TransAssert(BaseEstimator): @@ -310,6 +310,92 @@ def test_column_transformer_empty_columns(pandas, column_selection, assert isinstance(ct.transformers_[0][1], TransRaise) +def test_column_transformer_output_indices(): + # Checks for the output_indices_ attribute + X_array = np.arange(6).reshape(3, 2) + + ct = ColumnTransformer([('trans1', Trans(), [0]), + ('trans2', Trans(), [1])]) + X_trans = ct.fit_transform(X_array) + assert ct.output_indices_ == {'trans1': slice(0, 1), + 'trans2': slice(1, 2), + 'remainder': slice(0, 0)} + assert_array_equal(X_trans[:, [0]], + X_trans[:, ct.output_indices_['trans1']]) + assert_array_equal(X_trans[:, [1]], + X_trans[:, ct.output_indices_['trans2']]) + + # test with transformer_weights and multiple columns + ct = ColumnTransformer([('trans', Trans(), [0, 1])], + transformer_weights={'trans': .1}) + X_trans = ct.fit_transform(X_array) + assert ct.output_indices_ == {'trans': slice(0, 2), + 'remainder': slice(0, 0)} + assert_array_equal(X_trans[:, [0, 1]], + X_trans[:, ct.output_indices_['trans']]) + assert_array_equal(X_trans[:, []], + X_trans[:, ct.output_indices_['remainder']]) + + # test case that ensures that the attribute does also work when + # a given transformer doesn't have any columns to work on + ct = ColumnTransformer([('trans1', Trans(), [0, 1]), + ('trans2', TransRaise(), [])]) + X_trans = ct.fit_transform(X_array) + assert ct.output_indices_ == {'trans1': slice(0, 2), + 'trans2': slice(0, 0), + 'remainder': slice(0, 0)} + assert_array_equal(X_trans[:, [0, 1]], + X_trans[:, ct.output_indices_['trans1']]) + assert_array_equal(X_trans[:, []], + X_trans[:, ct.output_indices_['trans2']]) + assert_array_equal(X_trans[:, []], + X_trans[:, ct.output_indices_['remainder']]) + + ct = ColumnTransformer([('trans', TransRaise(), [])], + remainder='passthrough') + X_trans = ct.fit_transform(X_array) + assert ct.output_indices_ == {'trans': slice(0, 0), + 'remainder': slice(0, 2)} + assert_array_equal(X_trans[:, []], + X_trans[:, ct.output_indices_['trans']]) + assert_array_equal(X_trans[:, [0, 1]], + X_trans[:, ct.output_indices_['remainder']]) + + +def test_column_transformer_output_indices_df(): + # Checks for the output_indices_ attribute with data frames + pd = pytest.importorskip('pandas') + + X_df = pd.DataFrame(np.arange(6).reshape(3, 2), + columns=['first', 'second']) + + ct = ColumnTransformer([('trans1', Trans(), ['first']), + ('trans2', Trans(), ['second'])]) + X_trans = ct.fit_transform(X_df) + assert ct.output_indices_ == {'trans1': slice(0, 1), + 'trans2': slice(1, 2), + 'remainder': slice(0, 0)} + assert_array_equal(X_trans[:, [0]], + X_trans[:, ct.output_indices_['trans1']]) + assert_array_equal(X_trans[:, [1]], + X_trans[:, ct.output_indices_['trans2']]) + assert_array_equal(X_trans[:, []], + X_trans[:, ct.output_indices_['remainder']]) + + ct = ColumnTransformer([('trans1', Trans(), [0]), + ('trans2', Trans(), [1])]) + X_trans = ct.fit_transform(X_df) + assert ct.output_indices_ == {'trans1': slice(0, 1), + 'trans2': slice(1, 2), + 'remainder': slice(0, 0)} + assert_array_equal(X_trans[:, [0]], + X_trans[:, ct.output_indices_['trans1']]) + assert_array_equal(X_trans[:, [1]], + X_trans[:, ct.output_indices_['trans2']]) + assert_array_equal(X_trans[:, []], + X_trans[:, ct.output_indices_['remainder']]) + + def test_column_transformer_sparse_array(): X_sparse = sparse.eye(3, 2).tocsr()
[ { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex be894774f5a27..a54abb78730a4 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -102,6 +102,13 @@ Changelog\n - |Enhancement| :func:`datasets.fetch_kddcup99` raises a better message\n when the cached file is invalid. :pr:`19669` `Thomas Fan`_.\n \n+:mod:`sklearn.compose`\n+......................\n+\n+- |Enhancement| :class:`compose.ColumnTransformer` now records the output\n+ of each transformer in `output_indices_`. :pr:`18393` by\n+ :user:`Luca Bittarello <lbittarello>`.\n+\n :mod:`sklearn.decomposition`\n ............................\n \n" } ]
1.00
114616d9f6ce9eba7c1aacd3d4a254f868010e25
[ "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_verbose[fit_transform-est5-\\\\[ColumnTransformer\\\\].*\\\\(1 of 2\\\\) Processing trans1.* total=.*\\\\n\\\\[ColumnTransformer\\\\].*\\\\(2 of 2\\\\) Processing trans2.* total=.*\\\\n$]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_remainder_pandas[key0]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_empty_columns[True-bool-pandas]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_verbose[fit-est2-\\\\[ColumnTransformer\\\\].*\\\\(1 of 2\\\\) Processing trans1.* total=.*\\\\n\\\\[ColumnTransformer\\\\].*\\\\(2 of 2\\\\) Processing remainder.* total=.*\\\\n$]", "sklearn/compose/tests/test_column_transformer.py::test_make_column_transformer_pandas", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_verbose[fit-est1-\\\\[ColumnTransformer\\\\].*\\\\(1 of 3\\\\) Processing trans1.* total=.*\\\\n\\\\[ColumnTransformer\\\\].*\\\\(2 of 3\\\\) Processing trans2.* total=.*\\\\n\\\\[ColumnTransformer\\\\].*\\\\(3 of 3\\\\) Processing remainder.* total=.*\\\\n$]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_no_estimators", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_empty_columns[True-bool_int-pandas]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_with_make_column_selector", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_remainder_pandas[key3]", "sklearn/compose/tests/test_column_transformer.py::test_sk_visual_block_remainder_fitted_pandas[passthrough]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_sparse_stacking", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_remainder_numpy[key0]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_get_feature_names_dataframe", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_verbose[fit_transform-est1-\\\\[ColumnTransformer\\\\].*\\\\(1 of 3\\\\) Processing trans1.* total=.*\\\\n\\\\[ColumnTransformer\\\\].*\\\\(2 of 3\\\\) Processing trans2.* total=.*\\\\n\\\\[ColumnTransformer\\\\].*\\\\(3 of 3\\\\) Processing remainder.* total=.*\\\\n$]", "sklearn/compose/tests/test_column_transformer.py::test_feature_names_empty_columns[callable]", "sklearn/compose/tests/test_column_transformer.py::test_make_column_selector_with_select_dtypes[cols10-^col_s-None-exclude10]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_sparse_array", "sklearn/compose/tests/test_column_transformer.py::test_2D_transformer_output_pandas", "sklearn/compose/tests/test_column_transformer.py::test_make_column_selector_with_select_dtypes[cols2-None-include2-None]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_sparse_threshold", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_remainder_pandas[key7]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_remainder_transformer[key2]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_get_set_params_with_remainder", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_mixed_cols_sparse", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_verbose[fit-est3-\\\\[ColumnTransformer\\\\].*\\\\(1 of 3\\\\) Processing trans1.* total=.*\\\\n\\\\[ColumnTransformer\\\\].*\\\\(2 of 3\\\\) Processing trans2.* total=.*\\\\n\\\\[ColumnTransformer\\\\].*\\\\(3 of 3\\\\) Processing remainder.* total=.*\\\\n$]", "sklearn/compose/tests/test_column_transformer.py::test_get_feature_names_empty_selection[selector0]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_mask_indexing[csr_matrix]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_negative_column_indexes", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_remainder_numpy[key3]", "sklearn/compose/tests/test_column_transformer.py::test_make_column_selector_with_select_dtypes[cols9-float|str-None-None]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_reordered_column_names_remainder[second]", "sklearn/compose/tests/test_column_transformer.py::test_sk_visual_block_remainder_fitted_numpy[passthrough]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_verbose[fit_transform-est0-\\\\[ColumnTransformer\\\\].*\\\\(1 of 3\\\\) Processing trans1.* total=.*\\\\n\\\\[ColumnTransformer\\\\].*\\\\(2 of 3\\\\) Processing trans2.* total=.*\\\\n\\\\[ColumnTransformer\\\\].*\\\\(3 of 3\\\\) Processing remainder.* total=.*\\\\n$]", "sklearn/compose/tests/test_column_transformer.py::test_2D_transformer_output", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_invalid_columns[passthrough]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_reordered_column_names_remainder[first]", "sklearn/compose/tests/test_column_transformer.py::test_sk_visual_block_remainder[passthrough]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_get_set_params", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_remainder_pandas[pd-index]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_verbose[fit_transform-est2-\\\\[ColumnTransformer\\\\].*\\\\(1 of 2\\\\) Processing trans1.* total=.*\\\\n\\\\[ColumnTransformer\\\\].*\\\\(2 of 2\\\\) Processing remainder.* total=.*\\\\n$]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_get_feature_names", "sklearn/compose/tests/test_column_transformer.py::test_make_column_selector_with_select_dtypes[cols8-^col_int-include8-None]", "sklearn/compose/tests/test_column_transformer.py::test_make_column_selector_with_select_dtypes[cols0-None-number-None]", "sklearn/compose/tests/test_column_transformer.py::test_sk_visual_block_remainder_fitted_numpy[remainder1]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_empty_columns[False-list-numpy]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_special_strings", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_sparse_remainder_transformer", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_remainder_pandas[key5]", "sklearn/compose/tests/test_column_transformer.py::test_n_features_in", "sklearn/compose/tests/test_column_transformer.py::test_make_column_selector_with_select_dtypes[cols6-at$-include6-None]", "sklearn/compose/tests/test_column_transformer.py::test_make_column_selector_with_select_dtypes[cols5-None-float-None]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_drop_all_sparse_remainder_transformer", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_empty_columns[True-list-numpy]", "sklearn/compose/tests/test_column_transformer.py::test_make_column_selector_error", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_invalid_transformer", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_empty_columns[False-bool_int-pandas]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_empty_columns[False-bool-pandas]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_remainder_transformer[key1]", "sklearn/compose/tests/test_column_transformer.py::test_make_column_selector_with_select_dtypes[cols4-None-object-None]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_invalid_columns[drop]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_remainder_numpy[key2]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_no_estimators_set_params", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_remainder_pandas[key8]", "sklearn/compose/tests/test_column_transformer.py::test_make_column_selector_with_select_dtypes[cols11-str$-float-None]", "sklearn/compose/tests/test_column_transformer.py::test_make_column_transformer", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_no_remaining_remainder_transformer", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_remainder_pandas[key2]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_empty_columns[True-bool-numpy]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_empty_columns[False-list-pandas]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_remainder_transformer[key0]", "sklearn/compose/tests/test_column_transformer.py::test_feature_name_validation", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_empty_columns[False-bool-numpy]", "sklearn/compose/tests/test_column_transformer.py::test_make_column_transformer_kwargs", "sklearn/compose/tests/test_column_transformer.py::test_feature_names_empty_columns[array]", "sklearn/compose/tests/test_column_transformer.py::test_get_feature_names_empty_selection[selector1]", "sklearn/compose/tests/test_column_transformer.py::test_make_column_selector_with_select_dtypes[cols12-None-include12-None]", "sklearn/compose/tests/test_column_transformer.py::test_make_column_transformer_remainder_transformer", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_callable_specifier_dataframe", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_empty_columns[False-bool_int-numpy]", "sklearn/compose/tests/test_column_transformer.py::test_make_column_selector_with_select_dtypes[cols1-None-None-object]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_named_estimators", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_verbose[fit_transform-est3-\\\\[ColumnTransformer\\\\].*\\\\(1 of 3\\\\) Processing trans1.* total=.*\\\\n\\\\[ColumnTransformer\\\\].*\\\\(2 of 3\\\\) Processing trans2.* total=.*\\\\n\\\\[ColumnTransformer\\\\].*\\\\(3 of 3\\\\) Processing remainder.* total=.*\\\\n$]", "sklearn/compose/tests/test_column_transformer.py::test_sk_visual_block_remainder[remainder1]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_empty_columns[True-bool_int-numpy]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_list", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_verbose[fit_transform-est6-\\\\[ColumnTransformer\\\\].*\\\\(1 of 1\\\\) Processing trans1.* total=.*\\\\n$]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_verbose[fit-est4-\\\\[ColumnTransformer\\\\].*\\\\(1 of 2\\\\) Processing trans1.* total=.*\\\\n\\\\[ColumnTransformer\\\\].*\\\\(2 of 2\\\\) Processing remainder.* total=.*\\\\n$]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_drops_all_remainder_transformer", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_remainder_transformer[key3]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_cloning", "sklearn/compose/tests/test_column_transformer.py::test_sk_visual_block_remainder_drop", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_remainder", "sklearn/compose/tests/test_column_transformer.py::test_make_column_selector_pickle", "sklearn/compose/tests/test_column_transformer.py::test_feature_names_empty_columns[list]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_callable_specifier", "sklearn/compose/tests/test_column_transformer.py::test_sk_visual_block_remainder_fitted_pandas[remainder1]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_remainder_numpy[key1]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_remainder_pandas[key1]", "sklearn/compose/tests/test_column_transformer.py::test_make_column_selector_with_select_dtypes[cols3-None-include3-None]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_verbose[fit-est0-\\\\[ColumnTransformer\\\\].*\\\\(1 of 3\\\\) Processing trans1.* total=.*\\\\n\\\\[ColumnTransformer\\\\].*\\\\(2 of 3\\\\) Processing trans2.* total=.*\\\\n\\\\[ColumnTransformer\\\\].*\\\\(3 of 3\\\\) Processing remainder.* total=.*\\\\n$]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_mask_indexing[asarray]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_dataframe", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_remainder_pandas[key6]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_error_msg_1D", "sklearn/compose/tests/test_column_transformer.py::test_make_column_selector_with_select_dtypes[cols7-None-include7-None]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_verbose[fit_transform-est4-\\\\[ColumnTransformer\\\\].*\\\\(1 of 2\\\\) Processing trans1.* total=.*\\\\n\\\\[ColumnTransformer\\\\].*\\\\(2 of 2\\\\) Processing remainder.* total=.*\\\\n$]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_verbose[fit-est5-\\\\[ColumnTransformer\\\\].*\\\\(1 of 2\\\\) Processing trans1.* total=.*\\\\n\\\\[ColumnTransformer\\\\].*\\\\(2 of 2\\\\) Processing trans2.* total=.*\\\\n$]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_verbose[fit-est6-\\\\[ColumnTransformer\\\\].*\\\\(1 of 1\\\\) Processing trans1.* total=.*\\\\n$]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_empty_columns[True-list-pandas]" ]
[ "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_output_indices", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_output_indices_df" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex be894774f5a27..a54abb78730a4 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -102,6 +102,13 @@ Changelog\n - |Enhancement| :func:`datasets.fetch_kddcup99` raises a better message\n when the cached file is invalid. :pr:`<PRID>` `Thomas Fan`_.\n \n+:mod:`sklearn.compose`\n+......................\n+\n+- |Enhancement| :class:`compose.ColumnTransformer` now records the output\n+ of each transformer in `output_indices_`. :pr:`<PRID>` by\n+ :user:`<NAME>`.\n+\n :mod:`sklearn.decomposition`\n ............................\n \n" } ]
diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index be894774f5a27..a54abb78730a4 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -102,6 +102,13 @@ Changelog - |Enhancement| :func:`datasets.fetch_kddcup99` raises a better message when the cached file is invalid. :pr:`<PRID>` `Thomas Fan`_. +:mod:`sklearn.compose` +...................... + +- |Enhancement| :class:`compose.ColumnTransformer` now records the output + of each transformer in `output_indices_`. :pr:`<PRID>` by + :user:`<NAME>`. + :mod:`sklearn.decomposition` ............................
scikit-learn/scikit-learn
scikit-learn__scikit-learn-22237
https://github.com/scikit-learn/scikit-learn/pull/22237
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 0acd0612dd0c7..332fbc33dd192 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -1048,6 +1048,11 @@ Changelog left corner of the HTML representation to show how the elements are clickable. :pr:`21298` by `Thomas Fan`_. +- |Enhancement| :func:`utils.check_array` with `dtype=None` returns numeric + arrays when passed in a pandas DataFrame with mixed dtypes. `dtype="numeric"` + will also make better infer the dtype when the DataFrame has mixed dtypes. + :pr:`22237` by `Thomas Fan`_. + - |Enhancement| Removes random unique identifiers in the HTML representation. With this change, jupyter notebooks are reproducible as long as the cells are run in the same order. :pr:`23098` by `Thomas Fan`_. diff --git a/sklearn/utils/validation.py b/sklearn/utils/validation.py index aba4e2b179953..2b5ce5b4f09ae 100644 --- a/sklearn/utils/validation.py +++ b/sklearn/utils/validation.py @@ -575,13 +575,25 @@ def _check_estimator_name(estimator): def _pandas_dtype_needs_early_conversion(pd_dtype): """Return True if pandas extension pd_dtype need to be converted early.""" + # Check these early for pandas versions without extension dtypes + from pandas.api.types import ( + is_bool_dtype, + is_sparse, + is_float_dtype, + is_integer_dtype, + ) + + if is_bool_dtype(pd_dtype): + # bool and extension booleans need early converstion because __array__ + # converts mixed dtype dataframes into object dtypes + return True + + if is_sparse(pd_dtype): + # Sparse arrays will be converted later in `check_array` + return False + try: - from pandas.api.types import ( - is_extension_array_dtype, - is_float_dtype, - is_integer_dtype, - is_sparse, - ) + from pandas.api.types import is_extension_array_dtype except ImportError: return False @@ -744,16 +756,10 @@ def check_array( "It will be converted to a dense numpy array." ) - dtypes_orig = [] - for dtype_iter in array.dtypes: - if dtype_iter.kind == "b": - # pandas boolean dtype __array__ interface coerces bools to objects - dtype_iter = np.dtype(object) - elif _pandas_dtype_needs_early_conversion(dtype_iter): - pandas_requires_conversion = True - - dtypes_orig.append(dtype_iter) - + dtypes_orig = list(array.dtypes) + pandas_requires_conversion = any( + _pandas_dtype_needs_early_conversion(i) for i in dtypes_orig + ) if all(isinstance(dtype_iter, np.dtype) for dtype_iter in dtypes_orig): dtype_orig = np.result_type(*dtypes_orig) @@ -776,7 +782,9 @@ def check_array( if pandas_requires_conversion: # pandas dataframe requires conversion earlier to handle extension dtypes with # nans - array = array.astype(dtype) + # Use the original dtype for conversion if dtype is None + new_dtype = dtype_orig if dtype is None else dtype + array = array.astype(new_dtype) # Since we converted here, we do not need to convert again later dtype = None
diff --git a/sklearn/utils/tests/test_validation.py b/sklearn/utils/tests/test_validation.py index 84a71a10981fb..391d9603d29de 100644 --- a/sklearn/utils/tests/test_validation.py +++ b/sklearn/utils/tests/test_validation.py @@ -924,26 +924,69 @@ def test_check_array_series(): assert_array_equal(res, np.array(["a", "b", "c"], dtype=object)) -def test_check_dataframe_mixed_float_dtypes(): [email protected]( + "dtype", ((np.float64, np.float32), np.float64, None, "numeric") +) [email protected]("bool_dtype", ("bool", "boolean")) +def test_check_dataframe_mixed_float_dtypes(dtype, bool_dtype): # pandas dataframe will coerce a boolean into a object, this is a mismatch # with np.result_type which will return a float # check_array needs to explicitly check for bool dtype in a dataframe for # this situation # https://github.com/scikit-learn/scikit-learn/issues/15787 - pd = importorskip("pandas") + if bool_dtype == "boolean": + # boolean extension arrays was introduced in 1.0 + pd = importorskip("pandas", minversion="1.0") + else: + pd = importorskip("pandas") + df = pd.DataFrame( - {"int": [1, 2, 3], "float": [0, 0.1, 2.1], "bool": [True, False, True]}, + { + "int": [1, 2, 3], + "float": [0, 0.1, 2.1], + "bool": pd.Series([True, False, True], dtype=bool_dtype), + }, columns=["int", "float", "bool"], ) - array = check_array(df, dtype=(np.float64, np.float32, np.float16)) + array = check_array(df, dtype=dtype) + assert array.dtype == np.float64 expected_array = np.array( [[1.0, 0.0, 1.0], [2.0, 0.1, 0.0], [3.0, 2.1, 1.0]], dtype=float ) assert_allclose_dense_sparse(array, expected_array) +def test_check_dataframe_with_only_bool(): + """Check that dataframe with bool return a boolean arrays.""" + pd = importorskip("pandas") + df = pd.DataFrame({"bool": [True, False, True]}) + + array = check_array(df, dtype=None) + assert array.dtype == np.bool_ + assert_array_equal(array, [[True], [False], [True]]) + + # common dtype is int for bool + int + df = pd.DataFrame( + {"bool": [True, False, True], "int": [1, 2, 3]}, + columns=["bool", "int"], + ) + array = check_array(df, dtype="numeric") + assert array.dtype == np.int64 + assert_array_equal(array, [[1, 1], [0, 2], [1, 3]]) + + +def test_check_dataframe_with_only_boolean(): + """Check that dataframe with boolean return a float array with dtype=None""" + pd = importorskip("pandas", minversion="1.0") + df = pd.DataFrame({"bool": pd.Series([True, False, True], dtype="boolean")}) + + array = check_array(df, dtype=None) + assert array.dtype == np.float64 + assert_array_equal(array, [[True], [False], [True]]) + + class DummyMemory: def cache(self, func): return func
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 0acd0612dd0c7..332fbc33dd192 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -1048,6 +1048,11 @@ Changelog\n left corner of the HTML representation to show how the elements are\n clickable. :pr:`21298` by `Thomas Fan`_.\n \n+- |Enhancement| :func:`utils.check_array` with `dtype=None` returns numeric\n+ arrays when passed in a pandas DataFrame with mixed dtypes. `dtype=\"numeric\"`\n+ will also make better infer the dtype when the DataFrame has mixed dtypes.\n+ :pr:`22237` by `Thomas Fan`_.\n+\n - |Enhancement| Removes random unique identifiers in the HTML representation.\n With this change, jupyter notebooks are reproducible as long as the cells are\n run in the same order. :pr:`23098` by `Thomas Fan`_.\n" } ]
1.01
8d295fbdc77c859b2ee811b2ee0588c48960bf6a
[ "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[csr_matrix-nan--allow-inf-force_all_finite should be a bool or \"allow-nan\"]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_raise_exception[csr]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[tuple-float]", "sklearn/utils/tests/test_validation.py::test_check_sparse_pandas_sp_format[True]", "sklearn/utils/tests/test_validation.py::test_check_array_memmap[True]", "sklearn/utils/tests/test_validation.py::test_num_features[list]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_scalars[str]", "sklearn/utils/tests/test_validation.py::test_check_non_negative[bsr_matrix]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[asarray-nan-X-True-Input X contains NaN]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[byte-uint16]", "sklearn/utils/tests/test_validation.py::test_check_non_negative[csr_matrix]", "sklearn/utils/tests/test_validation.py::test_check_non_negative[asarray]", "sklearn/utils/tests/test_validation.py::test_check_scalar_invalid[4-test_name6-int-2-4-bad parameter value-err_msg8]", "sklearn/utils/tests/test_validation.py::test_check_scalar_invalid[2-test_name4-int-2-4-right-err_msg6]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[series-float]", "sklearn/utils/tests/test_validation.py::test_check_is_fitted_with_attributes[tuple]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[list-float]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[asarray-nan--1-Input contains NaN]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[asarray-nan-y-True-Input y contains NaN]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[float64-float64-Int16]", "sklearn/utils/tests/test_validation.py::test_check_array_numeric_error[X1]", "sklearn/utils/tests/test_validation.py::test_get_feature_names_pandas_with_ints_no_warning[MultiIndex]", "sklearn/utils/tests/test_validation.py::test_get_feature_names_pandas_with_ints_no_warning[list-int]", "sklearn/utils/tests/test_validation.py::test_check_array_numeric_error[X3]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[numeric-float64-Float64]", "sklearn/utils/tests/test_validation.py::test_num_features[array]", "sklearn/utils/tests/test_validation.py::test_check_sparse_pandas_sp_format[coo]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[int32-long]", "sklearn/utils/tests/test_validation.py::test_check_scalar_invalid[5-test_name3-int-2-4-neither-err_msg5]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[csr_matrix-inf-sample_weight-True-Input sample_weight contains infinity]", "sklearn/utils/tests/test_validation.py::test_as_float_array", "sklearn/utils/tests/test_validation.py::test_check_array_numeric_error[X2]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[uint8-int8]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[csr_matrix-nan--True-Input contains NaN]", "sklearn/utils/tests/test_validation.py::test_get_feature_names_pandas_with_ints_no_warning[default]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[csr_matrix-nan--1-Input contains NaN]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[int16-int32]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[array-int]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[csr_matrix-nan-y-True-Input y contains NaN]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_valid[asarray-nan-allow-nan]", "sklearn/utils/tests/test_validation.py::test_check_scalar_invalid[4-test_name5-int-2-4-left-err_msg7]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[csr_matrix-inf--True-Input contains infinity]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_valid[asarray-inf-False]", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_valid[True-insignificant neg float64]", "sklearn/utils/tests/test_validation.py::test_deprecate_positional_args_warns_for_class", "sklearn/utils/tests/test_validation.py::test_check_dataframe_mixed_float_dtypes[boolean-numeric]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[False-X0-Input contains NaN.]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[asarray-inf-sample_weight-True-Input sample_weight contains infinity]", "sklearn/utils/tests/test_validation.py::test_check_scalar_invalid[1-test_name1-float-2-4-neither-err_msg0]", "sklearn/utils/tests/test_validation.py::test_check_non_negative[dok_matrix]", "sklearn/utils/tests/test_validation.py::test_check_array_numeric_error[X0]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[False-X2-Input contains infinity or a value too large for.*int]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_valid[csr_matrix-nan-allow-nan]", "sklearn/utils/tests/test_validation.py::test_check_array_links_to_imputer_doc_only_for_X[csr_matrix-y]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[csr_matrix-inf-X-allow-nan-Input X contains infinity]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_no_exception[coo]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[uint-uint64-unsignedinteger]", "sklearn/utils/tests/test_validation.py::test_num_features[sparse_csr]", "sklearn/utils/tests/test_validation.py::test_check_array_series", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[int8-byte-integer]", "sklearn/utils/tests/test_validation.py::test_check_X_y_informative_error", "sklearn/utils/tests/test_validation.py::test_check_feature_names_in", "sklearn/utils/tests/test_validation.py::test_num_features_errors_scalars[float]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_sparse_no_exception", "sklearn/utils/tests/test_validation.py::test_check_sparse_pandas_sp_format[csr]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[array-str]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_no_exception[bsr]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[list-int]", "sklearn/utils/tests/test_validation.py::test_check_array_links_to_imputer_doc_only_for_X[asarray-y]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[tuple-str]", "sklearn/utils/tests/test_validation.py::test_check_scalar_valid[3]", "sklearn/utils/tests/test_validation.py::test_check_scalar_invalid[None-test_name1-Integral-2-4-neither-err_msg2]", "sklearn/utils/tests/test_validation.py::test_check_scalar_invalid[4-test_name7-int-None-4-left-err_msg9]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[float16-float32]", "sklearn/utils/tests/test_validation.py::test_np_matrix", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[True-X1-Input contains NaN.]", "sklearn/utils/tests/test_validation.py::test_check_sample_weight", "sklearn/utils/tests/test_validation.py::test_check_dataframe_mixed_float_dtypes[boolean-float64]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_raise_exception[csc]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[intc-int32-integer]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[tuple-bool]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[True-X2-Input contains infinity or a value too large for.*int]", "sklearn/utils/tests/test_validation.py::test_check_dataframe_mixed_float_dtypes[bool-dtype0]", "sklearn/utils/tests/test_validation.py::test_check_non_negative[lil_matrix]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[asarray-inf--True-Input contains infinity]", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_raise[csc_matrix]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[csr_matrix-nan-X-True-Input X contains NaN]", "sklearn/utils/tests/test_validation.py::test_check_scalar_valid[2.5]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[dtype0-float32-Int16]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_no_exception[csc]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[longdouble-float16]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_valid[csr_matrix-inf-False]", "sklearn/utils/tests/test_validation.py::test_check_is_fitted_with_is_fitted", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[dtype0-float32-Float64]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[array-float]", "sklearn/utils/tests/test_validation.py::test_as_float_array_nan[X1]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[int64-longlong-integer]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[tuple-dict]", "sklearn/utils/tests/test_validation.py::test_suppress_validation", "sklearn/utils/tests/test_validation.py::test_check_is_fitted_attributes", "sklearn/utils/tests/test_validation.py::test_check_memory", "sklearn/utils/tests/test_validation.py::test_num_features[tuple]", "sklearn/utils/tests/test_validation.py::test_deprecate_positional_args_warns_for_function", "sklearn/utils/tests/test_validation.py::test_num_features[dataframe]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[float32-double]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[float64-float64-UInt16]", "sklearn/utils/tests/test_validation.py::test_check_array_deprecated_matrix", "sklearn/utils/tests/test_validation.py::test_num_features[sparse_csc]", "sklearn/utils/tests/test_validation.py::test_check_scalar_valid[2]", "sklearn/utils/tests/test_validation.py::test_check_array_dtype_warning", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_valid[asarray-nan-False]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[dtype0-float32-UInt8]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[uintc-uint32-unsignedinteger]", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_equals[array]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[uint32-uint64]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[False-X3-cannot convert float NaN to integer]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[numeric-float64-UInt16]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[list-str]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[float64-float64-Float32]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[False-X1-Input contains NaN.]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_no_exception[csr]", "sklearn/utils/tests/test_validation.py::test_check_array_links_to_imputer_doc_only_for_X[csr_matrix-sample_weight]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[True-X0-Input contains NaN.]", "sklearn/utils/tests/test_validation.py::test_check_scalar_invalid[1-test_name1-target_type3-2-4-neither-err_msg3]", "sklearn/utils/tests/test_validation.py::test_check_scalar_invalid[4-test_name8-int-2-None-right-err_msg10]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[series-dict]", "sklearn/utils/tests/test_validation.py::test_check_sparse_pandas_sp_format[bsr]", "sklearn/utils/tests/test_validation.py::test_check_array", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_valid[csr_matrix-nan-False]", "sklearn/utils/tests/test_validation.py::test_check_array_min_samples_and_features_messages", "sklearn/utils/tests/test_validation.py::test_check_is_fitted", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[dtype0-float32-Int8]", "sklearn/utils/tests/test_validation.py::test_check_fit_params[indices1]", "sklearn/utils/tests/test_validation.py::test_check_non_negative[coo_matrix]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[array-bool]", "sklearn/utils/tests/test_validation.py::test_get_feature_names_invalid_dtypes_warns[int-str]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[list-dict]", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_valid[True-insignificant neg]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_invalid[significant neg]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[asarray-inf-X-True-Input X contains infinity]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[tuple-int]", "sklearn/utils/tests/test_validation.py::test_check_is_fitted_with_attributes[list]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[numeric-float64-Float32]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[dtype0-float32-UInt16]", "sklearn/utils/tests/test_validation.py::test_check_sparse_pandas_sp_format[csc]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[asarray-nan--allow-inf-force_all_finite should be a bool or \"allow-nan\"]", "sklearn/utils/tests/test_validation.py::test_check_dataframe_mixed_float_dtypes[bool-numeric]", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_raise[csr_matrix]", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_valid[True-insignificant_imag]", "sklearn/utils/tests/test_validation.py::test_deprecate_positional_args_warns_for_function_version", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_invalid[significant neg float32]", "sklearn/utils/tests/test_validation.py::test_check_array_complex_data_error", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_not_equals[array]", "sklearn/utils/tests/test_validation.py::test_check_array_numeric_error[X4]", "sklearn/utils/tests/test_validation.py::test_check_non_negative[csc_matrix]", "sklearn/utils/tests/test_validation.py::test_check_array_links_to_imputer_doc_only_for_X[asarray-sample_weight]", "sklearn/utils/tests/test_validation.py::test_retrieve_samples_from_non_standard_shape", "sklearn/utils/tests/test_validation.py::test_get_feature_names_numpy", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[array-dict]", "sklearn/utils/tests/test_validation.py::test_as_float_array_nan[X0]", "sklearn/utils/tests/test_validation.py::test_check_consistent_length", "sklearn/utils/tests/test_validation.py::test_memmap", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_raise_exception[bsr]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[float64-float64-UInt8]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[int0-long-integer]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[uint16-ushort-unsignedinteger]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[float64-float64-Int8]", "sklearn/utils/tests/test_validation.py::test_check_dataframe_mixed_float_dtypes[bool-float64]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[int-long-integer]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[float64-float64-Float64]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_dtype_casting", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[numeric-float64-Int8]", "sklearn/utils/tests/test_validation.py::test_check_non_negative[dia_matrix]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[list-bool]", "sklearn/utils/tests/test_validation.py::test_check_array_links_to_imputer_doc_only_for_X[csr_matrix-X]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[series-bool]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_scalars[bool]", "sklearn/utils/tests/test_validation.py::test_check_scalar_invalid[None-test_name1-Real-2-4-neither-err_msg1]", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_invalid[all negative]", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_valid[True-insignificant pos]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[series-str]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[float16-half-floating]", "sklearn/utils/tests/test_validation.py::test_get_feature_names_pandas_with_ints_no_warning[range]", "sklearn/utils/tests/test_validation.py::test_has_fit_parameter", "sklearn/utils/tests/test_validation.py::test_num_features_errors_scalars[int]", "sklearn/utils/tests/test_validation.py::test_check_fit_params[None]", "sklearn/utils/tests/test_validation.py::test_check_array_memmap[False]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[True-X3-cannot convert float NaN to integer]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[longfloat-longdouble-floating]", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_equals[csr_matrix]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[ushort-uint32]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[asarray-nan--True-Input contains NaN]", "sklearn/utils/tests/test_validation.py::test_check_scalar_invalid[1-test_name2-int-2-4-neither-err_msg4]", "sklearn/utils/tests/test_validation.py::test_check_symmetric", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[dtype0-float32-Float32]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[uintp-ulonglong-unsignedinteger]", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_invalid[significant_imag]", "sklearn/utils/tests/test_validation.py::test_check_is_fitted_with_attributes[single]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[series-int]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_raise_exception[coo]", "sklearn/utils/tests/test_validation.py::test_ordering", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_not_equals[csr_matrix]", "sklearn/utils/tests/test_validation.py::test_check_array_on_mock_dataframe", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_equals[csc_matrix]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[asarray-inf-X-allow-nan-Input X contains infinity]", "sklearn/utils/tests/test_validation.py::test_check_array_links_to_imputer_doc_only_for_X[asarray-X]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_sparse_type_exception", "sklearn/utils/tests/test_validation.py::test_check_dataframe_mixed_float_dtypes[boolean-dtype0]", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_invalid[significant neg float64]", "sklearn/utils/tests/test_validation.py::test_check_feature_names_in_pandas", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[int_-intp-integer]", "sklearn/utils/tests/test_validation.py::test_check_dataframe_fit_attribute", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[ubyte-uint8-unsignedinteger]", "sklearn/utils/tests/test_validation.py::test_check_scalar_valid[5]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[numeric-float64-UInt8]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[double-float64-floating]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[csr_matrix-inf-X-True-Input X contains infinity]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[short-int16-integer]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[numeric-float64-Int16]", "sklearn/utils/tests/test_validation.py::test_get_feature_names_invalid_dtypes_warns[list-str]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[single-float32-floating]", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_not_equals[csc_matrix]", "sklearn/utils/tests/test_validation.py::test_check_array_dtype_stability", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_valid[True-insignificant neg float32]", "sklearn/utils/tests/test_validation.py::test_get_feature_names_pandas" ]
[ "sklearn/utils/tests/test_validation.py::test_check_dataframe_with_only_bool", "sklearn/utils/tests/test_validation.py::test_check_dataframe_mixed_float_dtypes[bool-None]", "sklearn/utils/tests/test_validation.py::test_check_dataframe_mixed_float_dtypes[boolean-None]", "sklearn/utils/tests/test_validation.py::test_check_dataframe_with_only_boolean" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 0acd0612dd0c7..332fbc33dd192 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -1048,6 +1048,11 @@ Changelog\n left corner of the HTML representation to show how the elements are\n clickable. :pr:`<PRID>` by `<NAME>`_.\n \n+- |Enhancement| :func:`utils.check_array` with `dtype=None` returns numeric\n+ arrays when passed in a pandas DataFrame with mixed dtypes. `dtype=\"numeric\"`\n+ will also make better infer the dtype when the DataFrame has mixed dtypes.\n+ :pr:`<PRID>` by `<NAME>`_.\n+\n - |Enhancement| Removes random unique identifiers in the HTML representation.\n With this change, jupyter notebooks are reproducible as long as the cells are\n run in the same order. :pr:`<PRID>` by `<NAME>`_.\n" } ]
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 0acd0612dd0c7..332fbc33dd192 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -1048,6 +1048,11 @@ Changelog left corner of the HTML representation to show how the elements are clickable. :pr:`<PRID>` by `<NAME>`_. +- |Enhancement| :func:`utils.check_array` with `dtype=None` returns numeric + arrays when passed in a pandas DataFrame with mixed dtypes. `dtype="numeric"` + will also make better infer the dtype when the DataFrame has mixed dtypes. + :pr:`<PRID>` by `<NAME>`_. + - |Enhancement| Removes random unique identifiers in the HTML representation. With this change, jupyter notebooks are reproducible as long as the cells are run in the same order. :pr:`<PRID>` by `<NAME>`_.
scikit-learn/scikit-learn
scikit-learn__scikit-learn-22248
https://github.com/scikit-learn/scikit-learn/pull/22248
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 4c307d9e54250..0240ad706b6ca 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -503,6 +503,9 @@ Changelog messages when optimizers produce non-finite parameter weights. :pr:`22150` by :user:`Christian Ritter <chritter>` and :user:`Norbert Preining <norbusan>`. +- |Enhancement| Adds :term:`get_feature_names_out` to + :class:`neural_network.BernoulliRBM`. :pr:`22248` by `Thomas Fan`_. + :mod:`sklearn.pipeline` ....................... diff --git a/sklearn/neural_network/_rbm.py b/sklearn/neural_network/_rbm.py index 6a6cb67f17de0..aac92c3108787 100644 --- a/sklearn/neural_network/_rbm.py +++ b/sklearn/neural_network/_rbm.py @@ -15,6 +15,7 @@ from ..base import BaseEstimator from ..base import TransformerMixin +from ..base import _ClassNamePrefixFeaturesOutMixin from ..utils import check_random_state from ..utils import gen_even_slices from ..utils.extmath import safe_sparse_dot @@ -22,7 +23,7 @@ from ..utils.validation import check_is_fitted -class BernoulliRBM(TransformerMixin, BaseEstimator): +class BernoulliRBM(_ClassNamePrefixFeaturesOutMixin, TransformerMixin, BaseEstimator): """Bernoulli Restricted Boltzmann Machine (RBM). A Restricted Boltzmann Machine with binary visible units and @@ -284,6 +285,7 @@ def partial_fit(self, X, y=None): self.random_state_.normal(0, 0.01, (self.n_components, X.shape[1])), order="F", ) + self._n_features_out = self.components_.shape[0] if not hasattr(self, "intercept_hidden_"): self.intercept_hidden_ = np.zeros( self.n_components, @@ -389,6 +391,7 @@ def fit(self, X, y=None): order="F", dtype=X.dtype, ) + self._n_features_out = self.components_.shape[0] self.intercept_hidden_ = np.zeros(self.n_components, dtype=X.dtype) self.intercept_visible_ = np.zeros(X.shape[1], dtype=X.dtype) self.h_samples_ = np.zeros((self.batch_size, self.n_components), dtype=X.dtype)
diff --git a/sklearn/neural_network/tests/test_rbm.py b/sklearn/neural_network/tests/test_rbm.py index aadae44479ad5..d36fa6b0bd11f 100644 --- a/sklearn/neural_network/tests/test_rbm.py +++ b/sklearn/neural_network/tests/test_rbm.py @@ -238,3 +238,15 @@ def test_convergence_dtype_consistency(): ) assert_allclose(rbm_64.components_, rbm_32.components_, rtol=1e-03, atol=0) assert_allclose(rbm_64.h_samples_, rbm_32.h_samples_) + + [email protected]("method", ["fit", "partial_fit"]) +def test_feature_names_out(method): + """Check `get_feature_names_out` for `BernoulliRBM`.""" + n_components = 10 + rbm = BernoulliRBM(n_components=n_components) + getattr(rbm, method)(Xdigits) + + names = rbm.get_feature_names_out() + expected_names = [f"bernoullirbm{i}" for i in range(n_components)] + assert_array_equal(expected_names, names) diff --git a/sklearn/tests/test_common.py b/sklearn/tests/test_common.py index fb4de8942f131..be26202d458d1 100644 --- a/sklearn/tests/test_common.py +++ b/sklearn/tests/test_common.py @@ -383,7 +383,6 @@ def test_pandas_column_name_consistency(estimator): "ensemble", "kernel_approximation", "preprocessing", - "neural_network", ]
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 4c307d9e54250..0240ad706b6ca 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -503,6 +503,9 @@ Changelog\n messages when optimizers produce non-finite parameter weights. :pr:`22150`\n by :user:`Christian Ritter <chritter>` and :user:`Norbert Preining <norbusan>`.\n \n+- |Enhancement| Adds :term:`get_feature_names_out` to\n+ :class:`neural_network.BernoulliRBM`. :pr:`22248` by `Thomas Fan`_.\n+\n :mod:`sklearn.pipeline`\n .......................\n \n" } ]
1.01
8991c3d7870df692fe01510e0fe6de62ea550cad
[ "sklearn/neural_network/tests/test_rbm.py::test_fit_gibbs", "sklearn/neural_network/tests/test_rbm.py::test_small_sparse_partial_fit", "sklearn/neural_network/tests/test_rbm.py::test_gibbs_smoke", "sklearn/neural_network/tests/test_rbm.py::test_transform", "sklearn/neural_network/tests/test_rbm.py::test_transformer_dtypes_casting[float32-float32]", "sklearn/neural_network/tests/test_rbm.py::test_transformer_dtypes_casting[float64-float64]", "sklearn/neural_network/tests/test_rbm.py::test_fit", "sklearn/neural_network/tests/test_rbm.py::test_rbm_verbose", "sklearn/neural_network/tests/test_rbm.py::test_sample_hiddens", "sklearn/neural_network/tests/test_rbm.py::test_convergence_dtype_consistency", "sklearn/neural_network/tests/test_rbm.py::test_sparse_and_verbose", "sklearn/neural_network/tests/test_rbm.py::test_small_sparse", "sklearn/neural_network/tests/test_rbm.py::test_score_samples", "sklearn/neural_network/tests/test_rbm.py::test_partial_fit", "sklearn/neural_network/tests/test_rbm.py::test_fit_gibbs_sparse", "sklearn/neural_network/tests/test_rbm.py::test_transformer_dtypes_casting[int-float64]" ]
[ "sklearn/neural_network/tests/test_rbm.py::test_feature_names_out[fit]", "sklearn/neural_network/tests/test_rbm.py::test_feature_names_out[partial_fit]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 4c307d9e54250..0240ad706b6ca 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -503,6 +503,9 @@ Changelog\n messages when optimizers produce non-finite parameter weights. :pr:`<PRID>`\n by :user:`<NAME>` and :user:`<NAME>`.\n \n+- |Enhancement| Adds :term:`get_feature_names_out` to\n+ :class:`neural_network.BernoulliRBM`. :pr:`<PRID>` by `<NAME>`_.\n+\n :mod:`sklearn.pipeline`\n .......................\n \n" } ]
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 4c307d9e54250..0240ad706b6ca 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -503,6 +503,9 @@ Changelog messages when optimizers produce non-finite parameter weights. :pr:`<PRID>` by :user:`<NAME>` and :user:`<NAME>`. +- |Enhancement| Adds :term:`get_feature_names_out` to + :class:`neural_network.BernoulliRBM`. :pr:`<PRID>` by `<NAME>`_. + :mod:`sklearn.pipeline` .......................
scikit-learn/scikit-learn
scikit-learn__scikit-learn-19263
https://github.com/scikit-learn/scikit-learn/pull/19263
diff --git a/doc/modules/compose.rst b/doc/modules/compose.rst index 6e827304c38cd..a9195ba9ab022 100644 --- a/doc/modules/compose.rst +++ b/doc/modules/compose.rst @@ -527,6 +527,20 @@ above example would be:: ('countvectorizer', CountVectorizer(), 'title')]) +If :class:`~sklearn.compose.ColumnTransformer` is fitted with a dataframe +and the dataframe only has string column names, then transforming a dataframe +will use the column names to select the columns:: + + + >>> ct = ColumnTransformer( + ... [("scale", StandardScaler(), ["expert_rating"])]).fit(X) + >>> X_new = pd.DataFrame({"expert_rating": [5, 6, 1], + ... "ignored_new_col": [1.2, 0.3, -0.1]}) + >>> ct.transform(X_new) + array([[ 0.9...], + [ 2.1...], + [-3.9...]]) + .. _visualizing_composite_estimators: Visualizing Composite Estimators diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index 977d83890e0c0..d26c5dd0c347d 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -131,6 +131,11 @@ Changelog of each transformer in `output_indices_`. :pr:`18393` by :user:`Luca Bittarello <lbittarello>`. +- |Enhancement| :class:`compose.ColumnTransformer` now allows DataFrame input to + have its columns appear in a changed order in `transform`. Further, columns that + are dropped will not be required in transform, and additional columns will be + ignored if `remainder='drop'`. :pr:`19263` by `Thomas Fan`_ + - |FIX| :meth:`compose.ColumnTransformer.get_feature_names` supports non-string feature names returned by any of its transformers. :pr:`18459` by :user:`Albert Villanova del Moral <albertvillanova>` and diff --git a/sklearn/compose/_column_transformer.py b/sklearn/compose/_column_transformer.py index 2f2da882652c0..441fc95a106f1 100644 --- a/sklearn/compose/_column_transformer.py +++ b/sklearn/compose/_column_transformer.py @@ -244,7 +244,8 @@ def set_params(self, **kwargs): self._set_params('_transformers', **kwargs) return self - def _iter(self, fitted=False, replace_strings=False): + def _iter(self, fitted=False, replace_strings=False, + column_as_strings=False): """ Generate (name, trans, column, weight) tuples. @@ -262,11 +263,11 @@ def _iter(self, fitted=False, replace_strings=False): in zip(self.transformers, self._columns) ] # add transformer tuple for remainder - if self._remainder[2] is not None: + if self._remainder[2]: transformers = chain(transformers, [self._remainder]) get_weight = (self.transformer_weights or {}).get - for name, trans, column in transformers: + for name, trans, columns in transformers: if replace_strings: # replace 'passthrough' with identity transformer and # skip in case of 'drop' @@ -276,10 +277,21 @@ def _iter(self, fitted=False, replace_strings=False): ) elif trans == 'drop': continue - elif _is_empty_column_selection(column): + elif _is_empty_column_selection(columns): continue - yield (name, trans, column, get_weight(name)) + if column_as_strings and self._only_str_columns: + # Convert all columns to using their string labels + columns_is_scalar = np.isscalar(columns) + + indices = self._transformer_to_input_indices[name] + columns = self._feature_names_in[indices] + + if columns_is_scalar: + # selection is done with one dimension + columns = columns[0] + + yield (name, trans, columns, get_weight(name)) def _validate_transformers(self): if not self.transformers: @@ -305,12 +317,17 @@ def _validate_column_callables(self, X): """ Converts callable column specifications. """ - columns = [] - for _, _, column in self.transformers: - if callable(column): - column = column(X) - columns.append(column) - self._columns = columns + all_columns = [] + transformer_to_input_indices = {} + for name, _, columns in self.transformers: + if callable(columns): + columns = columns(X) + all_columns.append(columns) + transformer_to_input_indices[name] = _get_column_indices(X, + columns) + + self._columns = all_columns + self._transformer_to_input_indices = transformer_to_input_indices def _validate_remainder(self, X): """ @@ -328,12 +345,10 @@ def _validate_remainder(self, X): self.remainder) self._n_features = X.shape[1] - cols = [] - for columns in self._columns: - cols.extend(_get_column_indices(X, columns)) - - remaining_idx = sorted(set(range(self._n_features)) - set(cols)) - self._remainder = ('remainder', self.remainder, remaining_idx or None) + cols = set(chain(*self._transformer_to_input_indices.values())) + remaining = sorted(set(range(self._n_features)) - cols) + self._remainder = ('remainder', self.remainder, remaining) + self._transformer_to_input_indices['remainder'] = remaining @property def named_transformers_(self): @@ -443,7 +458,8 @@ def _log_message(self, name, idx, total): return None return '(%d of %d) Processing %s' % (idx, total, name) - def _fit_transform(self, X, y, func, fitted=False): + def _fit_transform(self, X, y, func, fitted=False, + column_as_strings=False): """ Private function to fit and/or transform on demand. @@ -452,7 +468,9 @@ def _fit_transform(self, X, y, func, fitted=False): ``fitted=True`` ensures the fitted transformers are used. """ transformers = list( - self._iter(fitted=fitted, replace_strings=True)) + self._iter( + fitted=fitted, replace_strings=True, + column_as_strings=column_as_strings)) try: return Parallel(n_jobs=self.n_jobs)( delayed(func)( @@ -518,6 +536,8 @@ def fit_transform(self, X, y=None): # TODO: this should be `feature_names_in_` when we start having it if hasattr(X, "columns"): self._feature_names_in = np.asarray(X.columns) + self._only_str_columns = all(isinstance(col, str) + for col in self._feature_names_in) else: self._feature_names_in = None X = _check_X(X) @@ -572,20 +592,34 @@ def transform(self, X): """ check_is_fitted(self) X = _check_X(X) - if hasattr(X, "columns"): - X_feature_names = np.asarray(X.columns) + + fit_dataframe_and_transform_dataframe = ( + self._feature_names_in is not None and hasattr(X, "columns")) + + if fit_dataframe_and_transform_dataframe: + named_transformers = self.named_transformers_ + # check that all names seen in fit are in transform, unless + # they were dropped + non_dropped_indices = [ + ind for name, ind in self._transformer_to_input_indices.items() + if name in named_transformers and + isinstance(named_transformers[name], str) and + named_transformers[name] != 'drop'] + + all_indices = set(chain(*non_dropped_indices)) + all_names = set(self._feature_names_in[ind] for ind in all_indices) + + diff = all_names - set(X.columns) + if diff: + raise ValueError(f"columns are missing: {diff}") else: - X_feature_names = None - - self._check_n_features(X, reset=False) - if (self._feature_names_in is not None and - X_feature_names is not None and - np.any(self._feature_names_in != X_feature_names)): - raise RuntimeError( - "Given feature/column names do not match the ones for the " - "data given during fit." - ) - Xs = self._fit_transform(X, None, _transform_one, fitted=True) + # ndarray was used for fitting or transforming, thus we only + # check that n_features_in_ is consistent + self._check_n_features(X, reset=False) + + Xs = self._fit_transform( + X, None, _transform_one, fitted=True, + column_as_strings=fit_dataframe_and_transform_dataframe) self._validate_output(Xs) if not Xs: @@ -629,10 +663,12 @@ def _sk_visual_block_(self): transformers = self.transformers elif hasattr(self, "_remainder"): remainder_columns = self._remainder[2] - if self._feature_names_in is not None: + if (self._feature_names_in is not None and + remainder_columns and + not all(isinstance(col, str) + for col in remainder_columns)): remainder_columns = ( - self._feature_names_in[remainder_columns].tolist() - ) + self._feature_names_in[remainder_columns].tolist()) transformers = chain(self.transformers, [('remainder', self.remainder, remainder_columns)])
diff --git a/sklearn/compose/tests/test_column_transformer.py b/sklearn/compose/tests/test_column_transformer.py index 549292ab51445..9278d67296ec5 100644 --- a/sklearn/compose/tests/test_column_transformer.py +++ b/sklearn/compose/tests/test_column_transformer.py @@ -4,7 +4,6 @@ import re import pickle -import warnings import numpy as np from scipy import sparse import pytest @@ -1260,82 +1259,6 @@ def test_column_transformer_negative_column_indexes(): assert_array_equal(tf_1.fit_transform(X), tf_2.fit_transform(X)) [email protected]("explicit_colname", ['first', 'second']) -def test_column_transformer_reordered_column_names_remainder(explicit_colname): - """Regression test for issue #14223: 'Named col indexing fails with - ColumnTransformer remainder on changing DataFrame column ordering' - - Should raise error on changed order combined with remainder. - Should allow for added columns in `transform` input DataFrame - as long as all preceding columns match. - """ - pd = pytest.importorskip('pandas') - - X_fit_array = np.array([[0, 1, 2], [2, 4, 6]]).T - X_fit_df = pd.DataFrame(X_fit_array, columns=['first', 'second']) - - X_trans_array = np.array([[2, 4, 6], [0, 1, 2]]).T - X_trans_df = pd.DataFrame(X_trans_array, columns=['second', 'first']) - - tf = ColumnTransformer([('bycol', Trans(), explicit_colname)], - remainder=Trans()) - - tf.fit(X_fit_df) - err_msg = ("Given feature/column names do not match the ones for the " - "data given during fit.") - with pytest.raises(RuntimeError, match=err_msg): - tf.transform(X_trans_df) - - # ValueError for added columns - X_extended_df = X_fit_df.copy() - X_extended_df['third'] = [3, 6, 9] - err_msg = ("X has 3 features, but ColumnTransformer is expecting 2 " - "features as input.") - with pytest.raises(ValueError, match=err_msg): - tf.transform(X_extended_df) - - # No 'columns' AttributeError when transform input is a numpy array - X_array = X_fit_array.copy() - err_msg = 'Specifying the columns' - with pytest.raises(ValueError, match=err_msg): - tf.transform(X_array) - - -def test_feature_name_validation(): - """Tests if the proper warning/error is raised if the columns do not match - during fit and transform.""" - pd = pytest.importorskip("pandas") - - X = np.ones(shape=(3, 2)) - X_extra = np.ones(shape=(3, 3)) - df = pd.DataFrame(X, columns=['a', 'b']) - df_extra = pd.DataFrame(X_extra, columns=['a', 'b', 'c']) - - tf = ColumnTransformer([('bycol', Trans(), ['a', 'b'])]) - tf.fit(df) - - msg = ("X has 3 features, but ColumnTransformer is expecting 2 features " - "as input.") - with pytest.raises(ValueError, match=msg): - tf.transform(df_extra) - - tf = ColumnTransformer([('bycol', Trans(), [0])]) - tf.fit(df) - - with pytest.raises(ValueError, match=msg): - tf.transform(X_extra) - - with warnings.catch_warnings(record=True) as warns: - tf.transform(X) - assert not warns - - tf = ColumnTransformer([('bycol', Trans(), ['a'])], - remainder=Trans()) - tf.fit(df) - with pytest.raises(ValueError, match=msg): - tf.transform(df_extra) - - @pytest.mark.parametrize("array_type", [np.asarray, sparse.csr_matrix]) def test_column_transformer_mask_indexing(array_type): # Regression test for #14510 @@ -1516,6 +1439,80 @@ def test_sk_visual_block_remainder_fitted_numpy(remainder): assert visual_block.estimators == (scaler, remainder) [email protected]("explicit_colname", ['first', 'second', 0, 1]) [email protected]("remainder", [Trans(), 'passthrough', 'drop']) +def test_column_transformer_reordered_column_names_remainder(explicit_colname, + remainder): + """Test the interaction between remainder and column transformer""" + pd = pytest.importorskip('pandas') + + X_fit_array = np.array([[0, 1, 2], [2, 4, 6]]).T + X_fit_df = pd.DataFrame(X_fit_array, columns=['first', 'second']) + + X_trans_array = np.array([[2, 4, 6], [0, 1, 2]]).T + X_trans_df = pd.DataFrame(X_trans_array, columns=['second', 'first']) + + tf = ColumnTransformer([('bycol', Trans(), explicit_colname)], + remainder=remainder) + + tf.fit(X_fit_df) + X_fit_trans = tf.transform(X_fit_df) + + # Changing the order still works + X_trans = tf.transform(X_trans_df) + assert_allclose(X_trans, X_fit_trans) + + # extra columns are ignored + X_extended_df = X_fit_df.copy() + X_extended_df['third'] = [3, 6, 9] + X_trans = tf.transform(X_extended_df) + assert_allclose(X_trans, X_fit_trans) + + if isinstance(explicit_colname, str): + # Raise error if columns are specified by names but input only allows + # to specify by position, e.g. numpy array instead of a pandas df. + X_array = X_fit_array.copy() + err_msg = 'Specifying the columns' + with pytest.raises(ValueError, match=err_msg): + tf.transform(X_array) + + +def test_feature_name_validation_missing_columns_drop_passthough(): + """Test the interaction between {'drop', 'passthrough'} and + missing column names.""" + pd = pytest.importorskip("pandas") + + X = np.ones(shape=(3, 4)) + df = pd.DataFrame(X, columns=['a', 'b', 'c', 'd']) + + df_dropped = df.drop('c', axis=1) + + # with remainder='passthrough', all columns seen during `fit` must be + # present + tf = ColumnTransformer([('bycol', Trans(), [1])], remainder='passthrough') + tf.fit(df) + msg = r"columns are missing: {'c'}" + with pytest.raises(ValueError, match=msg): + tf.transform(df_dropped) + + # with remainder='drop', it is allowed to have column 'c' missing + tf = ColumnTransformer([('bycol', Trans(), [1])], + remainder='drop') + tf.fit(df) + + df_dropped_trans = tf.transform(df_dropped) + df_fit_trans = tf.transform(df) + assert_allclose(df_dropped_trans, df_fit_trans) + + # bycol drops 'c', thus it is allowed for 'c' to be missing + tf = ColumnTransformer([('bycol', 'drop', ['c'])], + remainder='passthrough') + tf.fit(df) + df_dropped_trans = tf.transform(df_dropped) + df_fit_trans = tf.transform(df) + assert_allclose(df_dropped_trans, df_fit_trans) + + @pytest.mark.parametrize("selector", [[], [False, False]]) def test_get_feature_names_empty_selection(selector): """Test that get_feature_names is only called for transformers that
[ { "path": "doc/modules/compose.rst", "old_path": "a/doc/modules/compose.rst", "new_path": "b/doc/modules/compose.rst", "metadata": "diff --git a/doc/modules/compose.rst b/doc/modules/compose.rst\nindex 6e827304c38cd..a9195ba9ab022 100644\n--- a/doc/modules/compose.rst\n+++ b/doc/modules/compose.rst\n@@ -527,6 +527,20 @@ above example would be::\n ('countvectorizer', CountVectorizer(),\n 'title')])\n \n+If :class:`~sklearn.compose.ColumnTransformer` is fitted with a dataframe\n+and the dataframe only has string column names, then transforming a dataframe\n+will use the column names to select the columns::\n+\n+\n+ >>> ct = ColumnTransformer(\n+ ... [(\"scale\", StandardScaler(), [\"expert_rating\"])]).fit(X)\n+ >>> X_new = pd.DataFrame({\"expert_rating\": [5, 6, 1],\n+ ... \"ignored_new_col\": [1.2, 0.3, -0.1]})\n+ >>> ct.transform(X_new)\n+ array([[ 0.9...],\n+ [ 2.1...],\n+ [-3.9...]])\n+\n .. _visualizing_composite_estimators:\n \n Visualizing Composite Estimators\n" }, { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 977d83890e0c0..d26c5dd0c347d 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -131,6 +131,11 @@ Changelog\n of each transformer in `output_indices_`. :pr:`18393` by\n :user:`Luca Bittarello <lbittarello>`.\n \n+- |Enhancement| :class:`compose.ColumnTransformer` now allows DataFrame input to\n+ have its columns appear in a changed order in `transform`. Further, columns that\n+ are dropped will not be required in transform, and additional columns will be\n+ ignored if `remainder='drop'`. :pr:`19263` by `Thomas Fan`_\n+\n - |FIX| :meth:`compose.ColumnTransformer.get_feature_names` supports\n non-string feature names returned by any of its transformers.\n :pr:`18459` by :user:`Albert Villanova del Moral <albertvillanova>` and\n" } ]
1.00
a9cc0ed86fca1480acbd8aaf211f062ee2abd5b7
[ "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_verbose[fit_transform-est5-\\\\[ColumnTransformer\\\\].*\\\\(1 of 2\\\\) Processing trans1.* total=.*\\\\n\\\\[ColumnTransformer\\\\].*\\\\(2 of 2\\\\) Processing trans2.* total=.*\\\\n$]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_remainder_pandas[key0]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_empty_columns[True-bool-pandas]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_verbose[fit-est2-\\\\[ColumnTransformer\\\\].*\\\\(1 of 2\\\\) Processing trans1.* total=.*\\\\n\\\\[ColumnTransformer\\\\].*\\\\(2 of 2\\\\) Processing remainder.* total=.*\\\\n$]", "sklearn/compose/tests/test_column_transformer.py::test_make_column_transformer_pandas", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_verbose[fit-est1-\\\\[ColumnTransformer\\\\].*\\\\(1 of 3\\\\) Processing trans1.* total=.*\\\\n\\\\[ColumnTransformer\\\\].*\\\\(2 of 3\\\\) Processing trans2.* total=.*\\\\n\\\\[ColumnTransformer\\\\].*\\\\(3 of 3\\\\) Processing remainder.* total=.*\\\\n$]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_no_estimators", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_empty_columns[True-bool_int-pandas]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_with_make_column_selector", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_remainder_pandas[key3]", "sklearn/compose/tests/test_column_transformer.py::test_sk_visual_block_remainder_fitted_pandas[passthrough]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_sparse_stacking", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_get_feature_names_raises", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_remainder_numpy[key0]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_get_feature_names_dataframe", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_verbose[fit_transform-est1-\\\\[ColumnTransformer\\\\].*\\\\(1 of 3\\\\) Processing trans1.* total=.*\\\\n\\\\[ColumnTransformer\\\\].*\\\\(2 of 3\\\\) Processing trans2.* total=.*\\\\n\\\\[ColumnTransformer\\\\].*\\\\(3 of 3\\\\) Processing remainder.* total=.*\\\\n$]", "sklearn/compose/tests/test_column_transformer.py::test_feature_names_empty_columns[callable]", "sklearn/compose/tests/test_column_transformer.py::test_make_column_selector_with_select_dtypes[cols10-^col_s-None-exclude10]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_sparse_array", "sklearn/compose/tests/test_column_transformer.py::test_2D_transformer_output_pandas", "sklearn/compose/tests/test_column_transformer.py::test_make_column_selector_with_select_dtypes[cols2-None-include2-None]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_sparse_threshold", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_remainder_pandas[key7]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_remainder_transformer[key2]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_get_set_params_with_remainder", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_mixed_cols_sparse", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_verbose[fit-est3-\\\\[ColumnTransformer\\\\].*\\\\(1 of 3\\\\) Processing trans1.* total=.*\\\\n\\\\[ColumnTransformer\\\\].*\\\\(2 of 3\\\\) Processing trans2.* total=.*\\\\n\\\\[ColumnTransformer\\\\].*\\\\(3 of 3\\\\) Processing remainder.* total=.*\\\\n$]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_output_indices", "sklearn/compose/tests/test_column_transformer.py::test_get_feature_names_empty_selection[selector0]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_mask_indexing[csr_matrix]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_negative_column_indexes", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_remainder_numpy[key3]", "sklearn/compose/tests/test_column_transformer.py::test_make_column_selector_with_select_dtypes[cols9-float|str-None-None]", "sklearn/compose/tests/test_column_transformer.py::test_sk_visual_block_remainder_fitted_numpy[passthrough]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_verbose[fit_transform-est0-\\\\[ColumnTransformer\\\\].*\\\\(1 of 3\\\\) Processing trans1.* total=.*\\\\n\\\\[ColumnTransformer\\\\].*\\\\(2 of 3\\\\) Processing trans2.* total=.*\\\\n\\\\[ColumnTransformer\\\\].*\\\\(3 of 3\\\\) Processing remainder.* total=.*\\\\n$]", "sklearn/compose/tests/test_column_transformer.py::test_2D_transformer_output", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_invalid_columns[passthrough]", "sklearn/compose/tests/test_column_transformer.py::test_sk_visual_block_remainder[passthrough]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_get_set_params", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_remainder_pandas[pd-index]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_verbose[fit_transform-est2-\\\\[ColumnTransformer\\\\].*\\\\(1 of 2\\\\) Processing trans1.* total=.*\\\\n\\\\[ColumnTransformer\\\\].*\\\\(2 of 2\\\\) Processing remainder.* total=.*\\\\n$]", "sklearn/compose/tests/test_column_transformer.py::test_make_column_selector_with_select_dtypes[cols8-^col_int-include8-None]", "sklearn/compose/tests/test_column_transformer.py::test_make_column_selector_with_select_dtypes[cols0-None-number-None]", "sklearn/compose/tests/test_column_transformer.py::test_sk_visual_block_remainder_fitted_numpy[remainder1]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_empty_columns[False-list-numpy]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_special_strings", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_sparse_remainder_transformer", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_remainder_pandas[key5]", "sklearn/compose/tests/test_column_transformer.py::test_n_features_in", "sklearn/compose/tests/test_column_transformer.py::test_make_column_selector_with_select_dtypes[cols6-at$-include6-None]", "sklearn/compose/tests/test_column_transformer.py::test_make_column_selector_with_select_dtypes[cols5-None-float-None]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_drop_all_sparse_remainder_transformer", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_empty_columns[True-list-numpy]", "sklearn/compose/tests/test_column_transformer.py::test_make_column_selector_error", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_invalid_transformer", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_empty_columns[False-bool_int-pandas]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_empty_columns[False-bool-pandas]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_remainder_transformer[key1]", "sklearn/compose/tests/test_column_transformer.py::test_make_column_selector_with_select_dtypes[cols4-None-object-None]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_invalid_columns[drop]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_remainder_numpy[key2]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_no_estimators_set_params", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_remainder_pandas[key8]", "sklearn/compose/tests/test_column_transformer.py::test_make_column_selector_with_select_dtypes[cols11-str$-float-None]", "sklearn/compose/tests/test_column_transformer.py::test_make_column_transformer", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_no_remaining_remainder_transformer", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_remainder_pandas[key2]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_empty_columns[True-bool-numpy]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_empty_columns[False-list-pandas]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_remainder_transformer[key0]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_empty_columns[False-bool-numpy]", "sklearn/compose/tests/test_column_transformer.py::test_make_column_transformer_kwargs", "sklearn/compose/tests/test_column_transformer.py::test_feature_names_empty_columns[array]", "sklearn/compose/tests/test_column_transformer.py::test_get_feature_names_empty_selection[selector1]", "sklearn/compose/tests/test_column_transformer.py::test_make_column_selector_with_select_dtypes[cols12-None-include12-None]", "sklearn/compose/tests/test_column_transformer.py::test_make_column_transformer_remainder_transformer", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_callable_specifier_dataframe", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_empty_columns[False-bool_int-numpy]", "sklearn/compose/tests/test_column_transformer.py::test_make_column_selector_with_select_dtypes[cols1-None-None-object]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_named_estimators", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_verbose[fit_transform-est3-\\\\[ColumnTransformer\\\\].*\\\\(1 of 3\\\\) Processing trans1.* total=.*\\\\n\\\\[ColumnTransformer\\\\].*\\\\(2 of 3\\\\) Processing trans2.* total=.*\\\\n\\\\[ColumnTransformer\\\\].*\\\\(3 of 3\\\\) Processing remainder.* total=.*\\\\n$]", "sklearn/compose/tests/test_column_transformer.py::test_sk_visual_block_remainder[remainder1]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_empty_columns[True-bool_int-numpy]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_list", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_verbose[fit_transform-est6-\\\\[ColumnTransformer\\\\].*\\\\(1 of 1\\\\) Processing trans1.* total=.*\\\\n$]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_verbose[fit-est4-\\\\[ColumnTransformer\\\\].*\\\\(1 of 2\\\\) Processing trans1.* total=.*\\\\n\\\\[ColumnTransformer\\\\].*\\\\(2 of 2\\\\) Processing remainder.* total=.*\\\\n$]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_drops_all_remainder_transformer", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_remainder_transformer[key3]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_cloning", "sklearn/compose/tests/test_column_transformer.py::test_sk_visual_block_remainder_drop", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_remainder", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_get_feature_names[X0-keys0]", "sklearn/compose/tests/test_column_transformer.py::test_make_column_selector_pickle", "sklearn/compose/tests/test_column_transformer.py::test_feature_names_empty_columns[list]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_callable_specifier", "sklearn/compose/tests/test_column_transformer.py::test_sk_visual_block_remainder_fitted_pandas[remainder1]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_output_indices_df", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_remainder_numpy[key1]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_remainder_pandas[key1]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_get_feature_names[X1-keys1]", "sklearn/compose/tests/test_column_transformer.py::test_make_column_selector_with_select_dtypes[cols3-None-include3-None]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_verbose[fit-est0-\\\\[ColumnTransformer\\\\].*\\\\(1 of 3\\\\) Processing trans1.* total=.*\\\\n\\\\[ColumnTransformer\\\\].*\\\\(2 of 3\\\\) Processing trans2.* total=.*\\\\n\\\\[ColumnTransformer\\\\].*\\\\(3 of 3\\\\) Processing remainder.* total=.*\\\\n$]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_mask_indexing[asarray]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_dataframe", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_remainder_pandas[key6]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_error_msg_1D", "sklearn/compose/tests/test_column_transformer.py::test_make_column_selector_with_select_dtypes[cols7-None-include7-None]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_verbose[fit_transform-est4-\\\\[ColumnTransformer\\\\].*\\\\(1 of 2\\\\) Processing trans1.* total=.*\\\\n\\\\[ColumnTransformer\\\\].*\\\\(2 of 2\\\\) Processing remainder.* total=.*\\\\n$]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_verbose[fit-est5-\\\\[ColumnTransformer\\\\].*\\\\(1 of 2\\\\) Processing trans1.* total=.*\\\\n\\\\[ColumnTransformer\\\\].*\\\\(2 of 2\\\\) Processing trans2.* total=.*\\\\n$]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_verbose[fit-est6-\\\\[ColumnTransformer\\\\].*\\\\(1 of 1\\\\) Processing trans1.* total=.*\\\\n$]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_empty_columns[True-list-pandas]" ]
[ "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_reordered_column_names_remainder[passthrough-first]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_reordered_column_names_remainder[remainder0-0]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_reordered_column_names_remainder[passthrough-1]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_reordered_column_names_remainder[passthrough-0]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_reordered_column_names_remainder[remainder0-first]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_reordered_column_names_remainder[remainder0-1]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_reordered_column_names_remainder[drop-second]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_reordered_column_names_remainder[drop-1]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_reordered_column_names_remainder[drop-0]", "sklearn/compose/tests/test_column_transformer.py::test_feature_name_validation_missing_columns_drop_passthough", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_reordered_column_names_remainder[drop-first]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_reordered_column_names_remainder[remainder0-second]", "sklearn/compose/tests/test_column_transformer.py::test_column_transformer_reordered_column_names_remainder[passthrough-second]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/modules/compose.rst", "old_path": "a/doc/modules/compose.rst", "new_path": "b/doc/modules/compose.rst", "metadata": "diff --git a/doc/modules/compose.rst b/doc/modules/compose.rst\nindex 6e827304c38cd..a9195ba9ab022 100644\n--- a/doc/modules/compose.rst\n+++ b/doc/modules/compose.rst\n@@ -527,6 +527,20 @@ above example would be::\n ('countvectorizer', CountVectorizer(),\n 'title')])\n \n+If :class:`~sklearn.compose.ColumnTransformer` is fitted with a dataframe\n+and the dataframe only has string column names, then transforming a dataframe\n+will use the column names to select the columns::\n+\n+\n+ >>> ct = ColumnTransformer(\n+ ... [(\"scale\", StandardScaler(), [\"expert_rating\"])]).fit(X)\n+ >>> X_new = pd.DataFrame({\"expert_rating\": [5, 6, 1],\n+ ... \"ignored_new_col\": [1.2, 0.3, -0.1]})\n+ >>> ct.transform(X_new)\n+ array([[ 0.9...],\n+ [ 2.1...],\n+ [-3.9...]])\n+\n .. _visualizing_composite_estimators:\n \n Visualizing Composite Estimators\n" }, { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 977d83890e0c0..d26c5dd0c347d 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -131,6 +131,11 @@ Changelog\n of each transformer in `output_indices_`. :pr:`<PRID>` by\n :user:`<NAME>`.\n \n+- |Enhancement| :class:`compose.ColumnTransformer` now allows DataFrame input to\n+ have its columns appear in a changed order in `transform`. Further, columns that\n+ are dropped will not be required in transform, and additional columns will be\n+ ignored if `remainder='drop'`. :pr:`<PRID>` by `<NAME>`_\n+\n - |FIX| :meth:`compose.ColumnTransformer.get_feature_names` supports\n non-string feature names returned by any of its transformers.\n :pr:`<PRID>` by :user:`<NAME>` and\n" } ]
diff --git a/doc/modules/compose.rst b/doc/modules/compose.rst index 6e827304c38cd..a9195ba9ab022 100644 --- a/doc/modules/compose.rst +++ b/doc/modules/compose.rst @@ -527,6 +527,20 @@ above example would be:: ('countvectorizer', CountVectorizer(), 'title')]) +If :class:`~sklearn.compose.ColumnTransformer` is fitted with a dataframe +and the dataframe only has string column names, then transforming a dataframe +will use the column names to select the columns:: + + + >>> ct = ColumnTransformer( + ... [("scale", StandardScaler(), ["expert_rating"])]).fit(X) + >>> X_new = pd.DataFrame({"expert_rating": [5, 6, 1], + ... "ignored_new_col": [1.2, 0.3, -0.1]}) + >>> ct.transform(X_new) + array([[ 0.9...], + [ 2.1...], + [-3.9...]]) + .. _visualizing_composite_estimators: Visualizing Composite Estimators diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index 977d83890e0c0..d26c5dd0c347d 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -131,6 +131,11 @@ Changelog of each transformer in `output_indices_`. :pr:`<PRID>` by :user:`<NAME>`. +- |Enhancement| :class:`compose.ColumnTransformer` now allows DataFrame input to + have its columns appear in a changed order in `transform`. Further, columns that + are dropped will not be required in transform, and additional columns will be + ignored if `remainder='drop'`. :pr:`<PRID>` by `<NAME>`_ + - |FIX| :meth:`compose.ColumnTransformer.get_feature_names` supports non-string feature names returned by any of its transformers. :pr:`<PRID>` by :user:`<NAME>` and
scikit-learn/scikit-learn
scikit-learn__scikit-learn-19244
https://github.com/scikit-learn/scikit-learn/pull/19244
diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index 269a5d46e71b2..7202ab4e00476 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -214,7 +214,12 @@ Changelog - |Enhancement| :class:`compose.ColumnTransformer` now allows DataFrame input to have its columns appear in a changed order in `transform`. Further, columns that are dropped will not be required in transform, and additional columns will be - ignored if `remainder='drop'`. :pr:`19263` by `Thomas Fan`_ + ignored if `remainder='drop'`. :pr:`19263` by `Thomas Fan`_. + +- |Enhancement| Adds `**predict_params` keyword argument to + :meth:`compose.TransformedTargetRegressor.predict` that passes keyword + argument to the regressor. + :pr:`19244` by :user:`Ricardo <ricardojnf>`. - |FIX| :meth:`compose.ColumnTransformer.get_feature_names` supports non-string feature names returned by any of its transformers. diff --git a/sklearn/compose/_target.py b/sklearn/compose/_target.py index 562c5bae5a2dc..b8c1d7a8a76a1 100644 --- a/sklearn/compose/_target.py +++ b/sklearn/compose/_target.py @@ -235,7 +235,7 @@ def fit(self, X, y, **fit_params): return self - def predict(self, X): + def predict(self, X, **predict_params): """Predict using the base regressor, applying inverse. The regressor is used to predict and the ``inverse_func`` or @@ -246,6 +246,10 @@ def predict(self, X): X : {array-like, sparse matrix} of shape (n_samples, n_features) Samples. + **predict_params : dict of str -> object + Parameters passed to the `predict` method of the underlying + regressor. + Returns ------- y_hat : ndarray of shape (n_samples,) @@ -253,7 +257,7 @@ def predict(self, X): """ check_is_fitted(self) - pred = self.regressor_.predict(X) + pred = self.regressor_.predict(X, **predict_params) if pred.ndim == 1: pred_trans = self.transformer_.inverse_transform(pred.reshape(-1, 1)) else:
diff --git a/sklearn/compose/tests/test_target.py b/sklearn/compose/tests/test_target.py index 5c57ce37af2aa..f0d63c00c2772 100644 --- a/sklearn/compose/tests/test_target.py +++ b/sklearn/compose/tests/test_target.py @@ -375,3 +375,24 @@ def test_transform_target_regressor_route_pipeline(): pip.fit(X, y, **{"est__check_input": False}) assert regr.transformer_.fit_counter == 1 + + +class DummyRegressorWithExtraPredictParams(DummyRegressor): + def predict(self, X, check_input=True): + # In the test below we make sure that the check input parameter is + # passed as false + self.predict_called = True + assert not check_input + return super().predict(X) + + +def test_transform_target_regressor_pass_extra_predict_parameters(): + # Checks that predict kwargs are passed to regressor. + X, y = friedman + regr = TransformedTargetRegressor( + regressor=DummyRegressorWithExtraPredictParams(), transformer=DummyTransformer() + ) + + regr.fit(X, y) + regr.predict(X, check_input=False) + assert regr.regressor_.predict_called
[ { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 269a5d46e71b2..7202ab4e00476 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -214,7 +214,12 @@ Changelog\n - |Enhancement| :class:`compose.ColumnTransformer` now allows DataFrame input to\n have its columns appear in a changed order in `transform`. Further, columns that\n are dropped will not be required in transform, and additional columns will be\n- ignored if `remainder='drop'`. :pr:`19263` by `Thomas Fan`_\n+ ignored if `remainder='drop'`. :pr:`19263` by `Thomas Fan`_.\n+\n+- |Enhancement| Adds `**predict_params` keyword argument to\n+ :meth:`compose.TransformedTargetRegressor.predict` that passes keyword\n+ argument to the regressor.\n+ :pr:`19244` by :user:`Ricardo <ricardojnf>`.\n \n - |FIX| :meth:`compose.ColumnTransformer.get_feature_names` supports\n non-string feature names returned by any of its transformers.\n" } ]
1.00
6ab86fb34baf7429e52cb184a3535d4fd99d02d7
[ "sklearn/compose/tests/test_target.py::test_transform_target_regressor_functions", "sklearn/compose/tests/test_target.py::test_transform_target_regressor_1d_transformer[X0-y0]", "sklearn/compose/tests/test_target.py::test_transform_target_regressor_2d_transformer[X1-y1]", "sklearn/compose/tests/test_target.py::test_transform_target_regressor_error", "sklearn/compose/tests/test_target.py::test_transform_target_regressor_2d_transformer[X0-y0]", "sklearn/compose/tests/test_target.py::test_transform_target_regressor_2d_transformer_multioutput", "sklearn/compose/tests/test_target.py::test_transform_target_regressor_3d_target", "sklearn/compose/tests/test_target.py::test_transform_target_regressor_count_fit[False]", "sklearn/compose/tests/test_target.py::test_transform_target_regressor_route_pipeline", "sklearn/compose/tests/test_target.py::test_transform_target_regressor_ensure_y_array", "sklearn/compose/tests/test_target.py::test_transform_target_regressor_pass_fit_parameters", "sklearn/compose/tests/test_target.py::test_transform_target_regressor_multi_to_single", "sklearn/compose/tests/test_target.py::test_transform_target_regressor_1d_transformer[X1-y1]", "sklearn/compose/tests/test_target.py::test_transform_target_regressor_count_fit[True]", "sklearn/compose/tests/test_target.py::test_transform_target_regressor_invertible", "sklearn/compose/tests/test_target.py::test_transform_target_regressor_functions_multioutput" ]
[ "sklearn/compose/tests/test_target.py::test_transform_target_regressor_pass_extra_predict_parameters" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 269a5d46e71b2..7202ab4e00476 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -214,7 +214,12 @@ Changelog\n - |Enhancement| :class:`compose.ColumnTransformer` now allows DataFrame input to\n have its columns appear in a changed order in `transform`. Further, columns that\n are dropped will not be required in transform, and additional columns will be\n- ignored if `remainder='drop'`. :pr:`<PRID>` by `<NAME>`_\n+ ignored if `remainder='drop'`. :pr:`<PRID>` by `<NAME>`_.\n+\n+- |Enhancement| Adds `**predict_params` keyword argument to\n+ :meth:`compose.TransformedTargetRegressor.predict` that passes keyword\n+ argument to the regressor.\n+ :pr:`<PRID>` by :user:`<NAME>`.\n \n - |FIX| :meth:`compose.ColumnTransformer.get_feature_names` supports\n non-string feature names returned by any of its transformers.\n" } ]
diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index 269a5d46e71b2..7202ab4e00476 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -214,7 +214,12 @@ Changelog - |Enhancement| :class:`compose.ColumnTransformer` now allows DataFrame input to have its columns appear in a changed order in `transform`. Further, columns that are dropped will not be required in transform, and additional columns will be - ignored if `remainder='drop'`. :pr:`<PRID>` by `<NAME>`_ + ignored if `remainder='drop'`. :pr:`<PRID>` by `<NAME>`_. + +- |Enhancement| Adds `**predict_params` keyword argument to + :meth:`compose.TransformedTargetRegressor.predict` that passes keyword + argument to the regressor. + :pr:`<PRID>` by :user:`<NAME>`. - |FIX| :meth:`compose.ColumnTransformer.get_feature_names` supports non-string feature names returned by any of its transformers.
scikit-learn/scikit-learn
scikit-learn__scikit-learn-21079
https://github.com/scikit-learn/scikit-learn/pull/21079
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 8de10a11ca351..fdaf50364671a 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -550,6 +550,12 @@ Changelog `fit` instead of `__init__`. :pr:`21434` by :user:`Krum Arnaudov <krumeto>`. +- |API| Adds :meth:`get_feature_names_out` to + :class:`preprocessing.Normalizer`, + :class:`preprocessing.KernelCenterer`, + :class:`preprocessing.OrdinalEncoder`, and + :class:`preprocessing.Binarizer`. :pr:`21079` by `Thomas Fan`_. + :mod:`sklearn.random_projection` ................................ diff --git a/sklearn/preprocessing/_data.py b/sklearn/preprocessing/_data.py index 835694e11512c..ea38106837642 100644 --- a/sklearn/preprocessing/_data.py +++ b/sklearn/preprocessing/_data.py @@ -16,7 +16,12 @@ from scipy import optimize from scipy.special import boxcox -from ..base import BaseEstimator, TransformerMixin, _OneToOneFeatureMixin +from ..base import ( + BaseEstimator, + TransformerMixin, + _OneToOneFeatureMixin, + _ClassNamePrefixFeaturesOutMixin, +) from ..utils import check_array from ..utils.deprecation import deprecated from ..utils.extmath import _incremental_mean_and_var, row_norms @@ -1825,7 +1830,7 @@ def normalize(X, norm="l2", *, axis=1, copy=True, return_norm=False): return X -class Normalizer(TransformerMixin, BaseEstimator): +class Normalizer(_OneToOneFeatureMixin, TransformerMixin, BaseEstimator): """Normalize samples individually to unit norm. Each sample (i.e. each row of the data matrix) with at least one @@ -1996,7 +2001,7 @@ def binarize(X, *, threshold=0.0, copy=True): return X -class Binarizer(TransformerMixin, BaseEstimator): +class Binarizer(_OneToOneFeatureMixin, TransformerMixin, BaseEstimator): """Binarize data (set feature values to 0 or 1) according to a threshold. Values greater than the threshold map to 1, while values less than @@ -2119,7 +2124,7 @@ def _more_tags(self): return {"stateless": True} -class KernelCenterer(TransformerMixin, BaseEstimator): +class KernelCenterer(_ClassNamePrefixFeaturesOutMixin, TransformerMixin, BaseEstimator): r"""Center an arbitrary kernel matrix :math:`K`. Let define a kernel :math:`K` such that: @@ -2258,6 +2263,15 @@ def transform(self, K, copy=True): return K + @property + def _n_features_out(self): + """Number of transformed output features.""" + # Used by _ClassNamePrefixFeaturesOutMixin. This model preserves the + # number of input features but this is not a one-to-one mapping in the + # usual sense. Hence the choice not to use _OneToOneFeatureMixin to + # implement get_feature_names_out for this class. + return self.n_features_in_ + def _more_tags(self): return {"pairwise": True} diff --git a/sklearn/preprocessing/_encoders.py b/sklearn/preprocessing/_encoders.py index 4c59cb691527f..b7fcdf616760a 100644 --- a/sklearn/preprocessing/_encoders.py +++ b/sklearn/preprocessing/_encoders.py @@ -7,7 +7,7 @@ from scipy import sparse import numbers -from ..base import BaseEstimator, TransformerMixin +from ..base import BaseEstimator, TransformerMixin, _OneToOneFeatureMixin from ..utils import check_array, is_scalar_nan from ..utils.deprecation import deprecated from ..utils.validation import check_is_fitted @@ -731,7 +731,7 @@ def get_feature_names_out(self, input_features=None): return np.asarray(feature_names, dtype=object) -class OrdinalEncoder(_BaseEncoder): +class OrdinalEncoder(_OneToOneFeatureMixin, _BaseEncoder): """ Encode categorical features as an integer array. diff --git a/sklearn/utils/validation.py b/sklearn/utils/validation.py index a4fa30ce55035..a6459059ba2f6 100644 --- a/sklearn/utils/validation.py +++ b/sklearn/utils/validation.py @@ -1828,7 +1828,9 @@ def _get_feature_names(X): def _check_feature_names_in(estimator, input_features=None, *, generate_names=True): - """Get output feature names for transformation. + """Check `input_features` and generate names if needed. + + Commonly used in :term:`get_feature_names_out`. Parameters ---------- @@ -1842,8 +1844,10 @@ def _check_feature_names_in(estimator, input_features=None, *, generate_names=Tr match `feature_names_in_` if `feature_names_in_` is defined. generate_names : bool, default=True - Wether to generate names when `input_features` is `None` and - `estimator.feature_names_in_` is not defined. + Whether to generate names when `input_features` is `None` and + `estimator.feature_names_in_` is not defined. This is useful for transformers + that validates `input_features` but do not require them in + :term:`get_feature_names_out` e.g. `PCA`. Returns -------
diff --git a/sklearn/preprocessing/tests/test_data.py b/sklearn/preprocessing/tests/test_data.py index 3476e40dd9bbc..ee326aba1b3de 100644 --- a/sklearn/preprocessing/tests/test_data.py +++ b/sklearn/preprocessing/tests/test_data.py @@ -45,6 +45,7 @@ from sklearn.preprocessing import power_transform from sklearn.preprocessing._data import _handle_zeros_in_scale from sklearn.preprocessing._data import BOUNDS_THRESHOLD +from sklearn.metrics.pairwise import linear_kernel from sklearn.exceptions import NotFittedError @@ -2672,6 +2673,8 @@ def test_one_to_one_features(Transformer): StandardScaler, QuantileTransformer, PowerTransformer, + Normalizer, + Binarizer, ], ) def test_one_to_one_features_pandas(Transformer): @@ -2691,3 +2694,16 @@ def test_one_to_one_features_pandas(Transformer): with pytest.raises(ValueError, match=msg): invalid_names = list("abcd") tr.get_feature_names_out(invalid_names) + + +def test_kernel_centerer_feature_names_out(): + """Test that kernel centerer `feature_names_out`.""" + + rng = np.random.RandomState(0) + X = rng.random_sample((6, 4)) + X_pairwise = linear_kernel(X) + centerer = KernelCenterer().fit(X_pairwise) + + names_out = centerer.get_feature_names_out() + samples_out2 = X_pairwise.shape[1] + assert_array_equal(names_out, [f"kernelcenterer{i}" for i in range(samples_out2)]) diff --git a/sklearn/preprocessing/tests/test_encoders.py b/sklearn/preprocessing/tests/test_encoders.py index dcc07d25af5fd..27c52088f80d9 100644 --- a/sklearn/preprocessing/tests/test_encoders.py +++ b/sklearn/preprocessing/tests/test_encoders.py @@ -1387,3 +1387,15 @@ def test_ordinal_encoder_python_integer(): assert_array_equal(encoder.categories_, np.sort(X, axis=0).T) X_trans = encoder.transform(X) assert_array_equal(X_trans, [[0], [3], [2], [1]]) + + +def test_ordinal_encoder_features_names_out_pandas(): + """Check feature names out is same as the input.""" + pd = pytest.importorskip("pandas") + + names = ["b", "c", "a"] + X = pd.DataFrame([[1, 2, 3]], columns=names) + enc = OrdinalEncoder().fit(X) + + feature_names_out = enc.get_feature_names_out() + assert_array_equal(names, feature_names_out) diff --git a/sklearn/tests/test_common.py b/sklearn/tests/test_common.py index be26202d458d1..350e1e95d9882 100644 --- a/sklearn/tests/test_common.py +++ b/sklearn/tests/test_common.py @@ -382,7 +382,6 @@ def test_pandas_column_name_consistency(estimator): GET_FEATURES_OUT_MODULES_TO_IGNORE = [ "ensemble", "kernel_approximation", - "preprocessing", ]
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 8de10a11ca351..fdaf50364671a 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -550,6 +550,12 @@ Changelog\n `fit` instead of `__init__`.\n :pr:`21434` by :user:`Krum Arnaudov <krumeto>`.\n \n+- |API| Adds :meth:`get_feature_names_out` to\n+ :class:`preprocessing.Normalizer`,\n+ :class:`preprocessing.KernelCenterer`,\n+ :class:`preprocessing.OrdinalEncoder`, and\n+ :class:`preprocessing.Binarizer`. :pr:`21079` by `Thomas Fan`_.\n+\n :mod:`sklearn.random_projection`\n ................................\n \n" } ]
1.01
6440856fbb0e1c0a048316befbf6df4e0a5765c1
[ "sklearn/preprocessing/tests/test_data.py::test_quantile_transform_sparse_ignore_zeros", "sklearn/preprocessing/tests/test_data.py::test_quantile_transform_subsampling", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[csr_matrix-float64-1e-10-100]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_equivalence_dense_sparse[None-0.5]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_pandas", "sklearn/preprocessing/tests/test_data.py::test_add_dummy_feature_csc", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_missing_value_support_pandas", "sklearn/preprocessing/tests/test_encoders.py::test_X_is_not_1D[X1-fit_transform]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse[None-True]", "sklearn/preprocessing/tests/test_encoders.py::test_encoder_dtypes_pandas", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[0-float32-False-csr_matrix-scaler1]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknown_string_dtypes[X_test1-X_train1]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[asarray-float32-10000000000.0-100]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[1.0-float32-False-asarray-scaler0]", "sklearn/preprocessing/tests/test_data.py::test_normalizer_l1", "sklearn/preprocessing/tests/test_data.py::test_scaler_n_samples_seen_with_nan[csr_matrix-True-False]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[if_binary-None-get_feature_names_out]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[1.0-float32-False-csc_matrix-scaler0]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_handle_unknown_strings", "sklearn/preprocessing/tests/test_data.py::test_scaler_n_samples_seen_with_nan[csc_matrix-False-False]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[None-None-get_feature_names]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_nans[box-cox]", "sklearn/preprocessing/tests/test_data.py::test_one_to_one_features_pandas[MaxAbsScaler]", "sklearn/preprocessing/tests/test_data.py::test_optimization_power_transformer[box-cox-0.5]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[asarray-float64-1e-10-10]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[1.0-float32-True-csc_matrix-scaler0]", "sklearn/preprocessing/tests/test_data.py::test_pairwise_deprecated", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse_transform_raise_error_with_unknown[X0-X_trans0-False]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[first-if_binary-get_feature_names_out]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[0-float32-True-csc_matrix-scaler0]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[1.0-float64-True-asarray-scaler0]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[None-if_binary-get_feature_names_out]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_2d", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[if_binary-first-get_feature_names]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[csc_matrix-float64-1-100]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[1.0-float64-False-csc_matrix-scaler0]", "sklearn/preprocessing/tests/test_data.py::test_binarizer", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_attributes[X1-True-False]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[100.0-float64-True-csr_matrix-scaler0]", "sklearn/preprocessing/tests/test_data.py::test_partial_fit_sparse_input[None]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[asarray-float64-1-100]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[csc_matrix-float64-1-10000]", "sklearn/preprocessing/tests/test_data.py::test_scaler_int", "sklearn/preprocessing/tests/test_data.py::test_robust_scale_1d_array", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[csc_matrix-float32-1e-10-10000]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_notfitted[box-cox]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[100.0-float32-True-csc_matrix-scaler0]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknown_string_dtypes[X_test0-X_train1]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse[first-False]", "sklearn/preprocessing/tests/test_data.py::test_center_kernel", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[int32-int32]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[if_binary-first-get_feature_names_out]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_numeric[int]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse_transform_raise_error_with_unknown[X0-X_trans0-True]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_attributes[X0-True-True]", "sklearn/preprocessing/tests/test_data.py::test_standard_check_array_of_inverse_transform", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[dataframe-S-S]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_warning", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names_drop[first-get_feature_names]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_equivalence_dense_sparse[None-0]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[csr_matrix-float32-1-100]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[csc_matrix-float64-1-10]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[csr_matrix-float32-1-10000]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_drop_first_explicit_categories", "sklearn/preprocessing/tests/test_data.py::test_quantile_transform_nan", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_yeojohnson_any_input[X0]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_fit_with_unseen_category", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_dtype[False-csr_matrix]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_col_zero_sparse", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_dtype[True-None]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknown_string_dtypes[X_test0-X_train2]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[csc_matrix-float32-10000000000.0-10]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[float32-int32]", "sklearn/preprocessing/tests/test_data.py::test_scaler_without_centering[None]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_raise[params1-TypeError-unknown_value should only be set when handle_unknown is 'use_encoded_value', got -2.]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[list-U-O]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[csr_matrix-float64-10000000000.0-100]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_unit_variance", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_partial_fit_numerical_stability", "sklearn/preprocessing/tests/test_data.py::test_scale_sparse_with_mean_raise_exception", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_missing_and_unknown[X1-expected_X_trans1-X_test1]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[0-float64-True-csr_matrix-scaler0]", "sklearn/preprocessing/tests/test_data.py::test_quantile_transformer_sorted_quantiles[array]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names_unicode[get_feature_names_out]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_yeojohnson_any_input[X1]", "sklearn/preprocessing/tests/test_encoders.py::test_categories[manual-sparse]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_equivalence_dense_sparse[None-0.1]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[asarray-float32-1e-10-10]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_sample_weight[sparse_csr-Xw1-X1-sample_weight1]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_has_categorical_tags[OneHotEncoder]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_drop_first_handle_unknown_ignore_warns", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[1.0-float64-False-asarray-scaler1]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_missing_and_unknown[X0-expected_X_trans0-X_test0]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[csr_matrix-float64-10000000000.0-10000]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[0-float64-False-csc_matrix-scaler1]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder[numeric]", "sklearn/preprocessing/tests/test_data.py::test_minmax_scaler_clip[feature_range0]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_specified_categories[object]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_equivalence_dense_sparse[positive-0.1]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse[None-False]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[asarray-float32-1-10]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_iris_quantiles", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_inverse[X1-True-yeo-johnson]", "sklearn/preprocessing/tests/test_data.py::test_partial_fit_sparse_input[True]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[csc_matrix-float32-10000000000.0-10000]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[csr_matrix-float32-1-10]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_1d", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype_pandas[float64]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[asarray-float32-10000000000.0-10000]", "sklearn/preprocessing/tests/test_data.py::test_maxabs_scaler_1d", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categories[missing-np.nan-object]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_dtype[False-csc_matrix]", "sklearn/preprocessing/tests/test_data.py::test_add_dummy_feature_coo", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse_if_binary", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_boxcox_strictly_positive_exception", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder[mixed]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknown_string_dtypes[X_test2-X_train1]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categories[numeric]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse_transform_raise_error_with_unknown[X1-X_trans1-False]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object-string-nan]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[asarray-float64-1-10000]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[asarray-float64-10000000000.0-10]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_specified_categories_missing_passthrough[object-None-missing-value]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[100.0-float64-False-csr_matrix-scaler1]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[asarray-float32-1-100]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[100.0-float64-True-asarray-scaler0]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[csr_matrix-float32-1e-10-100]", "sklearn/preprocessing/tests/test_encoders.py::test_invalid_drop_length[drop1]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[0-float64-True-asarray-scaler0]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[list-O-U]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_set_params", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[array-U-O]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_1d", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_copy_True[False-box-cox]", "sklearn/preprocessing/tests/test_data.py::test_quantile_transform_iris", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[numeric]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_nans[yeo-johnson]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[list-S-O]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_copy_True[True-yeo-johnson]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[list-U-S]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[None-None-get_feature_names_out]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[100.0-float32-False-csc_matrix-scaler1]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_copy_False[True-yeo-johnson]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categories[missing-float-nan-object]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_copy_False[False-box-cox]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_sparse_partial_fit_finite_variance[X_20]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names_drop[manual-get_feature_names]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_dtype[True-csr_matrix]", "sklearn/preprocessing/tests/test_data.py::test_one_to_one_features_pandas[QuantileTransformer]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[list-S-U]", "sklearn/preprocessing/tests/test_data.py::test_cv_pipeline_precomputed", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[asarray-float32-1e-10-10000]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_equivalence_dense_sparse[zeros-1]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categories[object]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype_pandas[int32]", "sklearn/preprocessing/tests/test_data.py::test_one_to_one_features[QuantileTransformer]", "sklearn/preprocessing/tests/test_data.py::test_one_to_one_features_pandas[StandardScaler]", "sklearn/preprocessing/tests/test_encoders.py::test_X_is_not_1D_pandas[fit_transform]", "sklearn/preprocessing/tests/test_data.py::test_optimization_power_transformer[yeo-johnson-1.0]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[0-float64-False-csc_matrix-scaler0]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categories[mixed]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_equivalence_dense_sparse[negative-0.5]", "sklearn/preprocessing/tests/test_data.py::test_raises_value_error_if_sample_weights_greater_than_1d", "sklearn/preprocessing/tests/test_data.py::test_kernelcenterer_non_linear_kernel", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[None-if_binary-get_feature_names]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_missing_and_unknown[X3-expected_X_trans3-X_test3]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_partial_fit", "sklearn/preprocessing/tests/test_data.py::test_one_to_one_features_pandas[MinMaxScaler]", "sklearn/preprocessing/tests/test_encoders.py::test_categories[first-sparse]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[mixed-None-nan]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_equals_if_binary", "sklearn/preprocessing/tests/test_encoders.py::test_X_is_not_1D[X0-fit_transform]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[asarray-float64-10000000000.0-100]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[array-S-O]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_sample_weight[array-Xw1-X1-sample_weight1]", "sklearn/preprocessing/tests/test_data.py::test_normalizer_max", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[numeric]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[csr_matrix-float64-1e-10-10000]", "sklearn/preprocessing/tests/test_encoders.py::test_X_is_not_1D_pandas[fit]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[dataframe-S-U]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[csc_matrix-float64-1e-10-100]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_attributes[X1-False-False]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_sample_weight[sparse_csc-Xw1-X1-sample_weight1]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_sample_weight[array-Xw0-X0-sample_weight0]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_inverse[X0-True-box-cox]", "sklearn/preprocessing/tests/test_data.py::test_scaler_n_samples_seen_with_nan[asarray-True-False]", "sklearn/preprocessing/tests/test_data.py::test_yeo_johnson_darwin_example", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[None-first-get_feature_names_out]", "sklearn/preprocessing/tests/test_data.py::test_quantile_transform_dense_toy", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_passthrough_missing_values_float", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_raise[params3-ValueError-The used value for unknown_value (1) is one of the values already used for encoding the seen categories.]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_equivalence_dense_sparse[positive-0.05]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[first-if_binary-get_feature_names]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_lambda_zero", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_inverse[X0-False-yeo-johnson]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_method_exception", "sklearn/preprocessing/tests/test_data.py::test_normalize", "sklearn/preprocessing/tests/test_data.py::test_minmax_scaler_partial_fit", "sklearn/preprocessing/tests/test_data.py::test_one_to_one_features_pandas[RobustScaler]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[1.0-float64-True-csr_matrix-scaler0]", "sklearn/preprocessing/tests/test_data.py::test_minmax_scaler_clip[feature_range1]", "sklearn/preprocessing/tests/test_data.py::test_quantile_transform_and_inverse", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_shape_exception[box-cox]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categories[string]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[dataframe-U-S]", "sklearn/preprocessing/tests/test_data.py::test_scaler_float16_overflow", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_inverse[X0-True-yeo-johnson]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[csr_matrix-float64-1-10]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[asarray-float32-10000000000.0-10]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_equivalence_dense_sparse[positive-0]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[1.0-float64-False-csr_matrix-scaler0]", "sklearn/preprocessing/tests/test_data.py::test_scaler_without_copy", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[float64-int32]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_equivalence_dense_sparse[negative-0]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names_drop[first-get_feature_names_out]", "sklearn/preprocessing/tests/test_data.py::test_scaler_n_samples_seen_with_nan[csc_matrix-True-False]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[100.0-float64-False-asarray-scaler0]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[if_binary-if_binary-get_feature_names]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[mixed-float-nan]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[array-S-U]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[csr_matrix-float32-10000000000.0-100]", "sklearn/preprocessing/tests/test_data.py::test_handle_zeros_in_scale", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_dtype[False-None]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[first-None-get_feature_names_out]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[int32-float32]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_missing_value_support_pandas_categorical[np.nan]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype_pandas[float32]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[dataframe-U-U]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[dataframe-S-O]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[0-float64-False-asarray-scaler0]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[0-float64-False-csr_matrix-scaler1]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[csr_matrix-float32-1e-10-10]", "sklearn/preprocessing/tests/test_encoders.py::test_encoder_dtypes", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[0-float32-False-csr_matrix-scaler0]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[asarray-float64-1e-10-100]", "sklearn/preprocessing/tests/test_data.py::test_fit_transform", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[0-float32-False-asarray-scaler0]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_handle_unknown", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_inverse[X1-False-yeo-johnson]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[0-float32-False-asarray-scaler1]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_sample_weight[array-Xw2-X2-sample_weight2]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[dataframe-O-O]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknown_string_dtypes[X_test1-X_train2]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[1.0-float64-False-asarray-scaler0]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_inverse[X1-False-box-cox]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_specified_categories_missing_passthrough[numeric-missing-value]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_transform_one_row_csr", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names[get_feature_names]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_not_fitted", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_drop_if_binary_handle_unknown_ignore_warns", "sklearn/preprocessing/tests/test_data.py::test_quantile_transform_axis1", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_manual[None]", "sklearn/preprocessing/tests/test_data.py::test_optimization_power_transformer[box-cox-0.1]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[asarray-float64-1-10]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[mixed-None]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[1.0-float64-False-csr_matrix-scaler1]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_attributes[X0-False-True]", "sklearn/preprocessing/tests/test_data.py::test_scaler_n_samples_seen_with_nan[asarray-False-False]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[dataframe-U-O]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categories[missing-float]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_sample_weight[sparse_csc-Xw0-X0-sample_weight0]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder[object]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_specified_categories_missing_passthrough[object-nan-missing_value]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[csr_matrix-float32-10000000000.0-10]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[0-float32-True-asarray-scaler0]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[100.0-float32-True-csr_matrix-scaler0]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[array-U-S]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_raise_categories_shape", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_iris", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_2d_arrays", "sklearn/preprocessing/tests/test_data.py::test_scaler_2d_arrays", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[first-first-get_feature_names]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[100.0-float32-True-asarray-scaler0]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_sparse_partial_fit_finite_variance[X_21]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_missing_values_get_feature_names[nan-get_feature_names]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_attributes[X0-True-False]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[1.0-float32-False-csr_matrix-scaler0]", "sklearn/preprocessing/tests/test_data.py::test_maxabs_scaler_large_negative_value", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[1.0-float32-True-csr_matrix-scaler0]", "sklearn/preprocessing/tests/test_encoders.py::test_invalid_drop_length[drop0]", "sklearn/preprocessing/tests/test_data.py::test_normalizer_max_sign", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_lambda_one", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_unsorted_categories", "sklearn/preprocessing/tests/test_data.py::test_quantile_transformer_sorted_quantiles[sparse]", "sklearn/preprocessing/tests/test_data.py::test_one_to_one_features[PowerTransformer]", "sklearn/preprocessing/tests/test_data.py::test_min_max_scaler_iris", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[asarray-float64-10000000000.0-10000]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[float64-float64]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_nan_non_float_dtype", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknown_string_dtypes[X_test1-X_train0]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[asarray-float32-1-10000]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[float64-float32]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[if_binary-if_binary-get_feature_names_out]", "sklearn/preprocessing/tests/test_data.py::test_one_to_one_features[StandardScaler]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_equivalence_dense_sparse[zeros-0.5]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_specified_categories[numeric]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object-string]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_trasform_with_partial_fit[None]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[csc_matrix-float32-1-10000]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[1.0-float32-False-asarray-scaler1]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[1.0-float64-True-csc_matrix-scaler0]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_attributes[X0-False-False]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[0-float32-True-csr_matrix-scaler0]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[csr_matrix-float64-10000000000.0-10]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_fit_transform[True-yeo-johnson]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[1.0-float32-False-csc_matrix-scaler1]", "sklearn/preprocessing/tests/test_data.py::test_maxabs_scaler_zero_variance_features", "sklearn/preprocessing/tests/test_encoders.py::test_X_is_not_1D[X0-fit]", "sklearn/preprocessing/tests/test_encoders.py::test_categories[first-dense]", "sklearn/preprocessing/tests/test_data.py::test_robust_scale_axis1", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object-None-and-nan]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names_drop[manual-get_feature_names_out]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_invalid_params[X_fit0-params0-Wrong input for parameter `drop`]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_invalid_params[X_fit2-params2-The following categories were supposed]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[csr_matrix-float64-1-100]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_raise[params0-TypeError-unknown_value should be an integer or np.nan when handle_unknown is 'use_encoded_value', got None.]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[100.0-float32-False-asarray-scaler0]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_fit_transform[False-yeo-johnson]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknown_string_dtypes[X_test0-X_train0]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[0-float64-False-csr_matrix-scaler0]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_notfitted[yeo-johnson]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_nan", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[csr_matrix-float32-1e-10-10000]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_invalid_params[X_fit1-params1-Wrong input for parameter `drop`]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[mixed-None-float-nan]", "sklearn/preprocessing/tests/test_encoders.py::test_categories[manual-dense]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[csr_matrix-float64-1-10000]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[list-O-O]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object-string-none]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[csr_matrix-float64-1e-10-10]", "sklearn/preprocessing/tests/test_data.py::test_scale_input_finiteness_validation", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[0-float64-True-csc_matrix-scaler0]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[array-U-U]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_dtype[True-csc_matrix]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[csc_matrix-float64-10000000000.0-10000]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[csc_matrix-float32-1-10]", "sklearn/preprocessing/tests/test_data.py::test_add_dummy_feature_csr", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_fit_transform[True-box-cox]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_equivalence_dense_sparse[zeros-0.05]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_sample_weight[sparse_csr-Xw0-X0-sample_weight0]", "sklearn/preprocessing/tests/test_data.py::test_minmax_scale_axis1", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_equivalence_dense_sparse[negative-0.05]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[100.0-float64-True-csc_matrix-scaler0]", "sklearn/preprocessing/tests/test_data.py::test_optimization_power_transformer[yeo-johnson-0.1]", "sklearn/preprocessing/tests/test_data.py::test_one_to_one_features[MaxAbsScaler]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_python_integer", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[list-S-S]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[dataframe-O-U]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[None-first-get_feature_names]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[100.0-float64-False-csc_matrix-scaler1]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[1.0-float32-True-asarray-scaler0]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[csc_matrix-float64-10000000000.0-10]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_equivalence_dense_sparse[positive-0.5]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_manual[nan1]", "sklearn/preprocessing/tests/test_data.py::test_quantile_transform_sparse_toy", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_missing_and_unknown[X2-expected_X_trans2-X_test2]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[mixed]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[float32-float64]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[csc_matrix-float32-1e-10-100]", "sklearn/preprocessing/tests/test_data.py::test_maxabs_scaler_partial_fit", "sklearn/preprocessing/tests/test_data.py::test_scale_function_without_centering", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[csc_matrix-float32-1-100]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_missing_value_support_pandas_categorical[pd.NA]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[first-None-get_feature_names]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_equivalence_dense_sparse[zeros-0]", "sklearn/preprocessing/tests/test_data.py::test_scaler_n_samples_seen_with_nan[csr_matrix-False-False]", "sklearn/preprocessing/tests/test_data.py::test_maxabs_scaler_transform_one_row_csr", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[100.0-float64-False-asarray-scaler1]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_equivalence_dense_sparse[positive-1]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_raise_error_for_1d_input", "sklearn/preprocessing/tests/test_data.py::test_scaler_n_samples_seen_with_nan[asarray-False-True]", "sklearn/preprocessing/tests/test_data.py::test_quantile_transform_bounds", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_equivalence_dense_sparse[None-1]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_sample_weight[sparse_csr-Xw2-X2-sample_weight2]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[0-float64-False-asarray-scaler1]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_copy_True[False-yeo-johnson]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[0-float32-False-csc_matrix-scaler1]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[array-O-O]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[0-float32-False-csc_matrix-scaler0]", "sklearn/preprocessing/tests/test_data.py::test_normalizer_l2", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_inverse", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_copy_True[True-box-cox]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_inverse[X0-False-box-cox]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[asarray-float64-1e-10-10000]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_shape_exception[yeo-johnson]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[100.0-float32-False-csr_matrix-scaler1]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names[get_feature_names_out]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_yeojohnson_any_input[X3]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_equivalence_dense_sparse[zeros-0.1]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[csc_matrix-float32-10000000000.0-100]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_equivalence_dense_sparse[negative-0.1]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_manual[nan0]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[csc_matrix-float64-1e-10-10000]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse[first-True]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_get_feature_names_deprecated", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[csc_matrix-float32-1e-10-10]", "sklearn/preprocessing/tests/test_data.py::test_quantile_transform_valid_axis", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[100.0-float32-False-csr_matrix-scaler0]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object-nan-and-None]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_zero_variance_features", "sklearn/preprocessing/tests/test_data.py::test_min_max_scaler_1d", "sklearn/preprocessing/tests/test_data.py::test_one_to_one_features[MinMaxScaler]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories_mixed_columns", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_inverse[X1-True-box-cox]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[float32-float32]", "sklearn/preprocessing/tests/test_data.py::test_add_dummy_feature", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[100.0-float32-False-asarray-scaler1]", "sklearn/preprocessing/tests/test_data.py::test_optimization_power_transformer[yeo-johnson-0.5]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_yeojohnson_any_input[X2]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[object]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_missing_values_get_feature_names[None-get_feature_names]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_missing_values_get_feature_names[nan-get_feature_names_out]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[1.0-float32-False-csr_matrix-scaler1]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[int32-float64]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[if_binary-None-get_feature_names]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_numeric[float]", "sklearn/preprocessing/tests/test_data.py::test_min_max_scaler_zero_variance_features", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_has_categorical_tags[OrdinalEncoder]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_passthrough_missing_values_float_errors_dtype", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknown_string_dtypes[X_test2-X_train0]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_trasform_with_partial_fit[True]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_error_sparse", "sklearn/preprocessing/tests/test_data.py::test_one_to_one_features_pandas[PowerTransformer]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[csc_matrix-float64-1e-10-10]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_invalid_range", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[100.0-float32-False-csc_matrix-scaler0]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknown_string_dtypes[X_test2-X_train2]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_sample_weight[sparse_csc-Xw2-X2-sample_weight2]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[csc_matrix-float64-10000000000.0-100]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names_drop[binary-get_feature_names_out]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[list-U-U]", "sklearn/preprocessing/tests/test_data.py::test_scaler_return_identity", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[array-O-U]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names_unicode[get_feature_names]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_raise[params4-ValueError-handle_unknown should be either 'error' or 'use_encoded_value', got ignore.]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_sparse", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_missing_value_support_pandas_categorical[np.nan]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_specified_categories[object-string-cat]", "sklearn/preprocessing/tests/test_data.py::test_scale_1d", "sklearn/preprocessing/tests/test_data.py::test_scaler_without_centering[True]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names_drop[binary-get_feature_names]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_fit_transform[False-box-cox]", "sklearn/preprocessing/tests/test_data.py::test_quantile_transform_check_error", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[1.0-float64-False-csc_matrix-scaler1]", "sklearn/preprocessing/tests/test_data.py::test_scaler_n_samples_seen_with_nan[asarray-True-True]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_sparse_dense", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_missing_values_get_feature_names[None-get_feature_names_out]", "sklearn/preprocessing/tests/test_data.py::test_fit_cold_start", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[100.0-float64-False-csc_matrix-scaler0]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_equivalence_dense_sparse[None-0.05]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_equivalence_dense_sparse[negative-1]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[asarray-float32-1e-10-100]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[mixed-nan]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_near_constant_features[csr_matrix-float32-10000000000.0-10000]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_string_categories[array-S-S]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[first-first-get_feature_names_out]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_raise[params2-TypeError-unknown_value should be an integer or np.nan when handle_unknown is 'use_encoded_value', got bla.]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_missing_value_support_pandas_categorical[pd.NA]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_copy_False[True-box-cox]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_constant_features[100.0-float64-False-csr_matrix-scaler0]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_string", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse_transform_raise_error_with_unknown[X1-X_trans1-True]", "sklearn/preprocessing/tests/test_data.py::test_one_to_one_features[RobustScaler]", "sklearn/preprocessing/tests/test_encoders.py::test_X_is_not_1D[X1-fit]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_copy_False[False-yeo-johnson]" ]
[ "sklearn/preprocessing/tests/test_data.py::test_one_to_one_features_pandas[Normalizer]", "sklearn/preprocessing/tests/test_data.py::test_one_to_one_features_pandas[Binarizer]", "sklearn/preprocessing/tests/test_data.py::test_kernel_centerer_feature_names_out", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_features_names_out_pandas" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 8de10a11ca351..fdaf50364671a 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -550,6 +550,12 @@ Changelog\n `fit` instead of `__init__`.\n :pr:`<PRID>` by :user:`<NAME>`.\n \n+- |API| Adds :meth:`get_feature_names_out` to\n+ :class:`preprocessing.Normalizer`,\n+ :class:`preprocessing.KernelCenterer`,\n+ :class:`preprocessing.OrdinalEncoder`, and\n+ :class:`preprocessing.Binarizer`. :pr:`<PRID>` by `<NAME>`_.\n+\n :mod:`sklearn.random_projection`\n ................................\n \n" } ]
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 8de10a11ca351..fdaf50364671a 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -550,6 +550,12 @@ Changelog `fit` instead of `__init__`. :pr:`<PRID>` by :user:`<NAME>`. +- |API| Adds :meth:`get_feature_names_out` to + :class:`preprocessing.Normalizer`, + :class:`preprocessing.KernelCenterer`, + :class:`preprocessing.OrdinalEncoder`, and + :class:`preprocessing.Binarizer`. :pr:`<PRID>` by `<NAME>`_. + :mod:`sklearn.random_projection` ................................
scikit-learn/scikit-learn
scikit-learn__scikit-learn-17169
https://github.com/scikit-learn/scikit-learn/pull/17169
diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst index c658bc6b12452..d56914f874b42 100644 --- a/doc/modules/classes.rst +++ b/doc/modules/classes.rst @@ -560,6 +560,7 @@ From text feature_selection.chi2 feature_selection.f_classif feature_selection.f_regression + feature_selection.r_regression feature_selection.mutual_info_classif feature_selection.mutual_info_regression diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index a566d03ae1bbc..eaf02942cf316 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -103,6 +103,14 @@ Changelog input strings would result in negative indices in the transformed data. :pr:`19035` by :user:`Liu Yu <ly648499246>`. +:mod:`sklearn.feature_selection` +................................ + +- |Feature| :func:`feature_selection.r_regression` computes Pearson's R + correlation coefficients between the features and the target. + :pr:`17169` by `Dmytro Lituiev <DSLituiev>` + and `Julien Jerphanion <jjerphan>`. + :mod:`sklearn.inspection` ......................... diff --git a/sklearn/feature_selection/__init__.py b/sklearn/feature_selection/__init__.py index 86e8a2af39084..ef894b40065de 100644 --- a/sklearn/feature_selection/__init__.py +++ b/sklearn/feature_selection/__init__.py @@ -8,6 +8,7 @@ from ._univariate_selection import f_classif from ._univariate_selection import f_oneway from ._univariate_selection import f_regression +from ._univariate_selection import r_regression from ._univariate_selection import SelectPercentile from ._univariate_selection import SelectKBest from ._univariate_selection import SelectFpr @@ -44,6 +45,7 @@ 'f_classif', 'f_oneway', 'f_regression', + 'r_regression', 'mutual_info_classif', 'mutual_info_regression', 'SelectorMixin'] diff --git a/sklearn/feature_selection/_univariate_selection.py b/sklearn/feature_selection/_univariate_selection.py index 0656e27d6e30f..7fc69a4b13cf2 100644 --- a/sklearn/feature_selection/_univariate_selection.py +++ b/sklearn/feature_selection/_univariate_selection.py @@ -229,60 +229,53 @@ def chi2(X, y): return _chisquare(observed, expected) -@_deprecate_positional_args -def f_regression(X, y, *, center=True): - """Univariate linear regression tests. +def r_regression(X, y, *, center=True): + """Compute Pearson's r for each features and the target. + + Pearson's r is also known as the Pearson correlation coefficient. + + .. versionadded:: 1.0 Linear model for testing the individual effect of each of many regressors. This is a scoring function to be used in a feature selection procedure, not a free standing feature selection procedure. - This is done in 2 steps: - - 1. The correlation between each regressor and the target is computed, - that is, ((X[:, i] - mean(X[:, i])) * (y - mean_y)) / (std(X[:, i]) * - std(y)). - 2. It is converted to an F score then to a p-value. + The cross correlation between each regressor and the target is computed + as ((X[:, i] - mean(X[:, i])) * (y - mean_y)) / (std(X[:, i]) * std(y)). For more on usage see the :ref:`User Guide <univariate_feature_selection>`. Parameters ---------- - X : {array-like, sparse matrix} shape = (n_samples, n_features) - The set of regressors that will be tested sequentially. + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The data matrix. - y : array of shape(n_samples). - The data matrix + y : array-like of shape (n_samples,) + The target vector. center : bool, default=True - If true, X and y will be centered. + Whether or not to center the data matrix `X` and the target vector `y`. + By default, `X` and `y` will be centered. Returns ------- - F : array, shape=(n_features,) - F values of features. - - pval : array, shape=(n_features,) - p-values of F-scores. + correlation_coefficient : ndarray of shape (n_features,) + Pearson's R correlation coefficients of features. See Also -------- - mutual_info_regression : Mutual information for a continuous target. - f_classif : ANOVA F-value between label/feature for classification tasks. - chi2 : Chi-squared stats of non-negative features for classification tasks. - SelectKBest : Select features based on the k highest scores. - SelectFpr : Select features based on a false positive rate test. - SelectFdr : Select features based on an estimated false discovery rate. - SelectFwe : Select features based on family-wise error rate. - SelectPercentile : Select features based on percentile of the highest - scores. + f_regression: Univariate linear regression tests returning f-statistic + and p-values + mutual_info_regression: Mutual information for a continuous target. + f_classif: ANOVA F-value between label/feature for classification tasks. + chi2: Chi-squared stats of non-negative features for classification tasks. """ X, y = check_X_y(X, y, accept_sparse=['csr', 'csc', 'coo'], dtype=np.float64) n_samples = X.shape[0] - # compute centered values - # note that E[(x - mean(x))*(y - mean(y))] = E[x*(y - mean(y))], so we + # Compute centered values + # Note that E[(x - mean(x))*(y - mean(y))] = E[x*(y - mean(y))], so we # need not center X if center: y = y - np.mean(y) @@ -290,22 +283,86 @@ def f_regression(X, y, *, center=True): X_means = X.mean(axis=0).getA1() else: X_means = X.mean(axis=0) - # compute the scaled standard deviations via moments + # Compute the scaled standard deviations via moments X_norms = np.sqrt(row_norms(X.T, squared=True) - n_samples * X_means ** 2) else: X_norms = row_norms(X.T) - # compute the correlation - corr = safe_sparse_dot(y, X) - corr /= X_norms - corr /= np.linalg.norm(y) + correlation_coefficient = safe_sparse_dot(y, X) + correlation_coefficient /= X_norms + correlation_coefficient /= np.linalg.norm(y) + return correlation_coefficient + + +@_deprecate_positional_args +def f_regression(X, y, *, center=True): + """Univariate linear regression tests returning F-statistic and p-values. + + Quick linear model for testing the effect of a single regressor, + sequentially for many regressors. + + This is done in 2 steps: + + 1. The cross correlation between each regressor and the target is computed, + that is, ((X[:, i] - mean(X[:, i])) * (y - mean_y)) / (std(X[:, i]) * + std(y)) using r_regression function. + 2. It is converted to an F score and then to a p-value. + + :func:`f_regression` is derived from :func:`r_regression` and will rank + features in the same order if all the features are positively correlated + with the target. + + Note however that contrary to :func:`f_regression`, :func:`r_regression` + values lie in [-1, 1] and can thus be negative. :func:`f_regression` is + therefore recommended as a feature selection criterion to identify + potentially predictive feature for a downstream classifier, irrespective of + the sign of the association with the target variable. + + Furthermore :func:`f_regression` returns p-values while + :func:`r_regression` does not. + + Read more in the :ref:`User Guide <univariate_feature_selection>`. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The data matrix. + + y : array-like of shape (n_samples,) + The target vector. + + center : bool, default=True + Whether or not to center the data matrix `X` and the target vector `y`. + By default, `X` and `y` will be centered. + + Returns + ------- + f_statistic : ndarray of shape (n_features,) + F-statistic for each feature. + + p_values : ndarray of shape (n_features,) + P-values associated with the F-statistic. + + See Also + -------- + r_regression: Pearson's R between label/feature for regression tasks. + f_classif: ANOVA F-value between label/feature for classification tasks. + chi2: Chi-squared stats of non-negative features for classification tasks. + SelectKBest: Select features based on the k highest scores. + SelectFpr: Select features based on a false positive rate test. + SelectFdr: Select features based on an estimated false discovery rate. + SelectFwe: Select features based on family-wise error rate. + SelectPercentile: Select features based on percentile of the highest + scores. + """ + correlation_coefficient = r_regression(X, y, center=center) + deg_of_freedom = y.size - (2 if center else 1) - # convert to p-value - degrees_of_freedom = y.size - (2 if center else 1) - F = corr ** 2 / (1 - corr ** 2) * degrees_of_freedom - pv = stats.f.sf(F, 1, degrees_of_freedom) - return F, pv + corr_coef_squared = correlation_coefficient ** 2 + f_statistic = corr_coef_squared / (1 - corr_coef_squared) * deg_of_freedom + p_values = stats.f.sf(f_statistic, 1, deg_of_freedom) + return f_statistic, p_values ###################################################################### @@ -502,12 +559,12 @@ class SelectKBest(_BaseFilter): See Also -------- - f_classif : ANOVA F-value between label/feature for classification tasks. - mutual_info_classif : Mutual information for a discrete target. - chi2 : Chi-squared stats of non-negative features for classification tasks. - f_regression : F-value between label/feature for regression tasks. - mutual_info_regression : Mutual information for a continuous target. - SelectPercentile : Select features based on percentile of the highest + f_classif: ANOVA F-value between label/feature for classification tasks. + mutual_info_classif: Mutual information for a discrete target. + chi2: Chi-squared stats of non-negative features for classification tasks. + f_regression: F-value between label/feature for regression tasks. + mutual_info_regression: Mutual information for a continuous target. + SelectPercentile: Select features based on percentile of the highest scores. SelectFpr : Select features based on a false positive rate test. SelectFdr : Select features based on an estimated false discovery rate.
diff --git a/sklearn/feature_selection/tests/test_feature_select.py b/sklearn/feature_selection/tests/test_feature_select.py index 61f709094147e..852c8228b2a76 100644 --- a/sklearn/feature_selection/tests/test_feature_select.py +++ b/sklearn/feature_selection/tests/test_feature_select.py @@ -4,11 +4,12 @@ import itertools import warnings import numpy as np +from numpy.testing import assert_allclose from scipy import stats, sparse import pytest -from sklearn.utils._testing import assert_almost_equal +from sklearn.utils._testing import assert_almost_equal, _convert_container from sklearn.utils._testing import assert_array_equal from sklearn.utils._testing import assert_array_almost_equal from sklearn.utils._testing import assert_warns @@ -18,9 +19,20 @@ from sklearn.datasets import make_classification, make_regression from sklearn.feature_selection import ( - chi2, f_classif, f_oneway, f_regression, mutual_info_classif, - mutual_info_regression, SelectPercentile, SelectKBest, SelectFpr, - SelectFdr, SelectFwe, GenericUnivariateSelect) + chi2, + f_classif, + f_oneway, + f_regression, + GenericUnivariateSelect, + mutual_info_classif, + mutual_info_regression, + r_regression, + SelectPercentile, + SelectKBest, + SelectFpr, + SelectFdr, + SelectFwe, +) ############################################################################## @@ -71,6 +83,27 @@ def test_f_classif(): assert_array_almost_equal(pv_sparse, pv) [email protected]("center", [True, False]) +def test_r_regression(center): + X, y = make_regression(n_samples=2000, n_features=20, n_informative=5, + shuffle=False, random_state=0) + + corr_coeffs = r_regression(X, y, center=center) + assert ((-1 < corr_coeffs).all()) + assert ((corr_coeffs < 1).all()) + + sparse_X = _convert_container(X, "sparse") + + sparse_corr_coeffs = r_regression(sparse_X, y, center=center) + assert_allclose(sparse_corr_coeffs, corr_coeffs) + + # Testing against numpy for reference + Z = np.hstack((X, y[:, np.newaxis])) + correlation_matrix = np.corrcoef(Z, rowvar=False) + np_corr_coeffs = correlation_matrix[:-1, -1] + assert_array_almost_equal(np_corr_coeffs, corr_coeffs, decimal=3) + + def test_f_regression(): # Test whether the F test yields meaningful results # on a simple simulated regression problem @@ -87,14 +120,14 @@ def test_f_regression(): # with centering, compare with sparse F, pv = f_regression(X, y, center=True) F_sparse, pv_sparse = f_regression(sparse.csr_matrix(X), y, center=True) - assert_array_almost_equal(F_sparse, F) - assert_array_almost_equal(pv_sparse, pv) + assert_allclose(F_sparse, F) + assert_allclose(pv_sparse, pv) # again without centering, compare with sparse F, pv = f_regression(X, y, center=False) F_sparse, pv_sparse = f_regression(sparse.csr_matrix(X), y, center=False) - assert_array_almost_equal(F_sparse, F) - assert_array_almost_equal(pv_sparse, pv) + assert_allclose(F_sparse, F) + assert_allclose(pv_sparse, pv) def test_f_regression_input_dtype(): @@ -106,8 +139,8 @@ def test_f_regression_input_dtype(): F1, pv1 = f_regression(X, y) F2, pv2 = f_regression(X, y.astype(float)) - assert_array_almost_equal(F1, F2, 5) - assert_array_almost_equal(pv1, pv2, 5) + assert_allclose(F1, F2, 5) + assert_allclose(pv1, pv2, 5) def test_f_regression_center(): @@ -123,7 +156,7 @@ def test_f_regression_center(): F1, _ = f_regression(X, Y, center=True) F2, _ = f_regression(X, Y, center=False) - assert_array_almost_equal(F1 * (n_samples - 1.) / (n_samples - 2.), F2) + assert_allclose(F1 * (n_samples - 1.) / (n_samples - 2.), F2) assert_almost_equal(F2[0], 0.232558139) # value from statsmodels OLS @@ -262,7 +295,7 @@ def test_select_heuristics_classif(): f_classif, mode=mode, param=0.01).fit(X, y).transform(X) assert_array_equal(X_r, X_r2) support = univariate_filter.get_support() - assert_array_almost_equal(support, gtruth) + assert_allclose(support, gtruth) ############################################################################## @@ -272,7 +305,7 @@ def test_select_heuristics_classif(): def assert_best_scores_kept(score_filter): scores = score_filter.scores_ support = score_filter.get_support() - assert_array_almost_equal(np.sort(scores[support]), + assert_allclose(np.sort(scores[support]), np.sort(scores)[-support.sum():])
[ { "path": "doc/modules/classes.rst", "old_path": "a/doc/modules/classes.rst", "new_path": "b/doc/modules/classes.rst", "metadata": "diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst\nindex c658bc6b12452..d56914f874b42 100644\n--- a/doc/modules/classes.rst\n+++ b/doc/modules/classes.rst\n@@ -560,6 +560,7 @@ From text\n feature_selection.chi2\n feature_selection.f_classif\n feature_selection.f_regression\n+ feature_selection.r_regression\n feature_selection.mutual_info_classif\n feature_selection.mutual_info_regression\n \n" }, { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex a566d03ae1bbc..eaf02942cf316 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -103,6 +103,14 @@ Changelog\n input strings would result in negative indices in the transformed data.\n :pr:`19035` by :user:`Liu Yu <ly648499246>`.\n \n+:mod:`sklearn.feature_selection`\n+................................\n+\n+- |Feature| :func:`feature_selection.r_regression` computes Pearson's R\n+ correlation coefficients between the features and the target.\n+ :pr:`17169` by `Dmytro Lituiev <DSLituiev>`\n+ and `Julien Jerphanion <jjerphan>`.\n+\n :mod:`sklearn.inspection`\n .........................\n \n" } ]
1.00
579e7de7f38f9f514ff2b2be049e67b14e723d17
[]
[ "sklearn/feature_selection/tests/test_feature_select.py::test_r_regression[True]", "sklearn/feature_selection/tests/test_feature_select.py::test_select_fdr_regression[1-0.01]", "sklearn/feature_selection/tests/test_feature_select.py::test_select_fdr_regression[5-0.1]", "sklearn/feature_selection/tests/test_feature_select.py::test_select_fdr_regression[10-0.001]", "sklearn/feature_selection/tests/test_feature_select.py::test_select_percentile_classif", "sklearn/feature_selection/tests/test_feature_select.py::test_mutual_info_classif", "sklearn/feature_selection/tests/test_feature_select.py::test_f_classif_multi_class", "sklearn/feature_selection/tests/test_feature_select.py::test_invalid_k", "sklearn/feature_selection/tests/test_feature_select.py::test_select_fdr_regression[10-0.1]", "sklearn/feature_selection/tests/test_feature_select.py::test_select_fwe_regression", "sklearn/feature_selection/tests/test_feature_select.py::test_select_percentile_regression_full", "sklearn/feature_selection/tests/test_feature_select.py::test_select_kbest_zero", "sklearn/feature_selection/tests/test_feature_select.py::test_f_regression", "sklearn/feature_selection/tests/test_feature_select.py::test_scorefunc_multilabel", "sklearn/feature_selection/tests/test_feature_select.py::test_select_fdr_regression[5-0.01]", "sklearn/feature_selection/tests/test_feature_select.py::test_boundary_case_ch2", "sklearn/feature_selection/tests/test_feature_select.py::test_f_classif", "sklearn/feature_selection/tests/test_feature_select.py::test_select_kbest_classif", "sklearn/feature_selection/tests/test_feature_select.py::test_tied_pvalues", "sklearn/feature_selection/tests/test_feature_select.py::test_selectpercentile_tiebreaking", "sklearn/feature_selection/tests/test_feature_select.py::test_nans", "sklearn/feature_selection/tests/test_feature_select.py::test_select_fdr_regression[1-0.1]", "sklearn/feature_selection/tests/test_feature_select.py::test_r_regression[False]", "sklearn/feature_selection/tests/test_feature_select.py::test_f_regression_input_dtype", "sklearn/feature_selection/tests/test_feature_select.py::test_select_heuristics_regression", "sklearn/feature_selection/tests/test_feature_select.py::test_no_feature_selected", "sklearn/feature_selection/tests/test_feature_select.py::test_f_classif_constant_feature", "sklearn/feature_selection/tests/test_feature_select.py::test_select_kbest_regression", "sklearn/feature_selection/tests/test_feature_select.py::test_invalid_percentile", "sklearn/feature_selection/tests/test_feature_select.py::test_select_fdr_regression[5-0.001]", "sklearn/feature_selection/tests/test_feature_select.py::test_f_oneway_vs_scipy_stats", "sklearn/feature_selection/tests/test_feature_select.py::test_f_regression_center", "sklearn/feature_selection/tests/test_feature_select.py::test_selectkbest_tiebreaking", "sklearn/feature_selection/tests/test_feature_select.py::test_score_func_error", "sklearn/feature_selection/tests/test_feature_select.py::test_select_heuristics_classif", "sklearn/feature_selection/tests/test_feature_select.py::test_select_fdr_regression[10-0.01]", "sklearn/feature_selection/tests/test_feature_select.py::test_mutual_info_regression", "sklearn/feature_selection/tests/test_feature_select.py::test_f_oneway_ints", "sklearn/feature_selection/tests/test_feature_select.py::test_tied_scores", "sklearn/feature_selection/tests/test_feature_select.py::test_select_fdr_regression[1-0.001]", "sklearn/feature_selection/tests/test_feature_select.py::test_select_kbest_all", "sklearn/feature_selection/tests/test_feature_select.py::test_select_percentile_classif_sparse", "sklearn/feature_selection/tests/test_feature_select.py::test_select_percentile_regression" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/modules/classes.rst", "old_path": "a/doc/modules/classes.rst", "new_path": "b/doc/modules/classes.rst", "metadata": "diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst\nindex c658bc6b12452..d56914f874b42 100644\n--- a/doc/modules/classes.rst\n+++ b/doc/modules/classes.rst\n@@ -560,6 +560,7 @@ From text\n feature_selection.chi2\n feature_selection.f_classif\n feature_selection.f_regression\n+ feature_selection.r_regression\n feature_selection.mutual_info_classif\n feature_selection.mutual_info_regression\n \n" }, { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex a566d03ae1bbc..eaf02942cf316 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -103,6 +103,14 @@ Changelog\n input strings would result in negative indices in the transformed data.\n :pr:`<PRID>` by :user:`<NAME>`.\n \n+:mod:`sklearn.feature_selection`\n+................................\n+\n+- |Feature| :func:`feature_selection.r_regression` computes Pearson's R\n+ correlation coefficients between the features and the target.\n+ :pr:`<PRID>` by `Dmytro Lituiev <DSLituiev>`\n+ and `Julien Jerphanion <jjerphan>`.\n+\n :mod:`sklearn.inspection`\n .........................\n \n" } ]
diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst index c658bc6b12452..d56914f874b42 100644 --- a/doc/modules/classes.rst +++ b/doc/modules/classes.rst @@ -560,6 +560,7 @@ From text feature_selection.chi2 feature_selection.f_classif feature_selection.f_regression + feature_selection.r_regression feature_selection.mutual_info_classif feature_selection.mutual_info_regression diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index a566d03ae1bbc..eaf02942cf316 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -103,6 +103,14 @@ Changelog input strings would result in negative indices in the transformed data. :pr:`<PRID>` by :user:`<NAME>`. +:mod:`sklearn.feature_selection` +................................ + +- |Feature| :func:`feature_selection.r_regression` computes Pearson's R + correlation coefficients between the features and the target. + :pr:`<PRID>` by `Dmytro Lituiev <DSLituiev>` + and `Julien Jerphanion <jjerphan>`. + :mod:`sklearn.inspection` .........................
scikit-learn/scikit-learn
scikit-learn__scikit-learn-20380
https://github.com/scikit-learn/scikit-learn/pull/20380
diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index ecb4b5972a669..ce252a502e28d 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -337,6 +337,11 @@ Changelog when the variance threshold is negative. :pr:`20207` by :user:`Tomohiro Endo <europeanplaice>` +- |Enhancement| :func:`feature_selection.RFE.fit` accepts additional estimator + parameters that are passed directly to the estimator's `fit` method. + :pr:`20380` by :user:`Iván Pulido <ijpulidos>`, :user:`Felipe Bidu <fbidu>`, + :user:`Gil Rutter <g-rutter>`, and :user:`Adrin Jalali <adrinjalali>`. + - |FIX| Fix a bug in :func:`isotonic.isotonic_regression` where the `sample_weight` passed by a user were overwritten during the fit. :pr:`20515` by :user:`Carsten Allefeld <allefeld>`. diff --git a/sklearn/feature_selection/_rfe.py b/sklearn/feature_selection/_rfe.py index 3471a0b939b59..8d64f05a48b4d 100644 --- a/sklearn/feature_selection/_rfe.py +++ b/sklearn/feature_selection/_rfe.py @@ -192,7 +192,7 @@ def classes_(self): """ return self.estimator_.classes_ - def fit(self, X, y): + def fit(self, X, y, **fit_params): """Fit the RFE model and then the underlying estimator on the selected features. Parameters @@ -203,14 +203,18 @@ def fit(self, X, y): y : array-like of shape (n_samples,) The target values. + **fit_params : dict + Additional parameters passed to the `fit` method of the underlying + estimator. + Returns ------- self : object Fitted estimator. """ - return self._fit(X, y) + return self._fit(X, y, **fit_params) - def _fit(self, X, y, step_score=None): + def _fit(self, X, y, step_score=None, **fit_params): # Parameter step_score controls the calculation of self.scores_ # step_score is not exposed to users # and is used when implementing RFECV @@ -269,7 +273,7 @@ def _fit(self, X, y, step_score=None): if self.verbose > 0: print("Fitting estimator with %d features." % np.sum(support_)) - estimator.fit(X[:, features], y) + estimator.fit(X[:, features], y, **fit_params) # Get importance and rank them importances = _get_feature_importances( @@ -296,7 +300,7 @@ def _fit(self, X, y, step_score=None): # Set final attributes features = np.arange(n_features)[support_] self.estimator_ = clone(self.estimator) - self.estimator_.fit(X[:, features], y) + self.estimator_.fit(X[:, features], y, **fit_params) # Compute step score when only n_features_to_select features left if step_score: @@ -325,7 +329,7 @@ def predict(self, X): return self.estimator_.predict(self.transform(X)) @if_delegate_has_method(delegate="estimator") - def score(self, X, y): + def score(self, X, y, **fit_params): """Reduce X to the selected features and return the score of the underlying estimator. Parameters @@ -336,6 +340,12 @@ def score(self, X, y): y : array of shape [n_samples] The target values. + **fit_params : dict + Parameters to pass to the `score` method of the underlying + estimator. + + .. versionadded:: 1.0 + Returns ------- score : float @@ -343,7 +353,7 @@ def score(self, X, y): features returned by `rfe.transform(X)` and `y`. """ check_is_fitted(self) - return self.estimator_.score(self.transform(X), y) + return self.estimator_.score(self.transform(X), y, **fit_params) def _get_support_mask(self): check_is_fitted(self)
diff --git a/sklearn/feature_selection/tests/test_rfe.py b/sklearn/feature_selection/tests/test_rfe.py index 190672ea248d3..d2e9ab16aafc5 100644 --- a/sklearn/feature_selection/tests/test_rfe.py +++ b/sklearn/feature_selection/tests/test_rfe.py @@ -8,6 +8,7 @@ from numpy.testing import assert_array_almost_equal, assert_array_equal from scipy import sparse +from sklearn.base import BaseEstimator, ClassifierMixin from sklearn.feature_selection import RFE, RFECV from sklearn.datasets import load_iris, make_friedman1 from sklearn.metrics import zero_one_loss @@ -108,6 +109,31 @@ def test_rfe(): assert_array_almost_equal(X_r, X_r_sparse.toarray()) +def test_RFE_fit_score_params(): + # Make sure RFE passes the metadata down to fit and score methods of the + # underlying estimator + class TestEstimator(BaseEstimator, ClassifierMixin): + def fit(self, X, y, prop=None): + if prop is None: + raise ValueError("fit: prop cannot be None") + self.svc_ = SVC(kernel="linear").fit(X, y) + self.coef_ = self.svc_.coef_ + return self + + def score(self, X, y, prop=None): + if prop is None: + raise ValueError("score: prop cannot be None") + return self.svc_.score(X, y) + + X, y = load_iris(return_X_y=True) + with pytest.raises(ValueError, match="fit: prop cannot be None"): + RFE(estimator=TestEstimator()).fit(X, y) + with pytest.raises(ValueError, match="score: prop cannot be None"): + RFE(estimator=TestEstimator()).fit(X, y, prop="foo").score(X, y) + + RFE(estimator=TestEstimator()).fit(X, y, prop="foo").score(X, y, prop="foo") + + @pytest.mark.parametrize("n_features_to_select", [-1, 2.1]) def test_rfe_invalid_n_features_errors(n_features_to_select): clf = SVC(kernel="linear")
[ { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex ecb4b5972a669..ce252a502e28d 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -337,6 +337,11 @@ Changelog\n when the variance threshold is negative.\n :pr:`20207` by :user:`Tomohiro Endo <europeanplaice>`\n \n+- |Enhancement| :func:`feature_selection.RFE.fit` accepts additional estimator\n+ parameters that are passed directly to the estimator's `fit` method.\n+ :pr:`20380` by :user:`Iván Pulido <ijpulidos>`, :user:`Felipe Bidu <fbidu>`,\n+ :user:`Gil Rutter <g-rutter>`, and :user:`Adrin Jalali <adrinjalali>`.\n+\n - |FIX| Fix a bug in :func:`isotonic.isotonic_regression` where the\n `sample_weight` passed by a user were overwritten during the fit.\n :pr:`20515` by :user:`Carsten Allefeld <allefeld>`.\n" } ]
1.00
238451d55ed57c3d16bc42f6a74f5f0126a7c700
[ "sklearn/feature_selection/tests/test_rfe.py::test_rfe_wrapped_estimator[RFECV-4-importance_getter0]", "sklearn/feature_selection/tests/test_rfe.py::test_rfe_importance_getter_validation[RFE-auto-ValueError]", "sklearn/feature_selection/tests/test_rfe.py::test_rfe_importance_getter_validation[RFECV-<lambda>-AttributeError]", "sklearn/feature_selection/tests/test_rfe.py::test_multioutput[RFE]", "sklearn/feature_selection/tests/test_rfe.py::test_rfe_importance_getter_validation[RFECV-importance_getter3-ValueError]", "sklearn/feature_selection/tests/test_rfe.py::test_rfe_wrapped_estimator[RFECV-4-regressor_.coef_]", "sklearn/feature_selection/tests/test_rfe.py::test_rfe_cv_n_jobs", "sklearn/feature_selection/tests/test_rfe.py::test_rfe_features_importance", "sklearn/feature_selection/tests/test_rfe.py::test_w_pipeline_2d_coef_", "sklearn/feature_selection/tests/test_rfe.py::test_rfe_invalid_n_features_errors[2.1]", "sklearn/feature_selection/tests/test_rfe.py::test_rfe_allow_nan_inf_in_x[None]", "sklearn/feature_selection/tests/test_rfe.py::test_rfe_allow_nan_inf_in_x[5]", "sklearn/feature_selection/tests/test_rfe.py::test_rfe_importance_getter_validation[RFE-random-AttributeError]", "sklearn/feature_selection/tests/test_rfe.py::test_rfe_estimator_tags", "sklearn/feature_selection/tests/test_rfe.py::test_rfe_percent_n_features", "sklearn/feature_selection/tests/test_rfe.py::test_rfe_importance_getter_validation[RFECV-auto-ValueError]", "sklearn/feature_selection/tests/test_rfe.py::test_rfe", "sklearn/feature_selection/tests/test_rfe.py::test_rfe_min_step", "sklearn/feature_selection/tests/test_rfe.py::test_rfe_invalid_n_features_errors[-1]", "sklearn/feature_selection/tests/test_rfe.py::test_rfe_importance_getter_validation[RFE-<lambda>-AttributeError]", "sklearn/feature_selection/tests/test_rfe.py::test_rfe_importance_getter_validation[RFECV-random-AttributeError]", "sklearn/feature_selection/tests/test_rfe.py::test_rfe_importance_getter_validation[RFE-importance_getter3-ValueError]", "sklearn/feature_selection/tests/test_rfe.py::test_multioutput[RFECV]", "sklearn/feature_selection/tests/test_rfe.py::test_rfecv_verbose_output", "sklearn/feature_selection/tests/test_rfe.py::test_rfecv_mockclassifier", "sklearn/feature_selection/tests/test_rfe.py::test_rfecv_grid_scores_size", "sklearn/feature_selection/tests/test_rfe.py::test_rfecv", "sklearn/feature_selection/tests/test_rfe.py::test_rfe_cv_groups", "sklearn/feature_selection/tests/test_rfe.py::test_rfe_wrapped_estimator[RFE-5-importance_getter0]", "sklearn/feature_selection/tests/test_rfe.py::test_rfe_wrapped_estimator[RFE-5-regressor_.coef_]", "sklearn/feature_selection/tests/test_rfe.py::test_rfe_mockclassifier", "sklearn/feature_selection/tests/test_rfe.py::test_number_of_subsets_of_features" ]
[ "sklearn/feature_selection/tests/test_rfe.py::test_RFE_fit_score_params" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex ecb4b5972a669..ce252a502e28d 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -337,6 +337,11 @@ Changelog\n when the variance threshold is negative.\n :pr:`<PRID>` by :user:`<NAME>`\n \n+- |Enhancement| :func:`feature_selection.RFE.fit` accepts additional estimator\n+ parameters that are passed directly to the estimator's `fit` method.\n+ :pr:`<PRID>` by :user:`<NAME>`, :user:`<NAME>`,\n+ :user:`<NAME>`, and :user:`<NAME>`.\n+\n - |FIX| Fix a bug in :func:`isotonic.isotonic_regression` where the\n `sample_weight` passed by a user were overwritten during the fit.\n :pr:`<PRID>` by :user:`<NAME>`.\n" } ]
diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index ecb4b5972a669..ce252a502e28d 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -337,6 +337,11 @@ Changelog when the variance threshold is negative. :pr:`<PRID>` by :user:`<NAME>` +- |Enhancement| :func:`feature_selection.RFE.fit` accepts additional estimator + parameters that are passed directly to the estimator's `fit` method. + :pr:`<PRID>` by :user:`<NAME>`, :user:`<NAME>`, + :user:`<NAME>`, and :user:`<NAME>`. + - |FIX| Fix a bug in :func:`isotonic.isotonic_regression` where the `sample_weight` passed by a user were overwritten during the fit. :pr:`<PRID>` by :user:`<NAME>`.
scikit-learn/scikit-learn
scikit-learn__scikit-learn-20431
https://github.com/scikit-learn/scikit-learn/pull/20431
diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index 3b23360fe60c4..3bb2c6457d8ab 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -386,6 +386,13 @@ Changelog :mod:`sklearn.inspection` ......................... +- |Enhancement| Add `max_samples` parameter in + :func:`inspection._permutation_importance`. It enables to draw a subset of + the samples to compute the permutation importance. This is useful to + keep the method tractable when evaluating feature importance on + large datasets. + :pr:`20431` by :user:`Oliver Pfaffel <o1iv3r>`. + - |Fix| Allow multiple scorers input to :func:`~sklearn.inspection.permutation_importance`. :pr:`19411` by :user:`Simona Maggio <simonamaggio>`. diff --git a/sklearn/inspection/_permutation_importance.py b/sklearn/inspection/_permutation_importance.py index e8d2260d60ca0..f94219e7d6190 100644 --- a/sklearn/inspection/_permutation_importance.py +++ b/sklearn/inspection/_permutation_importance.py @@ -1,11 +1,13 @@ """Permutation importance for estimators.""" +import numbers import numpy as np from joblib import Parallel +from ..ensemble._bagging import _generate_indices from ..metrics import check_scoring from ..metrics._scorer import _check_multimetric_scoring, _MultimetricScorer from ..model_selection._validation import _aggregate_score_dicts -from ..utils import Bunch +from ..utils import Bunch, _safe_indexing from ..utils import check_random_state from ..utils import check_array from ..utils.fixes import delayed @@ -18,7 +20,15 @@ def _weights_scorer(scorer, estimator, X, y, sample_weight): def _calculate_permutation_scores( - estimator, X, y, sample_weight, col_idx, random_state, n_repeats, scorer + estimator, + X, + y, + sample_weight, + col_idx, + random_state, + n_repeats, + scorer, + max_samples, ): """Calculate score when `col_idx` is permuted.""" random_state = check_random_state(random_state) @@ -29,10 +39,20 @@ def _calculate_permutation_scores( # if X is large it will be automatically be backed by a readonly memory map # (memmap). X.copy() on the other hand is always guaranteed to return a # writable data-structure whose columns can be shuffled inplace. - X_permuted = X.copy() + if max_samples < X.shape[0]: + row_indices = _generate_indices( + random_state=random_state, + bootstrap=False, + n_population=X.shape[0], + n_samples=max_samples, + ) + X_permuted = _safe_indexing(X, row_indices, axis=0) + y = _safe_indexing(y, row_indices, axis=0) + else: + X_permuted = X.copy() scores = [] - shuffling_idx = np.arange(X.shape[0]) + shuffling_idx = np.arange(X_permuted.shape[0]) for _ in range(n_repeats): random_state.shuffle(shuffling_idx) if hasattr(X_permuted, "iloc"): @@ -90,6 +110,7 @@ def permutation_importance( n_jobs=None, random_state=None, sample_weight=None, + max_samples=1.0, ): """Permutation importance for feature evaluation [BRE]_. @@ -157,6 +178,22 @@ def permutation_importance( .. versionadded:: 0.24 + max_samples : int or float, default=1.0 + The number of samples to draw from X to compute feature importance + in each repeat (without replacement). + + - If int, then draw `max_samples` samples. + - If float, then draw `max_samples * X.shape[0]` samples. + - If `max_samples` is equal to `1.0` or `X.shape[0]`, all samples + will be used. + + While using this option may provide less accurate importance estimates, + it keeps the method tractable when evaluating feature importance on + large datasets. In combination with `n_repeats`, this allows to control + the computational speed vs statistical accuracy trade-off of this method. + + .. versionadded:: 1.0 + Returns ------- result : :class:`~sklearn.utils.Bunch` or dict of such instances @@ -204,6 +241,11 @@ def permutation_importance( random_state = check_random_state(random_state) random_seed = random_state.randint(np.iinfo(np.int32).max + 1) + if not isinstance(max_samples, numbers.Integral): + max_samples = int(max_samples * X.shape[0]) + elif not (0 < max_samples <= X.shape[0]): + raise ValueError("max_samples must be in (0, n_samples]") + if callable(scoring): scorer = scoring elif scoring is None or isinstance(scoring, str): @@ -216,7 +258,15 @@ def permutation_importance( scores = Parallel(n_jobs=n_jobs)( delayed(_calculate_permutation_scores)( - estimator, X, y, sample_weight, col_idx, random_seed, n_repeats, scorer + estimator, + X, + y, + sample_weight, + col_idx, + random_seed, + n_repeats, + scorer, + max_samples, ) for col_idx in range(X.shape[1]) )
diff --git a/sklearn/inspection/tests/test_permutation_importance.py b/sklearn/inspection/tests/test_permutation_importance.py index 13386624363ed..46065cac4f560 100644 --- a/sklearn/inspection/tests/test_permutation_importance.py +++ b/sklearn/inspection/tests/test_permutation_importance.py @@ -31,7 +31,8 @@ @pytest.mark.parametrize("n_jobs", [1, 2]) -def test_permutation_importance_correlated_feature_regression(n_jobs): [email protected]("max_samples", [0.5, 1.0]) +def test_permutation_importance_correlated_feature_regression(n_jobs, max_samples): # Make sure that feature highly correlated to the target have a higher # importance rng = np.random.RandomState(42) @@ -46,7 +47,13 @@ def test_permutation_importance_correlated_feature_regression(n_jobs): clf.fit(X, y) result = permutation_importance( - clf, X, y, n_repeats=n_repeats, random_state=rng, n_jobs=n_jobs + clf, + X, + y, + n_repeats=n_repeats, + random_state=rng, + n_jobs=n_jobs, + max_samples=max_samples, ) assert result.importances.shape == (X.shape[1], n_repeats) @@ -57,7 +64,10 @@ def test_permutation_importance_correlated_feature_regression(n_jobs): @pytest.mark.parametrize("n_jobs", [1, 2]) -def test_permutation_importance_correlated_feature_regression_pandas(n_jobs): [email protected]("max_samples", [0.5, 1.0]) +def test_permutation_importance_correlated_feature_regression_pandas( + n_jobs, max_samples +): pd = pytest.importorskip("pandas") # Make sure that feature highly correlated to the target have a higher @@ -77,7 +87,13 @@ def test_permutation_importance_correlated_feature_regression_pandas(n_jobs): clf.fit(X, y) result = permutation_importance( - clf, X, y, n_repeats=n_repeats, random_state=rng, n_jobs=n_jobs + clf, + X, + y, + n_repeats=n_repeats, + random_state=rng, + n_jobs=n_jobs, + max_samples=max_samples, ) assert result.importances.shape == (X.shape[1], n_repeats) @@ -88,7 +104,8 @@ def test_permutation_importance_correlated_feature_regression_pandas(n_jobs): @pytest.mark.parametrize("n_jobs", [1, 2]) -def test_robustness_to_high_cardinality_noisy_feature(n_jobs, seed=42): [email protected]("max_samples", [0.5, 1.0]) +def test_robustness_to_high_cardinality_noisy_feature(n_jobs, max_samples, seed=42): # Permutation variable importance should not be affected by the high # cardinality bias of traditional feature importances, especially when # computed on a held-out test set: @@ -137,7 +154,13 @@ def test_robustness_to_high_cardinality_noisy_feature(n_jobs, seed=42): # Let's check that permutation-based feature importances do not have this # problem. r = permutation_importance( - clf, X_test, y_test, n_repeats=n_repeats, random_state=rng, n_jobs=n_jobs + clf, + X_test, + y_test, + n_repeats=n_repeats, + random_state=rng, + n_jobs=n_jobs, + max_samples=max_samples, ) assert r.importances.shape == (X.shape[1], n_repeats) @@ -233,14 +256,16 @@ def test_permutation_importance_linear_regresssion(): ) -def test_permutation_importance_equivalence_sequential_parallel(): [email protected]("max_samples", [500, 1.0]) +def test_permutation_importance_equivalence_sequential_parallel(max_samples): # regression test to make sure that sequential and parallel calls will # output the same results. + # Also tests that max_samples equal to number of samples is equivalent to 1.0 X, y = make_regression(n_samples=500, n_features=10, random_state=0) lr = LinearRegression().fit(X, y) importance_sequential = permutation_importance( - lr, X, y, n_repeats=5, random_state=0, n_jobs=1 + lr, X, y, n_repeats=5, random_state=0, n_jobs=1, max_samples=max_samples ) # First check that the problem is structured enough and that the model is @@ -273,7 +298,8 @@ def test_permutation_importance_equivalence_sequential_parallel(): @pytest.mark.parametrize("n_jobs", [None, 1, 2]) -def test_permutation_importance_equivalence_array_dataframe(n_jobs): [email protected]("max_samples", [0.5, 1.0]) +def test_permutation_importance_equivalence_array_dataframe(n_jobs, max_samples): # This test checks that the column shuffling logic has the same behavior # both a dataframe and a simple numpy array. pd = pytest.importorskip("pandas") @@ -310,7 +336,13 @@ def test_permutation_importance_equivalence_array_dataframe(n_jobs): n_repeats = 3 importance_array = permutation_importance( - rf, X, y, n_repeats=n_repeats, random_state=0, n_jobs=n_jobs + rf, + X, + y, + n_repeats=n_repeats, + random_state=0, + n_jobs=n_jobs, + max_samples=max_samples, ) # First check that the problem is structured enough and that the model is @@ -322,7 +354,13 @@ def test_permutation_importance_equivalence_array_dataframe(n_jobs): # Now check that importances computed on dataframe matche the values # of those computed on the array with the same data. importance_dataframe = permutation_importance( - rf, X_df, y, n_repeats=n_repeats, random_state=0, n_jobs=n_jobs + rf, + X_df, + y, + n_repeats=n_repeats, + random_state=0, + n_jobs=n_jobs, + max_samples=max_samples, ) assert_allclose( importance_array["importances"], importance_dataframe["importances"] @@ -485,3 +523,20 @@ def test_permutation_importance_multi_metric(list_single_scorer, multi_scorer): ) assert_allclose(multi_result.importances, single_result.importances) + + [email protected]("max_samples", [-1, 5]) +def test_permutation_importance_max_samples_error(max_samples): + """Check that a proper error message is raised when `max_samples` is not + set to a valid input value. + """ + X = np.array([(1.0, 2.0, 3.0, 4.0)]).T + y = np.array([0, 1, 0, 1]) + + clf = LogisticRegression() + clf.fit(X, y) + + err_msg = r"max_samples must be in \(0, n_samples\]" + + with pytest.raises(ValueError, match=err_msg): + permutation_importance(clf, X, y, max_samples=max_samples)
[ { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 3b23360fe60c4..3bb2c6457d8ab 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -386,6 +386,13 @@ Changelog\n :mod:`sklearn.inspection`\n .........................\n \n+- |Enhancement| Add `max_samples` parameter in\n+ :func:`inspection._permutation_importance`. It enables to draw a subset of\n+ the samples to compute the permutation importance. This is useful to\n+ keep the method tractable when evaluating feature importance on\n+ large datasets.\n+ :pr:`20431` by :user:`Oliver Pfaffel <o1iv3r>`.\n+\n - |Fix| Allow multiple scorers input to\n :func:`~sklearn.inspection.permutation_importance`.\n :pr:`19411` by :user:`Simona Maggio <simonamaggio>`.\n" } ]
1.00
81165cabad383db2ff7fd856e467041eea9b55dc
[ "sklearn/inspection/tests/test_permutation_importance.py::test_permutation_importance_no_weights_scoring_function", "sklearn/inspection/tests/test_permutation_importance.py::test_permutation_importance_large_memmaped_data[dataframe]", "sklearn/inspection/tests/test_permutation_importance.py::test_permutation_importance_mixed_types", "sklearn/inspection/tests/test_permutation_importance.py::test_permutation_importance_multi_metric[list_single_scorer2-<lambda>]", "sklearn/inspection/tests/test_permutation_importance.py::test_permutation_importance_linear_regresssion", "sklearn/inspection/tests/test_permutation_importance.py::test_permutation_importance_large_memmaped_data[array]", "sklearn/inspection/tests/test_permutation_importance.py::test_permutation_importance_multi_metric[list_single_scorer0-multi_scorer0]", "sklearn/inspection/tests/test_permutation_importance.py::test_permutation_importance_mixed_types_pandas", "sklearn/inspection/tests/test_permutation_importance.py::test_permutation_importance_sample_weight", "sklearn/inspection/tests/test_permutation_importance.py::test_permutation_importance_multi_metric[list_single_scorer1-multi_scorer1]" ]
[ "sklearn/inspection/tests/test_permutation_importance.py::test_permutation_importance_equivalence_array_dataframe[0.5-None]", "sklearn/inspection/tests/test_permutation_importance.py::test_permutation_importance_equivalence_array_dataframe[1.0-None]", "sklearn/inspection/tests/test_permutation_importance.py::test_permutation_importance_correlated_feature_regression[0.5-2]", "sklearn/inspection/tests/test_permutation_importance.py::test_robustness_to_high_cardinality_noisy_feature[0.5-2]", "sklearn/inspection/tests/test_permutation_importance.py::test_robustness_to_high_cardinality_noisy_feature[1.0-2]", "sklearn/inspection/tests/test_permutation_importance.py::test_permutation_importance_correlated_feature_regression[1.0-1]", "sklearn/inspection/tests/test_permutation_importance.py::test_permutation_importance_equivalence_array_dataframe[1.0-1]", "sklearn/inspection/tests/test_permutation_importance.py::test_permutation_importance_max_samples_error[5]", "sklearn/inspection/tests/test_permutation_importance.py::test_permutation_importance_equivalence_array_dataframe[1.0-2]", "sklearn/inspection/tests/test_permutation_importance.py::test_permutation_importance_equivalence_sequential_parallel[1.0]", "sklearn/inspection/tests/test_permutation_importance.py::test_permutation_importance_correlated_feature_regression_pandas[0.5-2]", "sklearn/inspection/tests/test_permutation_importance.py::test_permutation_importance_equivalence_array_dataframe[0.5-1]", "sklearn/inspection/tests/test_permutation_importance.py::test_permutation_importance_correlated_feature_regression_pandas[1.0-2]", "sklearn/inspection/tests/test_permutation_importance.py::test_permutation_importance_correlated_feature_regression_pandas[0.5-1]", "sklearn/inspection/tests/test_permutation_importance.py::test_permutation_importance_correlated_feature_regression_pandas[1.0-1]", "sklearn/inspection/tests/test_permutation_importance.py::test_permutation_importance_equivalence_sequential_parallel[500]", "sklearn/inspection/tests/test_permutation_importance.py::test_permutation_importance_equivalence_array_dataframe[0.5-2]", "sklearn/inspection/tests/test_permutation_importance.py::test_robustness_to_high_cardinality_noisy_feature[0.5-1]", "sklearn/inspection/tests/test_permutation_importance.py::test_robustness_to_high_cardinality_noisy_feature[1.0-1]", "sklearn/inspection/tests/test_permutation_importance.py::test_permutation_importance_correlated_feature_regression[1.0-2]", "sklearn/inspection/tests/test_permutation_importance.py::test_permutation_importance_correlated_feature_regression[0.5-1]", "sklearn/inspection/tests/test_permutation_importance.py::test_permutation_importance_max_samples_error[-1]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 3b23360fe60c4..3bb2c6457d8ab 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -386,6 +386,13 @@ Changelog\n :mod:`sklearn.inspection`\n .........................\n \n+- |Enhancement| Add `max_samples` parameter in\n+ :func:`inspection._permutation_importance`. It enables to draw a subset of\n+ the samples to compute the permutation importance. This is useful to\n+ keep the method tractable when evaluating feature importance on\n+ large datasets.\n+ :pr:`<PRID>` by :user:`<NAME>`.\n+\n - |Fix| Allow multiple scorers input to\n :func:`~sklearn.inspection.permutation_importance`.\n :pr:`<PRID>` by :user:`<NAME>`.\n" } ]
diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index 3b23360fe60c4..3bb2c6457d8ab 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -386,6 +386,13 @@ Changelog :mod:`sklearn.inspection` ......................... +- |Enhancement| Add `max_samples` parameter in + :func:`inspection._permutation_importance`. It enables to draw a subset of + the samples to compute the permutation importance. This is useful to + keep the method tractable when evaluating feature importance on + large datasets. + :pr:`<PRID>` by :user:`<NAME>`. + - |Fix| Allow multiple scorers input to :func:`~sklearn.inspection.permutation_importance`. :pr:`<PRID>` by :user:`<NAME>`.
scikit-learn/scikit-learn
scikit-learn__scikit-learn-19836
https://github.com/scikit-learn/scikit-learn/pull/19836
diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index ece6ff15ac51b..b66c87815bae7 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -270,6 +270,10 @@ Changelog :class:`ensemble.StackingClassifier` and :class:`ensemble.StackingRegressor`. :pr:`19564` by `Thomas Fan`_. +- |Enhancement| Documented and tested support of the Poisson criterion for + :class:`ensemble.RandomForestRegressor`. :pr:`19836` by + :user:`Brian Sun <bsun94>`. + - |Fix| Fixed the range of the argument max_samples to be (0.0, 1.0] in :class:`ensemble.RandomForestClassifier`, :class:`ensemble.RandomForestRegressor`, where `max_samples=1.0` is diff --git a/sklearn/ensemble/_forest.py b/sklearn/ensemble/_forest.py index 06ca0c171efc6..bc29c0362bb3e 100644 --- a/sklearn/ensemble/_forest.py +++ b/sklearn/ensemble/_forest.py @@ -323,6 +323,14 @@ def fit(self, X, y, sample_weight=None): # [:, np.newaxis] that does not. y = np.reshape(y, (-1, 1)) + if self.criterion == "poisson": + if np.any(y < 0): + raise ValueError("Some value(s) of y are negative which is " + "not allowed for Poisson regression.") + if np.sum(y) <= 0: + raise ValueError("Sum of y is not strictly positive which " + "is necessary for Poisson regression.") + self.n_outputs_ = y.shape[1] y, expanded_class_weight = self._validate_y_class_weight(y) @@ -1324,16 +1332,20 @@ class RandomForestRegressor(ForestRegressor): The default value of ``n_estimators`` changed from 10 to 100 in 0.22. - criterion : {"squared_error", "mse", "absolute_error", "mae"}, \ + criterion : {"squared_error", "mse", "absolute_error", "poisson"}, \ default="squared_error" The function to measure the quality of a split. Supported criteria are "squared_error" for the mean squared error, which is equal to - variance reduction as feature selection criterion, and "absolute_error" - for the mean absolute error. + variance reduction as feature selection criterion, "absolute_error" + for the mean absolute error, and "poisson" which uses reduction in + Poisson deviance to find splits. .. versionadded:: 0.18 Mean Absolute Error (MAE) criterion. + .. versionadded:: 1.0 + Poisson criterion. + .. deprecated:: 1.0 Criterion "mse" was deprecated in v1.0 and will be removed in version 1.2. Use `criterion="squared_error"` which is equivalent.
diff --git a/sklearn/ensemble/tests/test_forest.py b/sklearn/ensemble/tests/test_forest.py index 52615d037cf63..6c4aa905abe55 100644 --- a/sklearn/ensemble/tests/test_forest.py +++ b/sklearn/ensemble/tests/test_forest.py @@ -27,6 +27,8 @@ import joblib from numpy.testing import assert_allclose +from sklearn.dummy import DummyRegressor +from sklearn.metrics import mean_poisson_deviance from sklearn.utils._testing import assert_almost_equal from sklearn.utils._testing import assert_array_almost_equal from sklearn.utils._testing import assert_array_equal @@ -185,6 +187,76 @@ def test_regression(name, criterion): check_regression_criterion(name, criterion) +def test_poisson_vs_mse(): + """Test that random forest with poisson criterion performs better than + mse for a poisson target.""" + rng = np.random.RandomState(42) + n_train, n_test, n_features = 500, 500, 10 + X = datasets.make_low_rank_matrix(n_samples=n_train + n_test, + n_features=n_features, random_state=rng) + X = np.abs(X) + X /= np.max(np.abs(X), axis=0) + # We create a log-linear Poisson model + coef = rng.uniform(low=-4, high=1, size=n_features) + y = rng.poisson(lam=np.exp(X @ coef)) + X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=n_test, + random_state=rng) + + forest_poi = RandomForestRegressor( + criterion="poisson", + min_samples_leaf=10, + max_features="sqrt", + random_state=rng) + forest_mse = RandomForestRegressor( + criterion="squared_error", + min_samples_leaf=10, + max_features="sqrt", + random_state=rng) + + forest_poi.fit(X_train, y_train) + forest_mse.fit(X_train, y_train) + dummy = DummyRegressor(strategy="mean").fit(X_train, y_train) + + for X, y, val in [(X_train, y_train, "train"), (X_test, y_test, "test")]: + metric_poi = mean_poisson_deviance(y, forest_poi.predict(X)) + # squared_error forest might produce non-positive predictions => clip + # If y = 0 for those, the poisson deviance gets too good. + # If we drew more samples, we would eventually get y > 0 and the + # poisson deviance would explode, i.e. be undefined. Therefore, we do + # not clip to a tiny value like 1e-15, but to 0.1. This acts like a + # mild penalty to the non-positive predictions. + metric_mse = mean_poisson_deviance( + y, + np.clip(forest_mse.predict(X), 1e-6, None)) + metric_dummy = mean_poisson_deviance(y, dummy.predict(X)) + # As squared_error might correctly predict 0 in train set, its train + # score can be better than Poisson. This is no longer the case for the + # test set. But keep the above comment for clipping in mind. + if val == "test": + assert metric_poi < metric_mse + assert metric_poi < metric_dummy + + [email protected]('criterion', ('poisson', 'squared_error')) +def test_balance_property_random_forest(criterion): + """"Test that sum(y_pred)==sum(y_true) on the training set.""" + rng = np.random.RandomState(42) + n_train, n_test, n_features = 500, 500, 10 + X = datasets.make_low_rank_matrix(n_samples=n_train + n_test, + n_features=n_features, random_state=rng) + + coef = rng.uniform(low=-2, high=2, size=n_features) / np.max(X, axis=0) + y = rng.poisson(lam=np.exp(X @ coef)) + + reg = RandomForestRegressor(criterion=criterion, + n_estimators=10, + bootstrap=False, + random_state=rng) + reg.fit(X, y) + + assert np.sum(reg.predict(X)) == pytest.approx(np.sum(y)) + + def check_regressor_attributes(name): # Regression models should not have a classes_ attribute. r = FOREST_REGRESSORS[name](random_state=0) @@ -1367,6 +1439,23 @@ def test_min_impurity_decrease(): assert tree.min_impurity_decrease == 0.1 +def test_poisson_y_positive_check(): + est = RandomForestRegressor(criterion="poisson") + X = np.zeros((3, 3)) + + y = [-1, 1, 3] + err_msg = (r"Some value\(s\) of y are negative which is " + r"not allowed for Poisson regression.") + with pytest.raises(ValueError, match=err_msg): + est.fit(X, y) + + y = [0, 0, 0] + err_msg = (r"Sum of y is not strictly positive which " + r"is necessary for Poisson regression.") + with pytest.raises(ValueError, match=err_msg): + est.fit(X, y) + + # mypy error: Variable "DEFAULT_JOBLIB_BACKEND" is not valid type class MyBackend(DEFAULT_JOBLIB_BACKEND): # type: ignore def __init__(self, *args, **kwargs):
[ { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex ece6ff15ac51b..b66c87815bae7 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -270,6 +270,10 @@ Changelog\n :class:`ensemble.StackingClassifier` and :class:`ensemble.StackingRegressor`.\n :pr:`19564` by `Thomas Fan`_.\n \n+- |Enhancement| Documented and tested support of the Poisson criterion for\n+ :class:`ensemble.RandomForestRegressor`. :pr:`19836` by\n+ :user:`Brian Sun <bsun94>`.\n+\n - |Fix| Fixed the range of the argument max_samples to be (0.0, 1.0]\n in :class:`ensemble.RandomForestClassifier`,\n :class:`ensemble.RandomForestRegressor`, where `max_samples=1.0` is\n" } ]
1.00
a1a6b3a9602283792ec4091cdb990be1afab9163
[ "sklearn/ensemble/tests/test_forest.py::test_forest_classifier_oob[X2-y2-0.65-sparse_csr-RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_random_trees_embedding_raise_error_oob[False]", "sklearn/ensemble/tests/test_forest.py::test_regressor_attributes[RandomForestRegressor]", "sklearn/ensemble/tests/test_forest.py::test_max_leaf_nodes_max_depth[ExtraTreesRegressor]", "sklearn/ensemble/tests/test_forest.py::test_warm_start[ExtraTreesRegressor]", "sklearn/ensemble/tests/test_forest.py::test_little_tree_with_small_max_samples[RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_max_samples_boundary_classifiers[RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_importances[RandomForestClassifier-entropy-float32]", "sklearn/ensemble/tests/test_forest.py::test_max_samples_exceptions[1000000000-ValueError-`max_samples` must be in range 1 to 6 but got value 1000000000-ExtraTreesRegressor]", "sklearn/ensemble/tests/test_forest.py::test_iris[gini-RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_forest_oob_error[X0-y0-params0-Out of bag estimation only available if bootstrap=True-ExtraTreesRegressor]", "sklearn/ensemble/tests/test_forest.py::test_regression[friedman_mse-ExtraTreesRegressor]", "sklearn/ensemble/tests/test_forest.py::test_class_weights[ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_min_samples_leaf[RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_warm_start_oob[ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_forest_classifier_oob[X2-y2-0.65-sparse_csc-ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_distribution", "sklearn/ensemble/tests/test_forest.py::test_max_samples_exceptions[max_samples6-TypeError-`max_samples` should be int or float, but got type '\\\\<class 'numpy.ndarray'\\\\>'-RandomForestRegressor]", "sklearn/ensemble/tests/test_forest.py::test_warm_start_equal_n_estimators[RandomTreesEmbedding]", "sklearn/ensemble/tests/test_forest.py::test_gridsearch[ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_min_samples_leaf[RandomForestRegressor]", "sklearn/ensemble/tests/test_forest.py::test_sparse_input[coo_matrix-ExtraTreesRegressor]", "sklearn/ensemble/tests/test_forest.py::test_iris[gini-ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_forest_classifier_oob[X3-y3-0.18-sparse_csc-RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_sparse_input[coo_matrix-RandomTreesEmbedding]", "sklearn/ensemble/tests/test_forest.py::test_warm_start[RandomForestRegressor]", "sklearn/ensemble/tests/test_forest.py::test_importances[ExtraTreesRegressor-friedman_mse-float32]", "sklearn/ensemble/tests/test_forest.py::test_warm_start[RandomTreesEmbedding]", "sklearn/ensemble/tests/test_forest.py::test_importances[RandomForestRegressor-squared_error-float32]", "sklearn/ensemble/tests/test_forest.py::test_multioutput_string[RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_sparse_input[coo_matrix-RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_classification_toy[RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_importances[ExtraTreesClassifier-entropy-float64]", "sklearn/ensemble/tests/test_forest.py::test_importances[RandomForestClassifier-gini-float64]", "sklearn/ensemble/tests/test_forest.py::test_forest_classifier_oob[X3-y3-0.18-array-ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_pickle[RandomForestRegressor]", "sklearn/ensemble/tests/test_forest.py::test_forest_oob_error[X0-y0-params0-Out of bag estimation only available if bootstrap=True-ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_pickle[ExtraTreesRegressor]", "sklearn/ensemble/tests/test_forest.py::test_forest_classifier_oob[X0-y0-0.9-array-RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_max_samples_exceptions[nan-ValueError-`max_samples` must be in range \\\\(0.0, 1.0\\\\] but got value nan-RandomForestRegressor]", "sklearn/ensemble/tests/test_forest.py::test_poisson_vs_mse", "sklearn/ensemble/tests/test_forest.py::test_memory_layout[float64-ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_forest_oob_error[X1-y1-params1-The type of target cannot be used to compute OOB estimates-ExtraTreesRegressor]", "sklearn/ensemble/tests/test_forest.py::test_forest_regressor_oob[X0-y0-0.7-sparse_csc-ExtraTreesRegressor]", "sklearn/ensemble/tests/test_forest.py::test_warm_start_smaller_n_estimators[RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_forest_y_sparse", "sklearn/ensemble/tests/test_forest.py::test_importances[ExtraTreesRegressor-absolute_error-float32]", "sklearn/ensemble/tests/test_forest.py::test_warm_start_clear[RandomTreesEmbedding]", "sklearn/ensemble/tests/test_forest.py::test_random_hasher", "sklearn/ensemble/tests/test_forest.py::test_forest_classifier_oob[X1-y1-0.65-array-ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_dtype_convert", "sklearn/ensemble/tests/test_forest.py::test_forest_regressor_oob[X1-y1-0.55-sparse_csc-RandomForestRegressor]", "sklearn/ensemble/tests/test_forest.py::test_random_trees_dense_equal", "sklearn/ensemble/tests/test_forest.py::test_memory_layout[float32-RandomForestRegressor]", "sklearn/ensemble/tests/test_forest.py::test_backend_respected", "sklearn/ensemble/tests/test_forest.py::test_max_samples_exceptions[inf-ValueError-`max_samples` must be in range \\\\(0.0, 1.0\\\\] but got value inf-ExtraTreesRegressor]", "sklearn/ensemble/tests/test_forest.py::test_class_weights[RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_max_samples_exceptions[nan-ValueError-`max_samples` must be in range \\\\(0.0, 1.0\\\\] but got value nan-RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_importances[ExtraTreesClassifier-gini-float64]", "sklearn/ensemble/tests/test_forest.py::test_max_samples_exceptions[0.0-ValueError-`max_samples` must be in range \\\\(0.0, 1.0\\\\] but got value 0.0-ExtraTreesRegressor]", "sklearn/ensemble/tests/test_forest.py::test_forest_classifier_oob[X2-y2-0.65-array-RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_regression[squared_error-ExtraTreesRegressor]", "sklearn/ensemble/tests/test_forest.py::test_memory_layout[float64-RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_forest_classifier_oob[X3-y3-0.18-sparse_csr-ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_min_weight_fraction_leaf[RandomForestRegressor]", "sklearn/ensemble/tests/test_forest.py::test_sparse_input[csc_matrix-RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_balance_property_random_forest[poisson]", "sklearn/ensemble/tests/test_forest.py::test_parallel[ExtraTreesRegressor]", "sklearn/ensemble/tests/test_forest.py::test_parallel[RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_regression[squared_error-RandomForestRegressor]", "sklearn/ensemble/tests/test_forest.py::test_importances[ExtraTreesRegressor-friedman_mse-float64]", "sklearn/ensemble/tests/test_forest.py::test_iris[entropy-ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_forest_regressor_oob[X1-y1-0.55-sparse_csr-ExtraTreesRegressor]", "sklearn/ensemble/tests/test_forest.py::test_n_features_deprecation[RandomForestRegressor]", "sklearn/ensemble/tests/test_forest.py::test_decision_path[RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_max_samples_exceptions[str max_samples?!-TypeError-`max_samples` should be int or float, but got type '\\\\<class 'str'\\\\>'-RandomForestRegressor]", "sklearn/ensemble/tests/test_forest.py::test_warm_start_oob[ExtraTreesRegressor]", "sklearn/ensemble/tests/test_forest.py::test_sparse_input[csr_matrix-RandomTreesEmbedding]", "sklearn/ensemble/tests/test_forest.py::test_forest_regressor_oob[X0-y0-0.7-sparse_csc-RandomForestRegressor]", "sklearn/ensemble/tests/test_forest.py::test_warm_start_equal_n_estimators[ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_multioutput[ExtraTreesRegressor]", "sklearn/ensemble/tests/test_forest.py::test_max_leaf_nodes_max_depth[RandomForestRegressor]", "sklearn/ensemble/tests/test_forest.py::test_memory_layout[float32-ExtraTreesRegressor]", "sklearn/ensemble/tests/test_forest.py::test_forest_classifier_oob[X0-y0-0.9-sparse_csr-RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_max_leaf_nodes_max_depth[ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_sparse_input[csr_matrix-RandomForestRegressor]", "sklearn/ensemble/tests/test_forest.py::test_max_samples_exceptions[max_samples6-TypeError-`max_samples` should be int or float, but got type '\\\\<class 'numpy.ndarray'\\\\>'-RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_importances[ExtraTreesClassifier-gini-float32]", "sklearn/ensemble/tests/test_forest.py::test_max_samples_exceptions[max_samples6-TypeError-`max_samples` should be int or float, but got type '\\\\<class 'numpy.ndarray'\\\\>'-ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_min_samples_split[RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_warm_start_smaller_n_estimators[RandomTreesEmbedding]", "sklearn/ensemble/tests/test_forest.py::test_max_samples_exceptions[str max_samples?!-TypeError-`max_samples` should be int or float, but got type '\\\\<class 'str'\\\\>'-ExtraTreesRegressor]", "sklearn/ensemble/tests/test_forest.py::test_min_samples_leaf[ExtraTreesRegressor]", "sklearn/ensemble/tests/test_forest.py::test_max_samples_exceptions[inf-ValueError-`max_samples` must be in range \\\\(0.0, 1.0\\\\] but got value inf-RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_max_samples_exceptions[1000000000-ValueError-`max_samples` must be in range 1 to 6 but got value 1000000000-RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_importances[RandomForestRegressor-friedman_mse-float64]", "sklearn/ensemble/tests/test_forest.py::test_1d_input[RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_class_weight_balanced_and_bootstrap_multi_output[RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_forest_classifier_oob[X1-y1-0.65-array-RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_multioutput_string[ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_importances[RandomForestClassifier-entropy-float64]", "sklearn/ensemble/tests/test_forest.py::test_max_samples_exceptions[nan-ValueError-`max_samples` must be in range \\\\(0.0, 1.0\\\\] but got value nan-ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_importances[ExtraTreesRegressor-absolute_error-float64]", "sklearn/ensemble/tests/test_forest.py::test_warm_start_clear[ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_max_samples_boundary_regressors[RandomForestRegressor]", "sklearn/ensemble/tests/test_forest.py::test_forest_classifier_oob[X2-y2-0.65-sparse_csc-RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_forest_classifier_oob[X3-y3-0.18-sparse_csc-ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_min_samples_split[ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_1d_input[RandomTreesEmbedding]", "sklearn/ensemble/tests/test_forest.py::test_1d_input[ExtraTreesRegressor]", "sklearn/ensemble/tests/test_forest.py::test_class_weight_balanced_and_bootstrap_multi_output[ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_importances_asymptotic", "sklearn/ensemble/tests/test_forest.py::test_min_impurity_decrease", "sklearn/ensemble/tests/test_forest.py::test_forest_classifier_oob[X3-y3-0.18-array-RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_sparse_input[csc_matrix-RandomTreesEmbedding]", "sklearn/ensemble/tests/test_forest.py::test_unfitted_feature_importances[ExtraTreesRegressor]", "sklearn/ensemble/tests/test_forest.py::test_min_samples_leaf[ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_memory_layout[float64-ExtraTreesRegressor]", "sklearn/ensemble/tests/test_forest.py::test_decision_path[ExtraTreesRegressor]", "sklearn/ensemble/tests/test_forest.py::test_max_samples_exceptions[1000000000-ValueError-`max_samples` must be in range 1 to 6 but got value 1000000000-ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_regression[absolute_error-ExtraTreesRegressor]", "sklearn/ensemble/tests/test_forest.py::test_max_samples_exceptions[0.0-ValueError-`max_samples` must be in range \\\\(0.0, 1.0\\\\] but got value 0.0-ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_forest_regressor_oob[X1-y1-0.55-sparse_csr-RandomForestRegressor]", "sklearn/ensemble/tests/test_forest.py::test_parallel[ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_importances[RandomForestClassifier-gini-float32]", "sklearn/ensemble/tests/test_forest.py::test_n_features_deprecation[ExtraTreesRegressor]", "sklearn/ensemble/tests/test_forest.py::test_forest_oob_error[X0-y0-params0-Out of bag estimation only available if bootstrap=True-RandomForestRegressor]", "sklearn/ensemble/tests/test_forest.py::test_max_leaf_nodes_max_depth[RandomTreesEmbedding]", "sklearn/ensemble/tests/test_forest.py::test_min_samples_leaf[RandomTreesEmbedding]", "sklearn/ensemble/tests/test_forest.py::test_classes_shape[ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_forest_oob_warning[RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_memory_layout[float32-ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_warm_start_equal_n_estimators[RandomForestRegressor]", "sklearn/ensemble/tests/test_forest.py::test_forest_oob_error[X0-y0-params0-Out of bag estimation only available if bootstrap=True-RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_warm_start_smaller_n_estimators[ExtraTreesRegressor]", "sklearn/ensemble/tests/test_forest.py::test_balance_property_random_forest[squared_error]", "sklearn/ensemble/tests/test_forest.py::test_forest_oob_error[X1-y1-params1-The type of target cannot be used to compute OOB estimates-ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_warm_start_clear[ExtraTreesRegressor]", "sklearn/ensemble/tests/test_forest.py::test_forest_feature_importances_sum", "sklearn/ensemble/tests/test_forest.py::test_probability[ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_forest_classifier_oob[X2-y2-0.65-array-ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_warm_start[RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_forest_oob_warning[RandomForestRegressor]", "sklearn/ensemble/tests/test_forest.py::test_forest_classifier_oob[X1-y1-0.65-sparse_csc-RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_parallel[RandomForestRegressor]", "sklearn/ensemble/tests/test_forest.py::test_forest_classifier_oob[X0-y0-0.9-sparse_csc-ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_forest_regressor_oob[X0-y0-0.7-sparse_csr-ExtraTreesRegressor]", "sklearn/ensemble/tests/test_forest.py::test_warm_start_clear[RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_max_samples_exceptions[inf-ValueError-`max_samples` must be in range \\\\(0.0, 1.0\\\\] but got value inf-RandomForestRegressor]", "sklearn/ensemble/tests/test_forest.py::test_min_weight_fraction_leaf[ExtraTreesRegressor]", "sklearn/ensemble/tests/test_forest.py::test_multioutput[RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_multioutput[ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_max_samples_exceptions[inf-ValueError-`max_samples` must be in range \\\\(0.0, 1.0\\\\] but got value inf-ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_max_samples_boundary_regressors[ExtraTreesRegressor]", "sklearn/ensemble/tests/test_forest.py::test_sparse_input[csr_matrix-RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_max_samples_exceptions[0.0-ValueError-`max_samples` must be in range \\\\(0.0, 1.0\\\\] but got value 0.0-RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_max_samples_exceptions[str max_samples?!-TypeError-`max_samples` should be int or float, but got type '\\\\<class 'str'\\\\>'-ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_forest_regressor_oob[X1-y1-0.55-sparse_csc-ExtraTreesRegressor]", "sklearn/ensemble/tests/test_forest.py::test_sparse_input[csc_matrix-ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_memory_layout[float32-RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_n_features_deprecation[RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_multioutput[RandomForestRegressor]", "sklearn/ensemble/tests/test_forest.py::test_random_hasher_sparse_data", "sklearn/ensemble/tests/test_forest.py::test_decision_path[RandomForestRegressor]", "sklearn/ensemble/tests/test_forest.py::test_max_samples_exceptions[2.0-ValueError-`max_samples` must be in range \\\\(0.0, 1.0\\\\] but got value 2.0-ExtraTreesRegressor]", "sklearn/ensemble/tests/test_forest.py::test_min_weight_fraction_leaf[ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_sparse_input[csr_matrix-ExtraTreesRegressor]", "sklearn/ensemble/tests/test_forest.py::test_sparse_input[csc_matrix-RandomForestRegressor]", "sklearn/ensemble/tests/test_forest.py::test_regression[absolute_error-RandomForestRegressor]", "sklearn/ensemble/tests/test_forest.py::test_importances[ExtraTreesRegressor-squared_error-float64]", "sklearn/ensemble/tests/test_forest.py::test_warm_start[ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_warm_start_oob[RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_max_samples_exceptions[2.0-ValueError-`max_samples` must be in range \\\\(0.0, 1.0\\\\] but got value 2.0-RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_sparse_input[csr_matrix-ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_warm_start_clear[RandomForestRegressor]", "sklearn/ensemble/tests/test_forest.py::test_unfitted_feature_importances[RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_unfitted_feature_importances[RandomTreesEmbedding]", "sklearn/ensemble/tests/test_forest.py::test_forest_regressor_oob[X0-y0-0.7-sparse_csr-RandomForestRegressor]", "sklearn/ensemble/tests/test_forest.py::test_class_weight_errors[ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_forest_regressor_oob[X1-y1-0.55-array-ExtraTreesRegressor]", "sklearn/ensemble/tests/test_forest.py::test_classes_shape[RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_min_impurity_split", "sklearn/ensemble/tests/test_forest.py::test_regression[friedman_mse-RandomForestRegressor]", "sklearn/ensemble/tests/test_forest.py::test_max_samples_exceptions[nan-ValueError-`max_samples` must be in range \\\\(0.0, 1.0\\\\] but got value nan-ExtraTreesRegressor]", "sklearn/ensemble/tests/test_forest.py::test_importances[ExtraTreesRegressor-squared_error-float32]", "sklearn/ensemble/tests/test_forest.py::test_n_features_deprecation[RandomTreesEmbedding]", "sklearn/ensemble/tests/test_forest.py::test_mse_criterion_object_segfault_smoke_test[ExtraTreesRegressor]", "sklearn/ensemble/tests/test_forest.py::test_mse_criterion_object_segfault_smoke_test[RandomForestRegressor]", "sklearn/ensemble/tests/test_forest.py::test_random_trees_embedding_raise_error_oob[True]", "sklearn/ensemble/tests/test_forest.py::test_max_samples_exceptions[1000000000-ValueError-`max_samples` must be in range 1 to 6 but got value 1000000000-RandomForestRegressor]", "sklearn/ensemble/tests/test_forest.py::test_regressor_attributes[ExtraTreesRegressor]", "sklearn/ensemble/tests/test_forest.py::test_criterion_deprecated[mae-absolute_error]", "sklearn/ensemble/tests/test_forest.py::test_classification_toy[ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_importances[RandomForestRegressor-friedman_mse-float32]", "sklearn/ensemble/tests/test_forest.py::test_forest_oob_warning[ExtraTreesRegressor]", "sklearn/ensemble/tests/test_forest.py::test_min_samples_split[RandomTreesEmbedding]", "sklearn/ensemble/tests/test_forest.py::test_forest_classifier_oob[X2-y2-0.65-sparse_csr-ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_unfitted_feature_importances[RandomForestRegressor]", "sklearn/ensemble/tests/test_forest.py::test_warm_start_smaller_n_estimators[RandomForestRegressor]", "sklearn/ensemble/tests/test_forest.py::test_gridsearch[RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_max_samples_exceptions[2.0-ValueError-`max_samples` must be in range \\\\(0.0, 1.0\\\\] but got value 2.0-RandomForestRegressor]", "sklearn/ensemble/tests/test_forest.py::test_warm_start_smaller_n_estimators[ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_class_weight_errors[RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_sparse_input[coo_matrix-ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_forest_classifier_oob[X1-y1-0.65-sparse_csr-ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_warm_start_oob[RandomForestRegressor]", "sklearn/ensemble/tests/test_forest.py::test_importances[ExtraTreesClassifier-entropy-float32]", "sklearn/ensemble/tests/test_forest.py::test_forest_classifier_oob[X1-y1-0.65-sparse_csr-RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_warm_start_equal_n_estimators[ExtraTreesRegressor]", "sklearn/ensemble/tests/test_forest.py::test_importances[RandomForestRegressor-absolute_error-float32]", "sklearn/ensemble/tests/test_forest.py::test_decision_path[ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_probability[RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_min_weight_fraction_leaf[RandomTreesEmbedding]", "sklearn/ensemble/tests/test_forest.py::test_max_samples_exceptions[0.0-ValueError-`max_samples` must be in range \\\\(0.0, 1.0\\\\] but got value 0.0-RandomForestRegressor]", "sklearn/ensemble/tests/test_forest.py::test_criterion_deprecated[mse-squared_error]", "sklearn/ensemble/tests/test_forest.py::test_forest_degenerate_feature_importances", "sklearn/ensemble/tests/test_forest.py::test_n_features_deprecation[ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_1d_input[ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_forest_regressor_oob[X1-y1-0.55-array-RandomForestRegressor]", "sklearn/ensemble/tests/test_forest.py::test_max_samples_boundary_classifiers[ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_pickle[ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_forest_classifier_oob[X0-y0-0.9-array-ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_forest_classifier_oob[X0-y0-0.9-sparse_csr-ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_iris[entropy-RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_parallel_train", "sklearn/ensemble/tests/test_forest.py::test_importances[RandomForestRegressor-absolute_error-float64]", "sklearn/ensemble/tests/test_forest.py::test_forest_classifier_oob[X1-y1-0.65-sparse_csc-ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_min_weight_fraction_leaf[RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_1d_input[RandomForestRegressor]", "sklearn/ensemble/tests/test_forest.py::test_unfitted_feature_importances[ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_forest_regressor_oob[X0-y0-0.7-array-RandomForestRegressor]", "sklearn/ensemble/tests/test_forest.py::test_forest_oob_error[X1-y1-params1-The type of target cannot be used to compute OOB estimates-RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_forest_oob_error[X1-y1-params1-The type of target cannot be used to compute OOB estimates-RandomForestRegressor]", "sklearn/ensemble/tests/test_forest.py::test_pickle[RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_sparse_input[coo_matrix-RandomForestRegressor]", "sklearn/ensemble/tests/test_forest.py::test_little_tree_with_small_max_samples[RandomForestRegressor]", "sklearn/ensemble/tests/test_forest.py::test_forest_classifier_oob[X3-y3-0.18-sparse_csr-RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_random_trees_dense_type", "sklearn/ensemble/tests/test_forest.py::test_max_samples_exceptions[2.0-ValueError-`max_samples` must be in range \\\\(0.0, 1.0\\\\] but got value 2.0-ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_importances[RandomForestRegressor-squared_error-float64]", "sklearn/ensemble/tests/test_forest.py::test_sparse_input[csc_matrix-ExtraTreesRegressor]", "sklearn/ensemble/tests/test_forest.py::test_forest_oob_warning[ExtraTreesClassifier]", "sklearn/ensemble/tests/test_forest.py::test_memory_layout[float64-RandomForestRegressor]", "sklearn/ensemble/tests/test_forest.py::test_min_samples_split[ExtraTreesRegressor]", "sklearn/ensemble/tests/test_forest.py::test_max_leaf_nodes_max_depth[RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_warm_start_equal_n_estimators[RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_max_samples_exceptions[str max_samples?!-TypeError-`max_samples` should be int or float, but got type '\\\\<class 'str'\\\\>'-RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_forest_classifier_oob[X0-y0-0.9-sparse_csc-RandomForestClassifier]", "sklearn/ensemble/tests/test_forest.py::test_forest_regressor_oob[X0-y0-0.7-array-ExtraTreesRegressor]", "sklearn/ensemble/tests/test_forest.py::test_min_samples_split[RandomForestRegressor]", "sklearn/ensemble/tests/test_forest.py::test_max_samples_exceptions[max_samples6-TypeError-`max_samples` should be int or float, but got type '\\\\<class 'numpy.ndarray'\\\\>'-ExtraTreesRegressor]" ]
[ "sklearn/ensemble/tests/test_forest.py::test_poisson_y_positive_check" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex ece6ff15ac51b..b66c87815bae7 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -270,6 +270,10 @@ Changelog\n :class:`ensemble.StackingClassifier` and :class:`ensemble.StackingRegressor`.\n :pr:`<PRID>` by `<NAME>`_.\n \n+- |Enhancement| Documented and tested support of the Poisson criterion for\n+ :class:`ensemble.RandomForestRegressor`. :pr:`<PRID>` by\n+ :user:`<NAME>`.\n+\n - |Fix| Fixed the range of the argument max_samples to be (0.0, 1.0]\n in :class:`ensemble.RandomForestClassifier`,\n :class:`ensemble.RandomForestRegressor`, where `max_samples=1.0` is\n" } ]
diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index ece6ff15ac51b..b66c87815bae7 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -270,6 +270,10 @@ Changelog :class:`ensemble.StackingClassifier` and :class:`ensemble.StackingRegressor`. :pr:`<PRID>` by `<NAME>`_. +- |Enhancement| Documented and tested support of the Poisson criterion for + :class:`ensemble.RandomForestRegressor`. :pr:`<PRID>` by + :user:`<NAME>`. + - |Fix| Fixed the range of the argument max_samples to be (0.0, 1.0] in :class:`ensemble.RandomForestClassifier`, :class:`ensemble.RandomForestRegressor`, where `max_samples=1.0` is
scikit-learn/scikit-learn
scikit-learn__scikit-learn-19428
https://github.com/scikit-learn/scikit-learn/pull/19428
diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index 1338606e3a096..688c42fd1748d 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -411,6 +411,11 @@ Changelog :func:`~sklearn.inspection.permutation_importance`. :pr:`19411` by :user:`Simona Maggio <simonamaggio>`. +- |Enhancement| Add kwargs to format ICE and PD lines separately in partial + dependence plots :func:`~sklearn.inspection.plot_partial_dependence` and + :meth:`~sklearn.inspection.PartialDependenceDisplay.plot`. + :pr:`19428` by :user:`Mehdi Hamoumi <mhham>`. + :mod:`sklearn.linear_model` ........................... diff --git a/examples/inspection/plot_partial_dependence.py b/examples/inspection/plot_partial_dependence.py index ac8d20ec9f155..ceccd8c3001c1 100644 --- a/examples/inspection/plot_partial_dependence.py +++ b/examples/inspection/plot_partial_dependence.py @@ -53,9 +53,7 @@ y -= y.mean() -X_train, X_test, y_train, y_test = train_test_split( - X, y, test_size=0.1, random_state=0 -) +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=0) # %% # 1-way partial dependence with different models @@ -80,10 +78,12 @@ print("Training MLPRegressor...") tic = time() -est = make_pipeline(QuantileTransformer(), - MLPRegressor(hidden_layer_sizes=(50, 50), - learning_rate_init=0.01, - early_stopping=True)) +est = make_pipeline( + QuantileTransformer(), + MLPRegressor( + hidden_layer_sizes=(50, 50), learning_rate_init=0.01, early_stopping=True + ), +) est.fit(X_train, y_train) print(f"done in {time() - tic:.3f}s") print(f"Test R2 score: {est.score(X_test, y_test):.2f}") @@ -113,17 +113,25 @@ from sklearn.inspection import partial_dependence from sklearn.inspection import plot_partial_dependence -print('Computing partial dependence plots...') +print("Computing partial dependence plots...") tic = time() -features = ['MedInc', 'AveOccup', 'HouseAge', 'AveRooms'] +features = ["MedInc", "AveOccup", "HouseAge", "AveRooms"] display = plot_partial_dependence( - est, X_train, features, kind="both", subsample=50, - n_jobs=3, grid_resolution=20, random_state=0 + est, + X_train, + features, + kind="both", + subsample=50, + n_jobs=3, + grid_resolution=20, + random_state=0, + ice_lines_kw={"color": "tab:blue", "alpha": 0.2, "linewidth": 0.5}, + pd_line_kw={"color": "tab:orange", "linestyle": "--"}, ) print(f"done in {time() - tic:.3f}s") display.figure_.suptitle( - 'Partial dependence of house value on non-location features\n' - 'for the California housing dataset, with MLPRegressor' + "Partial dependence of house value on non-location features\n" + "for the California housing dataset, with MLPRegressor" ) display.figure_.subplots_adjust(hspace=0.3) @@ -156,16 +164,24 @@ # We will plot the partial dependence, both individual (ICE) and averaged one # (PDP). We limit to only 50 ICE curves to not overcrowd the plot. -print('Computing partial dependence plots...') +print("Computing partial dependence plots...") tic = time() display = plot_partial_dependence( - est, X_train, features, kind="both", subsample=50, - n_jobs=3, grid_resolution=20, random_state=0 + est, + X_train, + features, + kind="both", + subsample=50, + n_jobs=3, + grid_resolution=20, + random_state=0, + ice_lines_kw={"color": "tab:blue", "alpha": 0.2, "linewidth": 0.5}, + pd_line_kw={"color": "tab:orange", "linestyle": "--"}, ) print(f"done in {time() - tic:.3f}s") display.figure_.suptitle( - 'Partial dependence of house value on non-location features\n' - 'for the California housing dataset, with Gradient Boosting' + "Partial dependence of house value on non-location features\n" + "for the California housing dataset, with Gradient Boosting" ) display.figure_.subplots_adjust(wspace=0.4, hspace=0.3) @@ -209,18 +225,23 @@ # the tree-based algorithm, when only PDPs are requested, they can be computed # on an efficient way using the `'recursion'` method. -features = ['AveOccup', 'HouseAge', ('AveOccup', 'HouseAge')] -print('Computing partial dependence plots...') +features = ["AveOccup", "HouseAge", ("AveOccup", "HouseAge")] +print("Computing partial dependence plots...") tic = time() _, ax = plt.subplots(ncols=3, figsize=(9, 4)) display = plot_partial_dependence( - est, X_train, features, kind='average', n_jobs=3, grid_resolution=20, + est, + X_train, + features, + kind="average", + n_jobs=3, + grid_resolution=20, ax=ax, ) print(f"done in {time() - tic:.3f}s") display.figure_.suptitle( - 'Partial dependence of house value on non-location features\n' - 'for the California housing dataset, with Gradient Boosting' + "Partial dependence of house value on non-location features\n" + "for the California housing dataset, with Gradient Boosting" ) display.figure_.subplots_adjust(wspace=0.4, hspace=0.3) @@ -240,24 +261,27 @@ import numpy as np from mpl_toolkits.mplot3d import Axes3D + fig = plt.figure() -features = ('AveOccup', 'HouseAge') +features = ("AveOccup", "HouseAge") pdp = partial_dependence( - est, X_train, features=features, kind='average', grid_resolution=20 + est, X_train, features=features, kind="average", grid_resolution=20 ) XX, YY = np.meshgrid(pdp["values"][0], pdp["values"][1]) Z = pdp.average[0].T ax = Axes3D(fig) -surf = ax.plot_surface(XX, YY, Z, rstride=1, cstride=1, - cmap=plt.cm.BuPu, edgecolor='k') +fig.add_axes(ax) +surf = ax.plot_surface(XX, YY, Z, rstride=1, cstride=1, cmap=plt.cm.BuPu, edgecolor="k") ax.set_xlabel(features[0]) ax.set_ylabel(features[1]) -ax.set_zlabel('Partial dependence') +ax.set_zlabel("Partial dependence") # pretty init view ax.view_init(elev=22, azim=122) plt.colorbar(surf) -plt.suptitle('Partial dependence of house value on median\n' - 'age and average occupancy, with Gradient Boosting') +plt.suptitle( + "Partial dependence of house value on median\n" + "age and average occupancy, with Gradient Boosting" +) plt.subplots_adjust(top=0.9) plt.show() diff --git a/sklearn/inspection/_plot/partial_dependence.py b/sklearn/inspection/_plot/partial_dependence.py index b45bdbe0b2fb1..f03669e7a4207 100644 --- a/sklearn/inspection/_plot/partial_dependence.py +++ b/sklearn/inspection/_plot/partial_dependence.py @@ -32,6 +32,8 @@ def plot_partial_dependence( n_jobs=None, verbose=0, line_kw=None, + ice_lines_kw=None, + pd_line_kw=None, contour_kw=None, ax=None, kind="average", @@ -185,7 +187,24 @@ def plot_partial_dependence( line_kw : dict, default=None Dict with keywords passed to the ``matplotlib.pyplot.plot`` call. - For one-way partial dependence plots. + For one-way partial dependence plots. It can be used to define common + properties for both `ice_lines_kw` and `pdp_line_kw`. + + ice_lines_kw : dict, default=None + Dictionary with keywords passed to the `matplotlib.pyplot.plot` call. + For ICE lines in the one-way partial dependence plots. + The key value pairs defined in `ice_lines_kw` takes priority over + `line_kw`. + + .. versionadded:: 1.0 + + pd_line_kw : dict, default=None + Dictionary with keywords passed to the `matplotlib.pyplot.plot` call. + For partial dependence in one-way partial dependence plots. + The key value pairs defined in `pd_line_kw` takes priority over + `line_kw`. + + .. versionadded:: 1.0 contour_kw : dict, default=None Dict with keywords passed to the ``matplotlib.pyplot.contourf`` call. @@ -413,7 +432,14 @@ def convert_feature(fx): subsample=subsample, random_state=random_state, ) - return display.plot(ax=ax, n_cols=n_cols, line_kw=line_kw, contour_kw=contour_kw) + return display.plot( + ax=ax, + n_cols=n_cols, + line_kw=line_kw, + ice_lines_kw=ice_lines_kw, + pd_line_kw=pd_line_kw, + contour_kw=contour_kw, + ) class PartialDependenceDisplay: @@ -675,8 +701,8 @@ def _plot_one_way_partial_dependence( n_cols, pd_plot_idx, n_lines, - individual_line_kw, - line_kw, + ice_lines_kw, + pd_line_kw, ): """Plot 1-way partial dependence: ICE and PDP. @@ -704,9 +730,9 @@ def _plot_one_way_partial_dependence( matching 2D position in the grid layout. n_lines : int The total number of lines expected to be plot on the axis. - individual_line_kw : dict + ice_lines_kw : dict Dict with keywords passed when plotting the ICE lines. - line_kw : dict + pd_line_kw : dict Dict with keywords passed when plotting the PD plot. """ from matplotlib import transforms # noqa @@ -719,7 +745,7 @@ def _plot_one_way_partial_dependence( ax, pd_plot_idx, n_lines, - individual_line_kw, + ice_lines_kw, ) if self.kind in ("average", "both"): @@ -733,7 +759,7 @@ def _plot_one_way_partial_dependence( feature_values, ax, pd_line_idx, - line_kw, + pd_line_kw, ) trans = transforms.blended_transform_factory(ax.transData, ax.transAxes) @@ -759,7 +785,7 @@ def _plot_one_way_partial_dependence( else: ax.set_yticklabels([]) - if line_kw.get("label", None) and self.kind != "individual": + if pd_line_kw.get("label", None) and self.kind != "individual": ax.legend() def _plot_two_way_partial_dependence( @@ -842,7 +868,16 @@ def _plot_two_way_partial_dependence( ax.set_ylabel(self.feature_names[feature_idx[1]]) @_deprecate_positional_args(version="1.1") - def plot(self, *, ax=None, n_cols=3, line_kw=None, contour_kw=None): + def plot( + self, + *, + ax=None, + n_cols=3, + line_kw=None, + ice_lines_kw=None, + pd_line_kw=None, + contour_kw=None, + ): """Plot partial dependence plots. Parameters @@ -865,6 +900,22 @@ def plot(self, *, ax=None, n_cols=3, line_kw=None, contour_kw=None): Dict with keywords passed to the `matplotlib.pyplot.plot` call. For one-way partial dependence plots. + ice_lines_kw : dict, default=None + Dictionary with keywords passed to the `matplotlib.pyplot.plot` call. + For ICE lines in the one-way partial dependence plots. + The key value pairs defined in `ice_lines_kw` takes priority over + `line_kw`. + + .. versionadded:: 1.0 + + pd_line_kw : dict, default=None + Dictionary with keywords passed to the `matplotlib.pyplot.plot` call. + For partial dependence in one-way partial dependence plots. + The key value pairs defined in `pd_line_kw` takes priority over + `line_kw`. + + .. versionadded:: 1.0 + contour_kw : dict, default=None Dict with keywords passed to the `matplotlib.pyplot.contourf` call for two-way partial dependence plots. @@ -880,6 +931,10 @@ def plot(self, *, ax=None, n_cols=3, line_kw=None, contour_kw=None): if line_kw is None: line_kw = {} + if ice_lines_kw is None: + ice_lines_kw = {} + if pd_line_kw is None: + pd_line_kw = {} if contour_kw is None: contour_kw = {} @@ -893,14 +948,20 @@ def plot(self, *, ax=None, n_cols=3, line_kw=None, contour_kw=None): "color": "C0", "label": "average" if self.kind == "both" else None, } - line_kw = {**default_line_kws, **line_kw} + if self.kind in ("individual", "both"): + default_ice_lines_kws = {"alpha": 0.3, "linewidth": 0.5} + else: + default_ice_lines_kws = {} - individual_line_kw = line_kw.copy() - del individual_line_kw["label"] + ice_lines_kw = { + **default_line_kws, + **line_kw, + **default_ice_lines_kws, + **ice_lines_kw, + } + del ice_lines_kw["label"] - if self.kind == "individual" or self.kind == "both": - individual_line_kw["alpha"] = 0.3 - individual_line_kw["linewidth"] = 0.5 + pd_line_kw = {**default_line_kws, **line_kw, **pd_line_kw} n_features = len(self.features) if self.kind in ("individual", "both"): @@ -998,8 +1059,8 @@ def plot(self, *, ax=None, n_cols=3, line_kw=None, contour_kw=None): n_cols, pd_plot_idx, n_lines, - individual_line_kw, - line_kw, + ice_lines_kw, + pd_line_kw, ) else: self._plot_two_way_partial_dependence(
diff --git a/sklearn/inspection/_plot/tests/test_plot_partial_dependence.py b/sklearn/inspection/_plot/tests/test_plot_partial_dependence.py index 25c543d94c3c0..4d33313c8c884 100644 --- a/sklearn/inspection/_plot/tests/test_plot_partial_dependence.py +++ b/sklearn/inspection/_plot/tests/test_plot_partial_dependence.py @@ -687,3 +687,56 @@ def test_partial_dependence_overwrite_labels( legend_text = ax.get_legend().get_texts() assert len(legend_text) == 1 assert legend_text[0].get_text() == label + + [email protected]("ignore:A Bunch will be returned") [email protected]( + "line_kw, pd_line_kw, ice_lines_kw, expected_colors", + [ + ({"color": "r"}, {"color": "g"}, {"color": "b"}, ("g", "b")), + (None, {"color": "g"}, {"color": "b"}, ("g", "b")), + ({"color": "r"}, None, {"color": "b"}, ("r", "b")), + ({"color": "r"}, {"color": "g"}, None, ("g", "r")), + ({"color": "r"}, None, None, ("r", "r")), + ({"color": "r"}, {"linestyle": "--"}, {"linestyle": "-."}, ("r", "r")), + ], +) +def test_plot_partial_dependence_lines_kw( + pyplot, + clf_diabetes, + diabetes, + line_kw, + pd_line_kw, + ice_lines_kw, + expected_colors, +): + """Check that passing `pd_line_kw` and `ice_lines_kw` will act on the + specific lines in the plot. + """ + + disp = plot_partial_dependence( + clf_diabetes, + diabetes.data, + [0, 2], + grid_resolution=20, + feature_names=diabetes.feature_names, + n_cols=2, + kind="both", + line_kw=line_kw, + pd_line_kw=pd_line_kw, + ice_lines_kw=ice_lines_kw, + ) + + line = disp.lines_[0, 0, -1] + assert line.get_color() == expected_colors[0] + if pd_line_kw is not None and "linestyle" in pd_line_kw: + assert line.get_linestyle() == pd_line_kw["linestyle"] + else: + assert line.get_linestyle() == "-" + + line = disp.lines_[0, 0, 0] + assert line.get_color() == expected_colors[1] + if ice_lines_kw is not None and "linestyle" in ice_lines_kw: + assert line.get_linestyle() == ice_lines_kw["linestyle"] + else: + assert line.get_linestyle() == "-"
[ { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 1338606e3a096..688c42fd1748d 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -411,6 +411,11 @@ Changelog\n :func:`~sklearn.inspection.permutation_importance`.\n :pr:`19411` by :user:`Simona Maggio <simonamaggio>`.\n \n+- |Enhancement| Add kwargs to format ICE and PD lines separately in partial\n+ dependence plots :func:`~sklearn.inspection.plot_partial_dependence` and\n+ :meth:`~sklearn.inspection.PartialDependenceDisplay.plot`.\n+ :pr:`19428` by :user:`Mehdi Hamoumi <mhham>`.\n+\n :mod:`sklearn.linear_model`\n ...........................\n \n" } ]
1.00
94edc00caba1bde6b793da4d0c53fd2d63fedf96
[ "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence[20]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_error[data1-params1-target must be in \\\\[0, n_tasks\\\\]]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_str_features[dataframe-series]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_passing_numpy_axes[average-1]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_error[data2-params2-target must be in \\\\[0, n_tasks\\\\]]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_multiclass", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_str_features[list-array]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_incorrent_num_axes[2-2]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_str_features[list-series]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_error[data0-params0-target must be specified for multi-output]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_kind[individual-0.5-shape5]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_multiclass_error[params1-target must be specified for multi-class]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence[10]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_error[data3-params3-Feature foobar not in feature_names]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_error[data6-params6-Each entry in features must be either an int, ]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_error[data13-params13-When a floating-point, subsample=1.2 should be in the \\\\(0, 1\\\\) range]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_partial_dependence_overwrite_labels[average-line_kw2-None]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_kind[individual-None-shape1]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_kind[both-0.5-shape6]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_str_features[list-index]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_error[data12-params12-When an integer, subsample=-1 should be positive.]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_does_not_override_ylabel", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_with_same_axes", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_error[data4-params4-Feature foobar not in feature_names]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_str_features[array-series]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_incorrent_num_axes[3-1]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_feature_name_reuse", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_partial_dependence_overwrite_labels[average-line_kw3-xxx]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_error[data7-params7-Each entry in features must be either an int, ]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_str_features[dataframe-index]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_partial_dependence_overwrite_labels[individual-line_kw0-None]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_partial_dependence_overwrite_labels[both-line_kw5-xxx]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_multiclass_error[params0-target not in est.classes_, got 4]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_error[data10-params10-It is not possible to display individual effects for more than one]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_partial_dependence_overwrite_labels[individual-line_kw1-None]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_str_features[array-list]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_str_features[array-index]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_subsampling[average-expected_shape0]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_subsampling[both-expected_shape2]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_multioutput[0]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_kind[average-None-shape0]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_passing_numpy_axes[both-443]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_partial_dependence_overwrite_labels[both-line_kw4-average]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_kind[individual-50-shape3]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_str_features[dataframe-None]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_custom_axes", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_dataframe", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_str_features[list-list]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_str_features[dataframe-list]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_subsampling[individual-expected_shape1]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_error[data5-params5-Each entry in features must be either an int, ]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_kind[both-50-shape4]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_passing_numpy_axes[individual-442]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_error[data8-params8-All entries of features must be less than ]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_multioutput[1]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_str_features[array-array]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_error[data9-params9-feature_names should not contain duplicates]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_error[data11-params11-It is not possible to display individual effects for more than one]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_multiclass_error[params2-Each entry in features must be either an int,]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_kind[both-None-shape2]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_str_features[dataframe-array]" ]
[ "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_lines_kw[line_kw2-None-ice_lines_kw2-expected_colors2]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_lines_kw[None-pd_line_kw1-ice_lines_kw1-expected_colors1]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_lines_kw[line_kw0-pd_line_kw0-ice_lines_kw0-expected_colors0]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_lines_kw[line_kw4-None-None-expected_colors4]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_lines_kw[line_kw5-pd_line_kw5-ice_lines_kw5-expected_colors5]", "sklearn/inspection/_plot/tests/test_plot_partial_dependence.py::test_plot_partial_dependence_lines_kw[line_kw3-pd_line_kw3-None-expected_colors3]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 1338606e3a096..688c42fd1748d 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -411,6 +411,11 @@ Changelog\n :func:`~sklearn.inspection.permutation_importance`.\n :pr:`<PRID>` by :user:`<NAME>`.\n \n+- |Enhancement| Add kwargs to format ICE and PD lines separately in partial\n+ dependence plots :func:`~sklearn.inspection.plot_partial_dependence` and\n+ :meth:`~sklearn.inspection.PartialDependenceDisplay.plot`.\n+ :pr:`<PRID>` by :user:`<NAME>`.\n+\n :mod:`sklearn.linear_model`\n ...........................\n \n" } ]
diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index 1338606e3a096..688c42fd1748d 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -411,6 +411,11 @@ Changelog :func:`~sklearn.inspection.permutation_importance`. :pr:`<PRID>` by :user:`<NAME>`. +- |Enhancement| Add kwargs to format ICE and PD lines separately in partial + dependence plots :func:`~sklearn.inspection.plot_partial_dependence` and + :meth:`~sklearn.inspection.PartialDependenceDisplay.plot`. + :pr:`<PRID>` by :user:`<NAME>`. + :mod:`sklearn.linear_model` ...........................
scikit-learn/scikit-learn
scikit-learn__scikit-learn-10027
https://github.com/scikit-learn/scikit-learn/pull/10027
diff --git a/benchmarks/bench_online_ocsvm.py b/benchmarks/bench_online_ocsvm.py new file mode 100644 index 0000000000000..33262e8fcb690 --- /dev/null +++ b/benchmarks/bench_online_ocsvm.py @@ -0,0 +1,279 @@ +""" +===================================== +SGDOneClassSVM benchmark +===================================== +This benchmark compares the :class:`SGDOneClassSVM` with :class:`OneClassSVM`. +The former is an online One-Class SVM implemented with a Stochastic Gradient +Descent (SGD). The latter is based on the LibSVM implementation. The +complexity of :class:`SGDOneClassSVM` is linear in the number of samples +whereas the one of :class:`OneClassSVM` is at best quadratic in the number of +samples. We here compare the performance in terms of AUC and training time on +classical anomaly detection datasets. + +The :class:`OneClassSVM` is applied with a Gaussian kernel and we therefore +use a kernel approximation prior to the application of :class:`SGDOneClassSVM`. +""" + +from time import time +import numpy as np + +from scipy.interpolate import interp1d + +from sklearn.metrics import roc_curve, auc +from sklearn.datasets import fetch_kddcup99, fetch_covtype +from sklearn.preprocessing import LabelBinarizer, StandardScaler +from sklearn.pipeline import make_pipeline +from sklearn.utils import shuffle +from sklearn.kernel_approximation import Nystroem +from sklearn.svm import OneClassSVM +from sklearn.linear_model import SGDOneClassSVM + +import matplotlib.pyplot as plt +import matplotlib + +font = {'weight': 'normal', + 'size': 15} + +matplotlib.rc('font', **font) + +print(__doc__) + + +def print_outlier_ratio(y): + """ + Helper function to show the distinct value count of element in the target. + Useful indicator for the datasets used in bench_isolation_forest.py. + """ + uniq, cnt = np.unique(y, return_counts=True) + print("----- Target count values: ") + for u, c in zip(uniq, cnt): + print("------ %s -> %d occurrences" % (str(u), c)) + print("----- Outlier ratio: %.5f" % (np.min(cnt) / len(y))) + + +# for roc curve computation +n_axis = 1000 +x_axis = np.linspace(0, 1, n_axis) + +datasets = ['http', 'smtp', 'SA', 'SF', 'forestcover'] + +novelty_detection = False # if False, training set polluted by outliers + +random_states = [42] +nu = 0.05 + +results_libsvm = np.empty((len(datasets), n_axis + 5)) +results_online = np.empty((len(datasets), n_axis + 5)) + +for dat, dataset_name in enumerate(datasets): + + print(dataset_name) + + # Loading datasets + if dataset_name in ['http', 'smtp', 'SA', 'SF']: + dataset = fetch_kddcup99(subset=dataset_name, shuffle=False, + percent10=False, random_state=88) + X = dataset.data + y = dataset.target + + if dataset_name == 'forestcover': + dataset = fetch_covtype(shuffle=False) + X = dataset.data + y = dataset.target + # normal data are those with attribute 2 + # abnormal those with attribute 4 + s = (y == 2) + (y == 4) + X = X[s, :] + y = y[s] + y = (y != 2).astype(int) + + # Vectorizing data + if dataset_name == 'SF': + # Casting type of X (object) as string is needed for string categorical + # features to apply LabelBinarizer + lb = LabelBinarizer() + x1 = lb.fit_transform(X[:, 1].astype(str)) + X = np.c_[X[:, :1], x1, X[:, 2:]] + y = (y != b'normal.').astype(int) + + if dataset_name == 'SA': + lb = LabelBinarizer() + # Casting type of X (object) as string is needed for string categorical + # features to apply LabelBinarizer + x1 = lb.fit_transform(X[:, 1].astype(str)) + x2 = lb.fit_transform(X[:, 2].astype(str)) + x3 = lb.fit_transform(X[:, 3].astype(str)) + X = np.c_[X[:, :1], x1, x2, x3, X[:, 4:]] + y = (y != b'normal.').astype(int) + + if dataset_name in ['http', 'smtp']: + y = (y != b'normal.').astype(int) + + print_outlier_ratio(y) + + n_samples, n_features = np.shape(X) + if dataset_name == 'SA': # LibSVM too long with n_samples // 2 + n_samples_train = n_samples // 20 + else: + n_samples_train = n_samples // 2 + + n_samples_test = n_samples - n_samples_train + print('n_train: ', n_samples_train) + print('n_features: ', n_features) + + tpr_libsvm = np.zeros(n_axis) + tpr_online = np.zeros(n_axis) + fit_time_libsvm = 0 + fit_time_online = 0 + predict_time_libsvm = 0 + predict_time_online = 0 + + X = X.astype(float) + + gamma = 1 / n_features # OCSVM default parameter + + for random_state in random_states: + + print('random state: %s' % random_state) + + X, y = shuffle(X, y, random_state=random_state) + X_train = X[:n_samples_train] + X_test = X[n_samples_train:] + y_train = y[:n_samples_train] + y_test = y[n_samples_train:] + + if novelty_detection: + X_train = X_train[y_train == 0] + y_train = y_train[y_train == 0] + + std = StandardScaler() + + print('----------- LibSVM OCSVM ------------') + ocsvm = OneClassSVM(kernel='rbf', gamma=gamma, nu=nu) + pipe_libsvm = make_pipeline(std, ocsvm) + + tstart = time() + pipe_libsvm.fit(X_train) + fit_time_libsvm += time() - tstart + + tstart = time() + # scoring such that the lower, the more normal + scoring = -pipe_libsvm.decision_function(X_test) + predict_time_libsvm += time() - tstart + fpr_libsvm_, tpr_libsvm_, _ = roc_curve(y_test, scoring) + + f_libsvm = interp1d(fpr_libsvm_, tpr_libsvm_) + tpr_libsvm += f_libsvm(x_axis) + + print('----------- Online OCSVM ------------') + nystroem = Nystroem(gamma=gamma, random_state=random_state) + online_ocsvm = SGDOneClassSVM(nu=nu, random_state=random_state) + pipe_online = make_pipeline(std, nystroem, online_ocsvm) + + tstart = time() + pipe_online.fit(X_train) + fit_time_online += time() - tstart + + tstart = time() + # scoring such that the lower, the more normal + scoring = -pipe_online.decision_function(X_test) + predict_time_online += time() - tstart + fpr_online_, tpr_online_, _ = roc_curve(y_test, scoring) + + f_online = interp1d(fpr_online_, tpr_online_) + tpr_online += f_online(x_axis) + + tpr_libsvm /= len(random_states) + tpr_libsvm[0] = 0. + fit_time_libsvm /= len(random_states) + predict_time_libsvm /= len(random_states) + auc_libsvm = auc(x_axis, tpr_libsvm) + + results_libsvm[dat] = ([fit_time_libsvm, predict_time_libsvm, + auc_libsvm, n_samples_train, + n_features] + list(tpr_libsvm)) + + tpr_online /= len(random_states) + tpr_online[0] = 0. + fit_time_online /= len(random_states) + predict_time_online /= len(random_states) + auc_online = auc(x_axis, tpr_online) + + results_online[dat] = ([fit_time_online, predict_time_online, + auc_online, n_samples_train, + n_features] + list(tpr_libsvm)) + + +# -------- Plotting bar charts ------------- +fit_time_libsvm_all = results_libsvm[:, 0] +predict_time_libsvm_all = results_libsvm[:, 1] +auc_libsvm_all = results_libsvm[:, 2] +n_train_all = results_libsvm[:, 3] +n_features_all = results_libsvm[:, 4] + +fit_time_online_all = results_online[:, 0] +predict_time_online_all = results_online[:, 1] +auc_online_all = results_online[:, 2] + + +width = 0.7 +ind = 2 * np.arange(len(datasets)) +x_tickslabels = [(name + '\n' + r'$n={:,d}$' + '\n' + r'$d={:d}$') + .format(int(n), int(d)) + for name, n, d in zip(datasets, n_train_all, n_features_all)] + + +def autolabel_auc(rects, ax): + """Attach a text label above each bar displaying its height.""" + for rect in rects: + height = rect.get_height() + ax.text(rect.get_x() + rect.get_width() / 2., 1.05 * height, + '%.3f' % height, ha='center', va='bottom') + + +def autolabel_time(rects, ax): + """Attach a text label above each bar displaying its height.""" + for rect in rects: + height = rect.get_height() + ax.text(rect.get_x() + rect.get_width() / 2., 1.05 * height, + '%.1f' % height, ha='center', va='bottom') + + +fig, ax = plt.subplots(figsize=(15, 8)) +ax.set_ylabel('AUC') +ax.set_ylim((0, 1.3)) +rect_libsvm = ax.bar(ind, auc_libsvm_all, width=width, color='r') +rect_online = ax.bar(ind + width, auc_online_all, width=width, color='y') +ax.legend((rect_libsvm[0], rect_online[0]), ('LibSVM', 'Online SVM')) +ax.set_xticks(ind + width / 2) +ax.set_xticklabels(x_tickslabels) +autolabel_auc(rect_libsvm, ax) +autolabel_auc(rect_online, ax) +plt.show() + + +fig, ax = plt.subplots(figsize=(15, 8)) +ax.set_ylabel('Training time (sec) - Log scale') +ax.set_yscale('log') +rect_libsvm = ax.bar(ind, fit_time_libsvm_all, color='r', width=width) +rect_online = ax.bar(ind + width, fit_time_online_all, color='y', width=width) +ax.legend((rect_libsvm[0], rect_online[0]), ('LibSVM', 'Online SVM')) +ax.set_xticks(ind + width / 2) +ax.set_xticklabels(x_tickslabels) +autolabel_time(rect_libsvm, ax) +autolabel_time(rect_online, ax) +plt.show() + + +fig, ax = plt.subplots(figsize=(15, 8)) +ax.set_ylabel('Testing time (sec) - Log scale') +ax.set_yscale('log') +rect_libsvm = ax.bar(ind, predict_time_libsvm_all, color='r', width=width) +rect_online = ax.bar(ind + width, predict_time_online_all, + color='y', width=width) +ax.legend((rect_libsvm[0], rect_online[0]), ('LibSVM', 'Online SVM')) +ax.set_xticks(ind + width / 2) +ax.set_xticklabels(x_tickslabels) +autolabel_time(rect_libsvm, ax) +autolabel_time(rect_online, ax) +plt.show() diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst index ceebfc337352a..45195dcedec64 100644 --- a/doc/modules/classes.rst +++ b/doc/modules/classes.rst @@ -762,6 +762,7 @@ Linear classifiers linear_model.RidgeClassifier linear_model.RidgeClassifierCV linear_model.SGDClassifier + linear_model.SGDOneClassSVM Classical linear regressors --------------------------- diff --git a/doc/modules/outlier_detection.rst b/doc/modules/outlier_detection.rst index 5d2008f3c3f58..14495bc558dab 100644 --- a/doc/modules/outlier_detection.rst +++ b/doc/modules/outlier_detection.rst @@ -110,9 +110,14 @@ does not perform very well for outlier detection. That being said, outlier detection in high-dimension, or without any assumptions on the distribution of the inlying data is very challenging. :class:`svm.OneClassSVM` may still be used with outlier detection but requires fine-tuning of its hyperparameter -`nu` to handle outliers and prevent overfitting. Finally, -:class:`covariance.EllipticEnvelope` assumes the data is Gaussian and learns -an ellipse. For more details on the different estimators refer to the example +`nu` to handle outliers and prevent overfitting. +:class:`linear_model.SGDOneClassSVM` provides an implementation of a +linear One-Class SVM with a linear complexity in the number of samples. This +implementation is here used with a kernel approximation technique to obtain +results similar to :class:`svm.OneClassSVM` which uses a Gaussian kernel +by default. Finally, :class:`covariance.EllipticEnvelope` assumes the data is +Gaussian and learns an ellipse. For more details on the different estimators +refer to the example :ref:`sphx_glr_auto_examples_miscellaneous_plot_anomaly_comparison.py` and the sections hereunder. @@ -173,6 +178,23 @@ but regular, observation outside the frontier. :scale: 75% +Scaling up the One-Class SVM +---------------------------- + +An online linear version of the One-Class SVM is implemented in +:class:`linear_model.SGDOneClassSVM`. This implementation scales linearly with +the number of samples and can be used with a kernel approximation to +approximate the solution of a kernelized :class:`svm.OneClassSVM` whose +complexity is at best quadratic in the number of samples. See section +:ref:`sgd_online_one_class_svm` for more details. + +.. topic:: Examples: + + * See :ref:`sphx_glr_auto_examples_linear_model_plot_sgdocsvm_vs_ocsvm.py` + for an illustration of the approximation of a kernelized One-Class SVM + with the `linear_model.SGDOneClassSVM` combined with kernel approximation. + + Outlier Detection ================= @@ -278,8 +300,8 @@ allows you to add more trees to an already fitted model:: for a comparison of :class:`ensemble.IsolationForest` with :class:`neighbors.LocalOutlierFactor`, :class:`svm.OneClassSVM` (tuned to perform like an outlier detection - method) and a covariance-based outlier detection with - :class:`covariance.EllipticEnvelope`. + method), :class:`linear_model.SGDOneClassSVM`, and a covariance-based + outlier detection with :class:`covariance.EllipticEnvelope`. .. topic:: References: diff --git a/doc/modules/sgd.rst b/doc/modules/sgd.rst index 1376947540e78..0a1d8407e64ae 100644 --- a/doc/modules/sgd.rst +++ b/doc/modules/sgd.rst @@ -232,6 +232,58 @@ For regression with a squared loss and a l2 penalty, another variant of SGD with an averaging strategy is available with Stochastic Average Gradient (SAG) algorithm, available as a solver in :class:`Ridge`. +.. _sgd_online_one_class_svm: + +Online One-Class SVM +==================== + +The class :class:`sklearn.linear_model.SGDOneClassSVM` implements an online +linear version of the One-Class SVM using a stochastic gradient descent. +Combined with kernel approximation techniques, +:class:`sklearn.linear_model.SGDOneClassSVM` can be used to approximate the +solution of a kernelized One-Class SVM, implemented in +:class:`sklearn.svm.OneClassSVM`, with a linear complexity in the number of +samples. Note that the complexity of a kernelized One-Class SVM is at best +quadratic in the number of samples. +:class:`sklearn.linear_model.SGDOneClassSVM` is thus well suited for datasets +with a large number of training samples (> 10,000) for which the SGD +variant can be several orders of magnitude faster. + +Its implementation is based on the implementation of the stochastic +gradient descent. Indeed, the original optimization problem of the One-Class +SVM is given by + +.. math:: + + \begin{aligned} + \min_{w, \rho, \xi} & \quad \frac{1}{2}\Vert w \Vert^2 - \rho + \frac{1}{\nu n} \sum_{i=1}^n \xi_i \\ + \text{s.t.} & \quad \langle w, x_i \rangle \geq \rho - \xi_i \quad 1 \leq i \leq n \\ + & \quad \xi_i \geq 0 \quad 1 \leq i \leq n + \end{aligned} + +where :math:`\nu \in (0, 1]` is the user-specified parameter controlling the +proportion of outliers and the proportion of support vectors. Getting rid of +the slack variables :math:`\xi_i` this problem is equivalent to + +.. math:: + + \min_{w, \rho} \frac{1}{2}\Vert w \Vert^2 - \rho + \frac{1}{\nu n} \sum_{i=1}^n \max(0, \rho - \langle w, x_i \rangle) \, . + +Multiplying by the constant :math:`\nu` and introducing the intercept +:math:`b = 1 - \rho` we obtain the following equivalent optimization problem + +.. math:: + + \min_{w, b} \frac{\nu}{2}\Vert w \Vert^2 + b\nu + \frac{1}{n} \sum_{i=1}^n \max(0, 1 - (\langle w, x_i \rangle + b)) \, . + +This is similar to the optimization problems studied in section +:ref:`sgd_mathematical_formulation` with :math:`y_i = 1, 1 \leq i \leq n` and +:math:`\alpha = \nu/2`, :math:`L` being the hinge loss function and :math:`R` +being the L2 norm. We just need to add the term :math:`b\nu` in the +optimization loop. + +As :class:`SGDClassifier` and :class:`SGDRegressor`, :class:`SGDOneClassSVM` +supports averaged SGD. Averaging can be enabled by setting ``average=True``. Stochastic Gradient Descent for sparse data =========================================== diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index 521e358ac2f02..c252f5df1074e 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -147,6 +147,13 @@ Changelog :mod:`sklearn.linear_model` ........................... +- |Feature| The new :class:`linear_model.SGDOneClassSVM` provides an SGD + implementation of the linear One-Class SVM. Combined with kernel + approximation techniques, this implementation approximates the solution of + a kernelized One Class SVM while benefitting from a linear + complexity in the number of samples. + :pr:`10027` by :user:`Albert Thomas <albertcthomas>`. + - |Efficiency| The implementation of :class:`linear_model.LogisticRegression` has been optimised for dense matrices when using `solver='newton-cg'` and `multi_class!='multinomial'`. diff --git a/examples/linear_model/plot_sgdocsvm_vs_ocsvm.py b/examples/linear_model/plot_sgdocsvm_vs_ocsvm.py new file mode 100644 index 0000000000000..e70694cdb1c1b --- /dev/null +++ b/examples/linear_model/plot_sgdocsvm_vs_ocsvm.py @@ -0,0 +1,135 @@ +""" +==================================================================== +One-Class SVM versus One-Class SVM using Stochastic Gradient Descent +==================================================================== + +This example shows how to approximate the solution of +:class:`sklearn.svm.OneClassSVM` in the case of an RBF kernel with +:class:`sklearn.linear_model.SGDOneClassSVM`, a Stochastic Gradient Descent +(SGD) version of the One-Class SVM. A kernel approximation is first used in +order to apply :class:`sklearn.linear_model.SGDOneClassSVM` which implements a +linear One-Class SVM using SGD. + +Note that :class:`sklearn.linear_model.SGDOneClassSVM` scales linearly with +the number of samples whereas the complexity of a kernelized +:class:`sklearn.svm.OneClassSVM` is at best quadratic with respect to the +number of samples. It is not the purpose of this example to illustrate the +benefits of such an approximation in terms of computation time but rather to +show that we obtain similar results on a toy dataset. +""" +print(__doc__) # noqa + +import numpy as np +import matplotlib.pyplot as plt +import matplotlib +from sklearn.svm import OneClassSVM +from sklearn.linear_model import SGDOneClassSVM +from sklearn.kernel_approximation import Nystroem +from sklearn.pipeline import make_pipeline + +font = {'weight': 'normal', + 'size': 15} + +matplotlib.rc('font', **font) + +random_state = 42 +rng = np.random.RandomState(random_state) + +# Generate train data +X = 0.3 * rng.randn(500, 2) +X_train = np.r_[X + 2, X - 2] +# Generate some regular novel observations +X = 0.3 * rng.randn(20, 2) +X_test = np.r_[X + 2, X - 2] +# Generate some abnormal novel observations +X_outliers = rng.uniform(low=-4, high=4, size=(20, 2)) + +xx, yy = np.meshgrid(np.linspace(-4.5, 4.5, 50), np.linspace(-4.5, 4.5, 50)) + +# OCSVM hyperparameters +nu = 0.05 +gamma = 2. + +# Fit the One-Class SVM +clf = OneClassSVM(gamma=gamma, kernel='rbf', nu=nu) +clf.fit(X_train) +y_pred_train = clf.predict(X_train) +y_pred_test = clf.predict(X_test) +y_pred_outliers = clf.predict(X_outliers) +n_error_train = y_pred_train[y_pred_train == -1].size +n_error_test = y_pred_test[y_pred_test == -1].size +n_error_outliers = y_pred_outliers[y_pred_outliers == 1].size + +Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()]) +Z = Z.reshape(xx.shape) + + +# Fit the One-Class SVM using a kernel approximation and SGD +transform = Nystroem(gamma=gamma, random_state=random_state) +clf_sgd = SGDOneClassSVM(nu=nu, shuffle=True, fit_intercept=True, + random_state=random_state, tol=1e-4) +pipe_sgd = make_pipeline(transform, clf_sgd) +pipe_sgd.fit(X_train) +y_pred_train_sgd = pipe_sgd.predict(X_train) +y_pred_test_sgd = pipe_sgd.predict(X_test) +y_pred_outliers_sgd = pipe_sgd.predict(X_outliers) +n_error_train_sgd = y_pred_train_sgd[y_pred_train_sgd == -1].size +n_error_test_sgd = y_pred_test_sgd[y_pred_test_sgd == -1].size +n_error_outliers_sgd = y_pred_outliers_sgd[y_pred_outliers_sgd == 1].size + +Z_sgd = pipe_sgd.decision_function(np.c_[xx.ravel(), yy.ravel()]) +Z_sgd = Z_sgd.reshape(xx.shape) + +# plot the level sets of the decision function +plt.figure(figsize=(9, 6)) +plt.title('One Class SVM') +plt.contourf(xx, yy, Z, levels=np.linspace(Z.min(), 0, 7), cmap=plt.cm.PuBu) +a = plt.contour(xx, yy, Z, levels=[0], linewidths=2, colors='darkred') +plt.contourf(xx, yy, Z, levels=[0, Z.max()], colors='palevioletred') + +s = 20 +b1 = plt.scatter(X_train[:, 0], X_train[:, 1], c='white', s=s, edgecolors='k') +b2 = plt.scatter(X_test[:, 0], X_test[:, 1], c='blueviolet', s=s, + edgecolors='k') +c = plt.scatter(X_outliers[:, 0], X_outliers[:, 1], c='gold', s=s, + edgecolors='k') +plt.axis('tight') +plt.xlim((-4.5, 4.5)) +plt.ylim((-4.5, 4.5)) +plt.legend([a.collections[0], b1, b2, c], + ["learned frontier", "training observations", + "new regular observations", "new abnormal observations"], + loc="upper left") +plt.xlabel( + "error train: %d/%d; errors novel regular: %d/%d; " + "errors novel abnormal: %d/%d" + % (n_error_train, X_train.shape[0], n_error_test, X_test.shape[0], + n_error_outliers, X_outliers.shape[0])) +plt.show() + +plt.figure(figsize=(9, 6)) +plt.title('Online One-Class SVM') +plt.contourf(xx, yy, Z_sgd, levels=np.linspace(Z_sgd.min(), 0, 7), + cmap=plt.cm.PuBu) +a = plt.contour(xx, yy, Z_sgd, levels=[0], linewidths=2, colors='darkred') +plt.contourf(xx, yy, Z_sgd, levels=[0, Z_sgd.max()], colors='palevioletred') + +s = 20 +b1 = plt.scatter(X_train[:, 0], X_train[:, 1], c='white', s=s, edgecolors='k') +b2 = plt.scatter(X_test[:, 0], X_test[:, 1], c='blueviolet', s=s, + edgecolors='k') +c = plt.scatter(X_outliers[:, 0], X_outliers[:, 1], c='gold', s=s, + edgecolors='k') +plt.axis('tight') +plt.xlim((-4.5, 4.5)) +plt.ylim((-4.5, 4.5)) +plt.legend([a.collections[0], b1, b2, c], + ["learned frontier", "training observations", + "new regular observations", "new abnormal observations"], + loc="upper left") +plt.xlabel( + "error train: %d/%d; errors novel regular: %d/%d; " + "errors novel abnormal: %d/%d" + % (n_error_train_sgd, X_train.shape[0], n_error_test_sgd, X_test.shape[0], + n_error_outliers_sgd, X_outliers.shape[0])) +plt.show() diff --git a/examples/miscellaneous/plot_anomaly_comparison.py b/examples/miscellaneous/plot_anomaly_comparison.py index b5ebd96bd8815..c0c3a4f890923 100644 --- a/examples/miscellaneous/plot_anomaly_comparison.py +++ b/examples/miscellaneous/plot_anomaly_comparison.py @@ -22,7 +22,17 @@ One-class SVM might give useful results in these situations depending on the value of its hyperparameters. -:class:`~sklearn.covariance.EllipticEnvelope` assumes the data is Gaussian and +The :class:`sklearn.linear_model.SGDOneClassSVM` is an implementation of the +One-Class SVM based on stochastic gradient descent (SGD). Combined with kernel +approximation, this estimator can be used to approximate the solution +of a kernelized :class:`sklearn.svm.OneClassSVM`. We note that, although not +identical, the decision boundaries of the +:class:`sklearn.linear_model.SGDOneClassSVM` and the ones of +:class:`sklearn.svm.OneClassSVM` are very similar. The main advantage of using +:class:`sklearn.linear_model.SGDOneClassSVM` is that it scales linearly with +the number of samples. + +:class:`sklearn.covariance.EllipticEnvelope` assumes the data is Gaussian and learns an ellipse. It thus degrades when the data is not unimodal. Notice however that this estimator is robust to outliers. @@ -66,6 +76,9 @@ from sklearn.covariance import EllipticEnvelope from sklearn.ensemble import IsolationForest from sklearn.neighbors import LocalOutlierFactor +from sklearn.linear_model import SGDOneClassSVM +from sklearn.kernel_approximation import Nystroem +from sklearn.pipeline import make_pipeline print(__doc__) @@ -77,11 +90,18 @@ n_outliers = int(outliers_fraction * n_samples) n_inliers = n_samples - n_outliers -# define outlier/anomaly detection methods to be compared +# define outlier/anomaly detection methods to be compared. +# the SGDOneClassSVM must be used in a pipeline with a kernel approximation +# to give similar results to the OneClassSVM anomaly_algorithms = [ ("Robust covariance", EllipticEnvelope(contamination=outliers_fraction)), ("One-Class SVM", svm.OneClassSVM(nu=outliers_fraction, kernel="rbf", gamma=0.1)), + ("One-Class SVM (SGD)", make_pipeline( + Nystroem(gamma=0.1, random_state=42, n_components=150), + SGDOneClassSVM(nu=outliers_fraction, shuffle=True, + fit_intercept=True, random_state=42, tol=1e-6) + )), ("Isolation Forest", IsolationForest(contamination=outliers_fraction, random_state=42)), ("Local Outlier Factor", LocalOutlierFactor( @@ -104,7 +124,7 @@ xx, yy = np.meshgrid(np.linspace(-7, 7, 150), np.linspace(-7, 7, 150)) -plt.figure(figsize=(len(anomaly_algorithms) * 2 + 3, 12.5)) +plt.figure(figsize=(len(anomaly_algorithms) * 2 + 4, 12.5)) plt.subplots_adjust(left=.02, right=.98, bottom=.001, top=.96, wspace=.05, hspace=.01) @@ -113,8 +133,8 @@ for i_dataset, X in enumerate(datasets): # Add outliers - X = np.concatenate([X, rng.uniform(low=-6, high=6, - size=(n_outliers, 2))], axis=0) + X = np.concatenate([X, rng.uniform(low=-6, high=6, size=(n_outliers, 2))], + axis=0) for name, algorithm in anomaly_algorithms: t0 = time.time() diff --git a/sklearn/linear_model/__init__.py b/sklearn/linear_model/__init__.py index 110e0008bccc9..f715e30795961 100644 --- a/sklearn/linear_model/__init__.py +++ b/sklearn/linear_model/__init__.py @@ -18,7 +18,7 @@ GammaRegressor, TweedieRegressor) from ._huber import HuberRegressor from ._sgd_fast import Hinge, Log, ModifiedHuber, SquaredLoss, Huber -from ._stochastic_gradient import SGDClassifier, SGDRegressor +from ._stochastic_gradient import SGDClassifier, SGDRegressor, SGDOneClassSVM from ._ridge import (Ridge, RidgeCV, RidgeClassifier, RidgeClassifierCV, ridge_regression) from ._logistic import LogisticRegression, LogisticRegressionCV @@ -65,6 +65,7 @@ 'RidgeClassifierCV', 'SGDClassifier', 'SGDRegressor', + 'SGDOneClassSVM', 'SquaredLoss', 'TheilSenRegressor', 'enet_path', diff --git a/sklearn/linear_model/_sgd_fast.pyx b/sklearn/linear_model/_sgd_fast.pyx index 3940e5d873669..dab7b36b14d0e 100644 --- a/sklearn/linear_model/_sgd_fast.pyx +++ b/sklearn/linear_model/_sgd_fast.pyx @@ -55,7 +55,7 @@ cdef class LossFunction: Parameters ---------- p : double - The prediction, p = w^T x + The prediction, p = w^T x + intercept y : double The true value (aka target) @@ -358,6 +358,7 @@ def _plain_sgd(np.ndarray[double, ndim=1, mode='c'] weights, double weight_pos, double weight_neg, int learning_rate, double eta0, double power_t, + bint one_class, double t=1.0, double intercept_decay=1.0, int average=0): @@ -427,6 +428,8 @@ def _plain_sgd(np.ndarray[double, ndim=1, mode='c'] weights, The initial learning rate. power_t : double The exponent for inverse scaling learning rate. + one_class : boolean + Whether to solve the One-Class SVM optimization problem. t : double Initial state of the learning rate. This value is equal to the iteration count except when the learning rate is set to `optimal`. @@ -435,6 +438,7 @@ def _plain_sgd(np.ndarray[double, ndim=1, mode='c'] weights, The number of iterations before averaging starts. average=1 is equivalent to averaging for all iterations. + Returns ------- weights : array, shape=[n_features] @@ -468,6 +472,7 @@ def _plain_sgd(np.ndarray[double, ndim=1, mode='c'] weights, cdef double eta = 0.0 cdef double p = 0.0 cdef double update = 0.0 + cdef double intercept_update = 0.0 cdef double sumloss = 0.0 cdef double score = 0.0 cdef double best_loss = INFINITY @@ -574,10 +579,15 @@ def _plain_sgd(np.ndarray[double, ndim=1, mode='c'] weights, # do not scale to negative values when eta or alpha are too # big: instead set the weights to zero w.scale(max(0, 1.0 - ((1.0 - l1_ratio) * eta * alpha))) + if update != 0.0: w.add(x_data_ptr, x_ind_ptr, xnnz, update) - if fit_intercept == 1: - intercept += update * intercept_decay + if fit_intercept == 1: + intercept_update = update + if one_class: # specific for One-Class SVM + intercept_update -= 2. * eta * alpha + if intercept_update != 0: + intercept += intercept_update * intercept_decay if 0 < average <= t: # compute the average for the intercept and update the diff --git a/sklearn/linear_model/_stochastic_gradient.py b/sklearn/linear_model/_stochastic_gradient.py index a426c9a8d95f2..44ecf564ffcc5 100644 --- a/sklearn/linear_model/_stochastic_gradient.py +++ b/sklearn/linear_model/_stochastic_gradient.py @@ -2,7 +2,9 @@ # Mathieu Blondel (partial_fit support) # # License: BSD 3 clause -"""Classification and regression using Stochastic Gradient Descent (SGD).""" +"""Classification, regression and One-Class SVM using Stochastic Gradient +Descent (SGD). +""" import numpy as np import warnings @@ -14,7 +16,7 @@ from ..base import clone, is_classifier from ._base import LinearClassifierMixin, SparseCoefMixin from ._base import make_dataset -from ..base import BaseEstimator, RegressorMixin +from ..base import BaseEstimator, RegressorMixin, OutlierMixin from ..utils import check_random_state from ..utils.extmath import safe_sparse_dot from ..utils.multiclass import _check_partial_fit_first_call @@ -134,7 +136,7 @@ def _validate_params(self, for_partial_fit=False): raise ValueError("max_iter must be > zero. Got %f" % self.max_iter) if not (0.0 <= self.l1_ratio <= 1.0): raise ValueError("l1_ratio must be in [0, 1]") - if self.alpha < 0.0: + if not isinstance(self, SGDOneClassSVM) and self.alpha < 0.0: raise ValueError("alpha must be >= 0") if self.n_iter_no_change < 1: raise ValueError("n_iter_no_change must be >= 1") @@ -190,7 +192,7 @@ def _get_penalty_type(self, penalty): raise ValueError("Penalty %s is not supported. " % penalty) from e def _allocate_parameter_mem(self, n_classes, n_features, coef_init=None, - intercept_init=None): + intercept_init=None, one_class=0): """Allocate mem for parameters; initialize if provided.""" if n_classes > 2: # allocate coef_ for multi-class @@ -215,7 +217,7 @@ def _allocate_parameter_mem(self, n_classes, n_features, coef_init=None, self.intercept_ = np.zeros(n_classes, dtype=np.float64, order="C") else: - # allocate coef_ for binary problem + # allocate coef_ if coef_init is not None: coef_init = np.asarray(coef_init, dtype=np.float64, order="C") @@ -229,26 +231,36 @@ def _allocate_parameter_mem(self, n_classes, n_features, coef_init=None, dtype=np.float64, order="C") - # allocate intercept_ for binary problem + # allocate intercept_ if intercept_init is not None: intercept_init = np.asarray(intercept_init, dtype=np.float64) if intercept_init.shape != (1,) and intercept_init.shape != (): raise ValueError("Provided intercept_init " "does not match dataset.") - self.intercept_ = intercept_init.reshape(1,) + if one_class: + self.offset_ = intercept_init.reshape(1,) + else: + self.intercept_ = intercept_init.reshape(1,) else: - self.intercept_ = np.zeros(1, dtype=np.float64, order="C") + if one_class: + self.offset_ = np.zeros(1, dtype=np.float64, order="C") + else: + self.intercept_ = np.zeros(1, dtype=np.float64, order="C") # initialize average parameters if self.average > 0: self._standard_coef = self.coef_ - self._standard_intercept = self.intercept_ self._average_coef = np.zeros(self.coef_.shape, dtype=np.float64, order="C") - self._average_intercept = np.zeros(self._standard_intercept.shape, - dtype=np.float64, - order="C") + if one_class: + self._standard_intercept = 1 - self.offset_ + else: + self._standard_intercept = self.intercept_ + + self._average_intercept = np.zeros( + self._standard_intercept.shape, dtype=np.float64, + order="C") def _make_validation_split(self, y): """Split the dataset between training set and validation set. @@ -447,7 +459,7 @@ def fit_binary(est, i, X, y, alpha, C, learning_rate, max_iter, est.early_stopping, validation_score_cb, int(est.n_iter_no_change), max_iter, tol, int(est.fit_intercept), int(est.verbose), int(est.shuffle), seed, pos_weight, neg_weight, learning_rate_type, - est.eta0, est.power_t, est.t_, intercept_decay, est.average) + est.eta0, est.power_t, 0, est.t_, intercept_decay, est.average) if est.average: if len(est.classes_) == 2: @@ -1363,7 +1375,7 @@ def _fit_regressor(self, X, y, alpha, C, loss, learning_rate, seed, 1.0, 1.0, learning_rate_type, - self.eta0, self.power_t, self.t_, + self.eta0, self.power_t, 0, self.t_, intercept_decay, self.average) self.t_ += self.n_iter_ * X.shape[0] @@ -1626,3 +1638,449 @@ def _more_tags(self): 'zero sample_weight is not equivalent to removing samples', } } + + +class SGDOneClassSVM(BaseSGD, OutlierMixin): + """Solves linear One-Class SVM using Stochastic Gradient Descent. + + This implementation is meant to be used with a kernel approximation + technique (e.g. `sklearn.kernel_approximation.Nystroem`) to obtain results + similar to `sklearn.svm.OneClassSVM` which uses a Gaussian kernel by + default. + + Read more in the :ref:`User Guide <sgd_online_one_class_svm>`. + + .. versionadded:: 1.0 + + Parameters + ---------- + nu : float, optional + The nu parameter of the One Class SVM: an upper bound on the + fraction of training errors and a lower bound of the fraction of + support vectors. Should be in the interval (0, 1]. By default 0.5 + will be taken. + + fit_intercept : bool + Whether the intercept should be estimated or not. Defaults to True. + + max_iter : int, optional + The maximum number of passes over the training data (aka epochs). + It only impacts the behavior in the ``fit`` method, and not the + `partial_fit`. Defaults to 1000. + + tol : float or None, optional + The stopping criterion. If it is not None, the iterations will stop + when (loss > previous_loss - tol). Defaults to 1e-3. + + shuffle : bool, optional + Whether or not the training data should be shuffled after each epoch. + Defaults to True. + + verbose : integer, optional + The verbosity level + + random_state : int, RandomState instance or None, optional (default=None) + The seed of the pseudo random number generator to use when shuffling + the data. If int, random_state is the seed used by the random number + generator; If RandomState instance, random_state is the random number + generator; If None, the random number generator is the RandomState + instance used by `np.random`. + + learning_rate : string, optional + The learning rate schedule: + + 'constant': + eta = eta0 + 'optimal': [default] + eta = 1.0 / (alpha * (t + t0)) + where t0 is chosen by a heuristic proposed by Leon Bottou. + 'invscaling': + eta = eta0 / pow(t, power_t) + 'adaptive': + eta = eta0, as long as the training keeps decreasing. + Each time n_iter_no_change consecutive epochs fail to decrease the + training loss by tol or fail to increase validation score by tol if + early_stopping is True, the current learning rate is divided by 5. + + eta0 : double + The initial learning rate for the 'constant', 'invscaling' or + 'adaptive' schedules. The default value is 0.0 as eta0 is not used by + the default schedule 'optimal'. + + power_t : double + The exponent for inverse scaling learning rate [default 0.5]. + + warm_start : bool, optional + When set to True, reuse the solution of the previous call to fit as + initialization, otherwise, just erase the previous solution. + See :term:`the Glossary <warm_start>`. + + Repeatedly calling fit or partial_fit when warm_start is True can + result in a different solution than when calling fit a single time + because of the way the data is shuffled. + If a dynamic learning rate is used, the learning rate is adapted + depending on the number of samples already seen. Calling ``fit`` resets + this counter, while ``partial_fit`` will result in increasing the + existing counter. + + average : bool or int, optional + When set to True, computes the averaged SGD weights and stores the + result in the ``coef_`` attribute. If set to an int greater than 1, + averaging will begin once the total number of samples seen reaches + average. So ``average=10`` will begin averaging after seeing 10 + samples. + + Attributes + ---------- + coef_ : array, shape (1, n_features) + Weights assigned to the features. + + offset_ : array, shape (1,) + Offset used to define the decision function from the raw scores. + We have the relation: decision_function = score_samples - offset. + + n_iter_ : int + The actual number of iterations to reach the stopping criterion. + + t_ : int + Number of weight updates performed during training. + Same as ``(n_iter_ * n_samples)``. + + loss_function_ : concrete ``LossFunction`` + + Examples + -------- + >>> import numpy as np + >>> from sklearn import linear_model + >>> X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]]) + >>> clf = linear_model.SGDOneClassSVM(random_state=42) + >>> clf.fit(X) + SGDOneClassSVM(random_state=42) + + >>> print(clf.predict([[4, 4]])) + [1] + + See also + -------- + sklearn.svm.OneClassSVM + + Notes + ----- + This estimator has a linear complexity in the number of training samples + and is thus better suited than the `sklearn.svm.OneClassSVM` + implementation for datasets with a large number of training samples (say + > 10,000). + """ + + loss_functions = {"hinge": (Hinge, 1.0)} + + def __init__(self, nu=0.5, fit_intercept=True, max_iter=1000, tol=1e-3, + shuffle=True, verbose=0, random_state=None, + learning_rate="optimal", eta0=0.0, power_t=0.5, + warm_start=False, average=False): + + alpha = nu / 2 + self.nu = nu + super(SGDOneClassSVM, self).__init__( + loss="hinge", penalty='l2', alpha=alpha, C=1.0, l1_ratio=0, + fit_intercept=fit_intercept, max_iter=max_iter, tol=tol, + shuffle=shuffle, verbose=verbose, epsilon=DEFAULT_EPSILON, + random_state=random_state, learning_rate=learning_rate, + eta0=eta0, power_t=power_t, early_stopping=False, + validation_fraction=0.1, n_iter_no_change=5, + warm_start=warm_start, average=average) + + def _validate_params(self, for_partial_fit=False): + """Validate input params. """ + if not(0 < self.nu <= 1): + raise ValueError("nu must be in (0, 1], got nu=%f" % self.nu) + + super(SGDOneClassSVM, self)._validate_params( + for_partial_fit=for_partial_fit) + + def _fit_one_class(self, X, alpha, C, sample_weight, + learning_rate, max_iter): + """Uses SGD implementation with X and y=np.ones(n_samples).""" + + # The One-Class SVM uses the SGD implementation with + # y=np.ones(n_samples). + n_samples = X.shape[0] + y = np.ones(n_samples, dtype=np.float64, order="C") + + dataset, offset_decay = make_dataset(X, y, sample_weight) + + penalty_type = self._get_penalty_type(self.penalty) + learning_rate_type = self._get_learning_rate_type(learning_rate) + + # early stopping is set to False for the One-Class SVM. thus + # validation_mask and validation_score_cb will be set to values + # associated to early_stopping=False in _make_validation_split and + # _make_validation_score_cb respectively. + validation_mask = self._make_validation_split(y) + validation_score_cb = self._make_validation_score_cb( + validation_mask, X, y, sample_weight) + + random_state = check_random_state(self.random_state) + # numpy mtrand expects a C long which is a signed 32 bit integer under + # Windows + seed = random_state.randint(0, np.iinfo(np.int32).max) + + tol = self.tol if self.tol is not None else -np.inf + + one_class = 1 + # There are no class weights for the One-Class SVM and they are + # therefore set to 1. + pos_weight = 1 + neg_weight = 1 + + if self.average: + coef = self._standard_coef + intercept = self._standard_intercept + average_coef = self._average_coef + average_intercept = self._average_intercept + else: + coef = self.coef_ + intercept = 1 - self.offset_ + average_coef = None # Not used + average_intercept = [0] # Not used + + coef, intercept, average_coef, average_intercept, self.n_iter_ = \ + _plain_sgd(coef, + intercept[0], + average_coef, + average_intercept[0], + self.loss_function_, + penalty_type, + alpha, C, + self.l1_ratio, + dataset, + validation_mask, self.early_stopping, + validation_score_cb, + int(self.n_iter_no_change), + max_iter, tol, + int(self.fit_intercept), + int(self.verbose), + int(self.shuffle), + seed, + neg_weight, pos_weight, + learning_rate_type, + self.eta0, self.power_t, + one_class, self.t_, + offset_decay, self.average) + + self.t_ += self.n_iter_ * n_samples + + if self.average > 0: + + self._average_intercept = np.atleast_1d(average_intercept) + self._standard_intercept = np.atleast_1d(intercept) + + if self.average <= self.t_ - 1.0: + # made enough updates for averaging to be taken into account + self.coef_ = average_coef + self.offset_ = 1 - np.atleast_1d(average_intercept) + else: + self.coef_ = coef + self.offset_ = 1 - np.atleast_1d(intercept) + + else: + self.offset_ = 1 - np.atleast_1d(intercept) + + def _partial_fit(self, X, alpha, C, loss, learning_rate, max_iter, + sample_weight, coef_init, offset_init): + first_call = getattr(self, "coef_", None) is None + X = self._validate_data( + X, None, accept_sparse='csr', dtype=np.float64, + order="C", accept_large_sparse=False, + reset=first_call) + + n_features = X.shape[1] + + # Allocate datastructures from input arguments + sample_weight = _check_sample_weight(sample_weight, X) + + # We use intercept = 1 - offset where intercept is the intercept of + # the SGD implementation and offset is the offset of the One-Class SVM + # optimization problem. + if getattr(self, "coef_", None) is None or coef_init is not None: + self._allocate_parameter_mem(1, n_features, + coef_init, offset_init, 1) + elif n_features != self.coef_.shape[-1]: + raise ValueError("Number of features %d does not match previous " + "data %d." % (n_features, self.coef_.shape[-1])) + + if self.average and getattr(self, "_average_coef", None) is None: + self._average_coef = np.zeros(n_features, dtype=np.float64, + order="C") + self._average_intercept = np.zeros(1, dtype=np.float64, order="C") + + self.loss_function_ = self._get_loss_function(loss) + if not hasattr(self, "t_"): + self.t_ = 1.0 + + # delegate to concrete training procedure + self._fit_one_class(X, alpha=alpha, C=C, + learning_rate=learning_rate, + sample_weight=sample_weight, + max_iter=max_iter) + + return self + + def partial_fit(self, X, y=None, sample_weight=None): + """Fit linear One-Class SVM with Stochastic Gradient Descent. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape (n_samples, n_features) + Subset of the training data. + + sample_weight : array-like, shape (n_samples,), optional + Weights applied to individual samples. + If not provided, uniform weights are assumed. + + Returns + ------- + self : returns an instance of self. + """ + + alpha = self.nu / 2 + self._validate_params(for_partial_fit=True) + + return self._partial_fit(X, alpha, C=1.0, loss=self.loss, + learning_rate=self.learning_rate, + max_iter=1, + sample_weight=sample_weight, + coef_init=None, offset_init=None) + + def _fit(self, X, alpha, C, loss, learning_rate, coef_init=None, + offset_init=None, sample_weight=None): + self._validate_params() + + if self.warm_start and hasattr(self, "coef_"): + if coef_init is None: + coef_init = self.coef_ + if offset_init is None: + offset_init = self.offset_ + else: + self.coef_ = None + self.offset_ = None + + # Clear iteration count for multiple call to fit. + self.t_ = 1.0 + + self._partial_fit(X, alpha, C, loss, learning_rate, self.max_iter, + sample_weight, coef_init, offset_init) + + if (self.tol is not None and self.tol > -np.inf + and self.n_iter_ == self.max_iter): + warnings.warn("Maximum number of iteration reached before " + "convergence. Consider increasing max_iter to " + "improve the fit.", + ConvergenceWarning) + + return self + + def fit(self, X, y=None, coef_init=None, offset_init=None, + sample_weight=None): + """Fit linear One-Class SVM with Stochastic Gradient Descent. + + This solves an equivalent optimization problem of the + One-Class SVM primal optimization problem and returns a weight vector + w and an offset rho such that the decision function is given by + <w, x> - rho. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape (n_samples, n_features) + Training data. + + coef_init : array, shape (n_classes, n_features) + The initial coefficients to warm-start the optimization. + + offset_init : array, shape (n_classes,) + The initial offset to warm-start the optimization. + + sample_weight : array-like, shape (n_samples,), optional + Weights applied to individual samples. + If not provided, uniform weights are assumed. These weights will + be multiplied with class_weight (passed through the + constructor) if class_weight is specified. + + Returns + ------- + self : returns an instance of self. + """ + + alpha = self.nu / 2 + self._fit(X, alpha=alpha, C=1.0, + loss=self.loss, learning_rate=self.learning_rate, + coef_init=coef_init, offset_init=offset_init, + sample_weight=sample_weight) + + return self + + def decision_function(self, X): + """Signed distance to the separating hyperplane. + + Signed distance is positive for an inlier and negative for an + outlier. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape (n_samples, n_features) + Testing data. + + Returns + ------- + dec : array-like, shape (n_samples,) + Decision function values of the samples. + """ + + check_is_fitted(self, "coef_") + + X = self._validate_data(X, accept_sparse='csr', reset=False) + decisions = safe_sparse_dot(X, self.coef_.T, + dense_output=True) - self.offset_ + + return decisions.ravel() + + def score_samples(self, X): + """Raw scoring function of the samples. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape (n_samples, n_features) + Testing data. + + Returns + ------- + score_samples : array-like, shape (n_samples,) + Unshiffted scoring function values of the samples. + """ + score_samples = self.decision_function(X) + self.offset_ + return score_samples + + def predict(self, X): + """Return labels (1 inlier, -1 outlier) of the samples. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape (n_samples, n_features) + Testing data. + + Returns + ------- + y : array, shape (n_samples,) + Labels of the samples. + """ + y = (self.decision_function(X) >= 0).astype(np.int32) + y[y == 0] = -1 # for consistency with outlier detectors + return y + + def _more_tags(self): + return { + '_xfail_checks': { + 'check_sample_weights_invariance': + 'zero sample_weight is not equivalent to removing samples', + } + } diff --git a/sklearn/svm/_classes.py b/sklearn/svm/_classes.py index 908ece408bb1d..c402779f4eeb6 100644 --- a/sklearn/svm/_classes.py +++ b/sklearn/svm/_classes.py @@ -1334,6 +1334,10 @@ class OneClassSVM(OutlierMixin, BaseLibSVM): array([-1, 1, 1, 1, -1]) >>> clf.score_samples(X) array([1.7798..., 2.0547..., 2.0556..., 2.0561..., 1.7332...]) + + See also + -------- + sklearn.linear_model.SGDOneClassSVM """ _impl = 'one_class'
diff --git a/sklearn/linear_model/tests/test_sgd.py b/sklearn/linear_model/tests/test_sgd.py index aba043024fea3..f943592c02005 100644 --- a/sklearn/linear_model/tests/test_sgd.py +++ b/sklearn/linear_model/tests/test_sgd.py @@ -9,14 +9,16 @@ from sklearn.utils._testing import assert_array_equal from sklearn.utils._testing import assert_almost_equal from sklearn.utils._testing import assert_array_almost_equal -from sklearn.utils._testing import assert_raises_regexp from sklearn.utils._testing import ignore_warnings from sklearn.utils.fixes import parse_version from sklearn import linear_model, datasets, metrics from sklearn.base import clone, is_classifier +from sklearn.svm import OneClassSVM from sklearn.preprocessing import LabelEncoder, scale, MinMaxScaler from sklearn.preprocessing import StandardScaler +from sklearn.kernel_approximation import Nystroem +from sklearn.pipeline import make_pipeline from sklearn.exceptions import ConvergenceWarning from sklearn.model_selection import StratifiedShuffleSplit, ShuffleSplit from sklearn.linear_model import _sgd_fast as sgd_fast @@ -67,6 +69,21 @@ def decision_function(self, X, *args, **kw): **kw) +class _SparseSGDOneClassSVM(linear_model.SGDOneClassSVM): + def fit(self, X, *args, **kw): + X = sp.csr_matrix(X) + return linear_model.SGDOneClassSVM.fit(self, X, *args, **kw) + + def partial_fit(self, X, *args, **kw): + X = sp.csr_matrix(X) + return linear_model.SGDOneClassSVM.partial_fit(self, X, *args, **kw) + + def decision_function(self, X, *args, **kw): + X = sp.csr_matrix(X) + return linear_model.SGDOneClassSVM.decision_function(self, X, *args, + **kw) + + def SGDClassifier(**kwargs): _update_kwargs(kwargs) return linear_model.SGDClassifier(**kwargs) @@ -77,6 +94,11 @@ def SGDRegressor(**kwargs): return linear_model.SGDRegressor(**kwargs) +def SGDOneClassSVM(**kwargs): + _update_kwargs(kwargs) + return linear_model.SGDOneClassSVM(**kwargs) + + def SparseSGDClassifier(**kwargs): _update_kwargs(kwargs) return _SparseSGDClassifier(**kwargs) @@ -87,6 +109,11 @@ def SparseSGDRegressor(**kwargs): return _SparseSGDRegressor(**kwargs) +def SparseSGDOneClassSVM(**kwargs): + _update_kwargs(kwargs) + return _SparseSGDOneClassSVM(**kwargs) + + # Test Data # test sample 1 @@ -252,7 +279,8 @@ def test_clone(klass): @pytest.mark.parametrize('klass', [SGDClassifier, SparseSGDClassifier, - SGDRegressor, SparseSGDRegressor]) + SGDRegressor, SparseSGDRegressor, + SGDOneClassSVM, SparseSGDOneClassSVM]) def test_plain_has_no_average_attr(klass): clf = klass(average=True, eta0=.01) clf.fit(X, Y) @@ -285,7 +313,8 @@ def test_sgd_deprecated_attr(klass): @pytest.mark.parametrize('klass', [SGDClassifier, SparseSGDClassifier, - SGDRegressor, SparseSGDRegressor]) + SGDRegressor, SparseSGDRegressor, + SGDOneClassSVM, SparseSGDOneClassSVM]) def test_late_onset_averaging_not_reached(klass): clf1 = klass(average=600) clf2 = klass() @@ -298,7 +327,11 @@ def test_late_onset_averaging_not_reached(klass): clf2.partial_fit(X, Y) assert_array_almost_equal(clf1.coef_, clf2.coef_, decimal=16) - assert_almost_equal(clf1.intercept_, clf2.intercept_, decimal=16) + if klass in [SGDClassifier, SparseSGDClassifier, SGDRegressor, + SparseSGDRegressor]: + assert_almost_equal(clf1.intercept_, clf2.intercept_, decimal=16) + elif klass in [SGDOneClassSVM, SparseSGDOneClassSVM]: + assert_allclose(clf1.offset_, clf2.offset_) @pytest.mark.parametrize('klass', [SGDClassifier, SparseSGDClassifier, @@ -444,28 +477,32 @@ def test_sgd_bad_l1_ratio(klass): klass(l1_ratio=1.1) [email protected]('klass', [SGDClassifier, SparseSGDClassifier]) [email protected]('klass', [SGDClassifier, SparseSGDClassifier, + SGDOneClassSVM, SparseSGDOneClassSVM]) def test_sgd_bad_learning_rate_schedule(klass): # Check whether expected ValueError on bad learning_rate with pytest.raises(ValueError): klass(learning_rate="<unknown>") [email protected]('klass', [SGDClassifier, SparseSGDClassifier]) [email protected]('klass', [SGDClassifier, SparseSGDClassifier, + SGDOneClassSVM, SparseSGDOneClassSVM]) def test_sgd_bad_eta0(klass): # Check whether expected ValueError on bad eta0 with pytest.raises(ValueError): klass(eta0=0, learning_rate="constant") [email protected]('klass', [SGDClassifier, SparseSGDClassifier]) [email protected]('klass', [SGDClassifier, SparseSGDClassifier, + SGDOneClassSVM, SparseSGDOneClassSVM]) def test_sgd_max_iter_param(klass): # Test parameter validity check with pytest.raises(ValueError): klass(max_iter=-10000) [email protected]('klass', [SGDClassifier, SparseSGDClassifier]) [email protected]('klass', [SGDClassifier, SparseSGDClassifier, + SGDOneClassSVM, SparseSGDOneClassSVM]) def test_sgd_shuffle_param(klass): # Test parameter validity check with pytest.raises(ValueError): @@ -493,7 +530,8 @@ def test_sgd_n_iter_no_change(klass): klass(n_iter_no_change=0) [email protected]('klass', [SGDClassifier, SparseSGDClassifier]) [email protected]('klass', [SGDClassifier, SparseSGDClassifier, + SGDOneClassSVM, SparseSGDOneClassSVM]) def test_argument_coef(klass): # Checks coef_init not allowed as model argument (only fit) # Provided coef_ does not match dataset @@ -501,7 +539,8 @@ def test_argument_coef(klass): klass(coef_init=np.zeros((3,))) [email protected]('klass', [SGDClassifier, SparseSGDClassifier]) [email protected]('klass', [SGDClassifier, SparseSGDClassifier, + SGDOneClassSVM, SparseSGDOneClassSVM]) def test_provide_coef(klass): # Checks coef_init shape for the warm starts # Provided coef_ does not match dataset. @@ -509,12 +548,17 @@ def test_provide_coef(klass): klass().fit(X, Y, coef_init=np.zeros((3,))) [email protected]('klass', [SGDClassifier, SparseSGDClassifier]) [email protected]('klass', [SGDClassifier, SparseSGDClassifier, + SGDOneClassSVM, SparseSGDOneClassSVM]) def test_set_intercept(klass): # Checks intercept_ shape for the warm starts # Provided intercept_ does not match dataset. - with pytest.raises(ValueError): - klass().fit(X, Y, intercept_init=np.zeros((3,))) + if klass in [SGDClassifier, SparseSGDClassifier]: + with pytest.raises(ValueError): + klass().fit(X, Y, intercept_init=np.zeros((3,))) + elif klass in [SGDOneClassSVM, SparseSGDOneClassSVM]: + with pytest.raises(ValueError): + klass().fit(X, Y, offset_init=np.zeros((3,))) @pytest.mark.parametrize('klass', [SGDClassifier, SparseSGDClassifier]) @@ -590,10 +634,8 @@ def test_partial_fit_weight_class_balanced(klass): r"estimate the class frequency distributions\. " r"Pass the resulting weights as the class_weight " r"parameter\.") - assert_raises_regexp(ValueError, - regex, - klass(class_weight='balanced').partial_fit, - X, Y, classes=np.unique(Y)) + with pytest.raises(ValueError, match=regex): + klass(class_weight='balanced').partial_fit(X, Y, classes=np.unique(Y)) @pytest.mark.parametrize('klass', [SGDClassifier, SparseSGDClassifier]) @@ -947,10 +989,14 @@ def test_sample_weights(klass): assert_array_equal(clf.predict([[0.2, -1.0]]), np.array([-1])) [email protected]('klass', [SGDClassifier, SparseSGDClassifier]) [email protected]('klass', [SGDClassifier, SparseSGDClassifier, + SGDOneClassSVM, SparseSGDOneClassSVM]) def test_wrong_sample_weights(klass): # Test if ValueError is raised if sample_weight has wrong shape - clf = klass(alpha=0.1, max_iter=1000, fit_intercept=False) + if klass in [SGDClassifier, SparseSGDClassifier]: + clf = klass(alpha=0.1, max_iter=1000, fit_intercept=False) + elif klass in [SGDOneClassSVM, SparseSGDOneClassSVM]: + clf = klass(nu=0.1, max_iter=1000, fit_intercept=False) # provided sample_weight too long with pytest.raises(ValueError): clf.fit(X, Y, sample_weight=np.arange(7)) @@ -1341,6 +1387,303 @@ def test_loss_function_epsilon(klass): assert clf.loss_functions['huber'][1] == 0.1 +############################################################################### +# SGD One Class SVM Test Case + +# a simple implementation of ASGD to use for testing SGDOneClassSVM +def asgd_oneclass(klass, X, eta, nu, coef_init=None, offset_init=0.0): + if coef_init is None: + coef = np.zeros(X.shape[1]) + else: + coef = coef_init + + average_coef = np.zeros(X.shape[1]) + offset = offset_init + intercept = 1 - offset + average_intercept = 0.0 + decay = 1.0 + + # sparse data has a fixed decay of .01 + if klass == SparseSGDOneClassSVM: + decay = .01 + + for i, entry in enumerate(X): + p = np.dot(entry, coef) + p += intercept + if p <= 1.0: + gradient = -1 + else: + gradient = 0 + coef *= max(0, 1.0 - (eta * nu / 2)) + coef += -(eta * gradient * entry) + intercept += -(eta * (nu + gradient)) * decay + + average_coef *= i + average_coef += coef + average_coef /= i + 1.0 + + average_intercept *= i + average_intercept += intercept + average_intercept /= i + 1.0 + + return average_coef, 1 - average_intercept + + [email protected]('klass', [SGDOneClassSVM, SparseSGDOneClassSVM]) [email protected]('nu', [-0.5, 2]) +def test_bad_nu_values(klass, nu): + msg = r"nu must be in \(0, 1]" + with pytest.raises(ValueError, match=msg): + klass(nu=nu) + + clf = klass(nu=0.05) + clf2 = clone(clf) + with pytest.raises(ValueError, match=msg): + clf2.set_params(nu=nu) + + [email protected]('klass', [SGDOneClassSVM, SparseSGDOneClassSVM]) +def _test_warm_start_oneclass(klass, X, lr): + # Test that explicit warm restart... + clf = klass(nu=0.5, eta0=0.01, shuffle=False, + learning_rate=lr) + clf.fit(X) + + clf2 = klass(nu=0.1, eta0=0.01, shuffle=False, + learning_rate=lr) + clf2.fit(X, coef_init=clf.coef_.copy(), + offset_init=clf.offset_.copy()) + + # ... and implicit warm restart are equivalent. + clf3 = klass(nu=0.5, eta0=0.01, shuffle=False, + warm_start=True, learning_rate=lr) + clf3.fit(X) + + assert clf3.t_ == clf.t_ + assert_allclose(clf3.coef_, clf.coef_) + + clf3.set_params(nu=0.1) + clf3.fit(X) + + assert clf3.t_ == clf2.t_ + assert_allclose(clf3.coef_, clf2.coef_) + + [email protected]('klass', [SGDOneClassSVM, SparseSGDOneClassSVM]) [email protected]('lr', + ["constant", "optimal", "invscaling", "adaptive"]) +def test_warm_start_oneclass(klass, lr): + _test_warm_start_oneclass(klass, X, lr) + + [email protected]('klass', [SGDOneClassSVM, SparseSGDOneClassSVM]) +def test_clone_oneclass(klass): + # Test whether clone works ok. + clf = klass(nu=0.5) + clf = clone(clf) + clf.set_params(nu=0.1) + clf.fit(X) + + clf2 = klass(nu=0.1) + clf2.fit(X) + + assert_array_equal(clf.coef_, clf2.coef_) + + [email protected]('klass', [SGDOneClassSVM, SparseSGDOneClassSVM]) +def test_partial_fit_oneclass(klass): + third = X.shape[0] // 3 + clf = klass(nu=0.1) + + clf.partial_fit(X[:third]) + assert clf.coef_.shape == (X.shape[1], ) + assert clf.offset_.shape == (1,) + assert clf.predict([[0, 0]]).shape == (1, ) + id1 = id(clf.coef_.data) + + clf.partial_fit(X[third:]) + id2 = id(clf.coef_.data) + # check that coef_ haven't been re-allocated + assert id1 == id2 + + # raises ValueError if number of features does not match previous data + with pytest.raises(ValueError): + clf.partial_fit(X[:, 1]) + + [email protected]('klass', [SGDOneClassSVM, SparseSGDOneClassSVM]) [email protected]('lr', + ["constant", "optimal", "invscaling", "adaptive"]) +def test_partial_fit_equal_fit_oneclass(klass, lr): + clf = klass(nu=0.05, max_iter=2, eta0=0.01, + learning_rate=lr, shuffle=False) + clf.fit(X) + y_scores = clf.decision_function(T) + t = clf.t_ + coef = clf.coef_ + offset = clf.offset_ + + clf = klass(nu=0.05, eta0=0.01, max_iter=1, + learning_rate=lr, shuffle=False) + for _ in range(2): + clf.partial_fit(X) + y_scores2 = clf.decision_function(T) + + assert clf.t_ == t + assert_allclose(y_scores, y_scores2) + assert_allclose(clf.coef_, coef) + assert_allclose(clf.offset_, offset) + + [email protected]('klass', [SGDOneClassSVM, SparseSGDOneClassSVM]) +def test_late_onset_averaging_reached_oneclass(klass): + # Test average + eta0 = .001 + nu = .05 + + # 2 passes over the training set but average only at second pass + clf1 = klass(average=7, learning_rate="constant", eta0=eta0, + nu=nu, max_iter=2, shuffle=False) + # 1 pass over the training set with no averaging + clf2 = klass(average=0, learning_rate="constant", eta0=eta0, + nu=nu, max_iter=1, shuffle=False) + + clf1.fit(X) + clf2.fit(X) + + # Start from clf2 solution, compute averaging using asgd function and + # compare with clf1 solution + average_coef, average_offset = \ + asgd_oneclass(klass, X, eta0, nu, + coef_init=clf2.coef_.ravel(), + offset_init=clf2.offset_) + + assert_allclose(clf1.coef_.ravel(), average_coef.ravel()) + assert_allclose(clf1.offset_, average_offset) + + [email protected]('klass', [SGDOneClassSVM, SparseSGDOneClassSVM]) +def test_sgd_averaged_computed_correctly_oneclass(klass): + # Tests the average SGD One-Class SVM matches the naive implementation + eta = .001 + nu = .05 + n_samples = 20 + n_features = 10 + rng = np.random.RandomState(0) + X = rng.normal(size=(n_samples, n_features)) + + clf = klass(learning_rate='constant', + eta0=eta, nu=nu, + fit_intercept=True, + max_iter=1, average=True, shuffle=False) + + clf.fit(X) + average_coef, average_offset = asgd_oneclass(klass, X, eta, nu) + + assert_allclose(clf.coef_, average_coef) + assert_allclose(clf.offset_, average_offset) + + [email protected]('klass', [SGDOneClassSVM, SparseSGDOneClassSVM]) +def test_sgd_averaged_partial_fit_oneclass(klass): + # Tests whether the partial fit yields the same average as the fit + eta = .001 + nu = .05 + n_samples = 20 + n_features = 10 + rng = np.random.RandomState(0) + X = rng.normal(size=(n_samples, n_features)) + + clf = klass(learning_rate='constant', + eta0=eta, nu=nu, + fit_intercept=True, + max_iter=1, average=True, shuffle=False) + + clf.partial_fit(X[:int(n_samples / 2)][:]) + clf.partial_fit(X[int(n_samples / 2):][:]) + average_coef, average_offset = asgd_oneclass(klass, X, eta, nu) + + assert_allclose(clf.coef_, average_coef) + assert_allclose(clf.offset_, average_offset) + + [email protected]('klass', [SGDOneClassSVM, SparseSGDOneClassSVM]) +def test_average_sparse_oneclass(klass): + # Checks the average coef on data with 0s + eta = .001 + nu = .01 + clf = klass(learning_rate='constant', + eta0=eta, nu=nu, + fit_intercept=True, + max_iter=1, average=True, shuffle=False) + + n_samples = X3.shape[0] + + clf.partial_fit(X3[:int(n_samples / 2)]) + clf.partial_fit(X3[int(n_samples / 2):]) + average_coef, average_offset = asgd_oneclass(klass, X3, eta, nu) + + assert_allclose(clf.coef_, average_coef) + assert_allclose(clf.offset_, average_offset) + + +def test_sgd_oneclass(): + # Test fit, decision_function, predict and score_samples on a toy + # dataset + X_train = np.array([[-2, -1], [-1, -1], [1, 1]]) + X_test = np.array([[0.5, -2], [2, 2]]) + clf = SGDOneClassSVM(nu=0.5, eta0=1, learning_rate='constant', + shuffle=False, max_iter=1) + clf.fit(X_train) + assert_allclose(clf.coef_, np.array([-0.125, 0.4375])) + assert clf.offset_[0] == -0.5 + + scores = clf.score_samples(X_test) + assert_allclose(scores, np.array([-0.9375, 0.625])) + + dec = clf.score_samples(X_test) - clf.offset_ + assert_allclose(clf.decision_function(X_test), dec) + + pred = clf.predict(X_test) + assert_array_equal(pred, np.array([-1, 1])) + + +def test_ocsvm_vs_sgdocsvm(): + # Checks SGDOneClass SVM gives a good approximation of kernelized + # One-Class SVM + nu = 0.05 + gamma = 2. + random_state = 42 + + # Generate train and test data + rng = np.random.RandomState(random_state) + X = 0.3 * rng.randn(500, 2) + X_train = np.r_[X + 2, X - 2] + X = 0.3 * rng.randn(100, 2) + X_test = np.r_[X + 2, X - 2] + + # One-Class SVM + clf = OneClassSVM(gamma=gamma, kernel='rbf', nu=nu) + clf.fit(X_train) + y_pred_ocsvm = clf.predict(X_test) + dec_ocsvm = clf.decision_function(X_test).reshape(1, -1) + + # SGDOneClassSVM using kernel approximation + max_iter = 15 + transform = Nystroem(gamma=gamma, random_state=random_state) + clf_sgd = SGDOneClassSVM(nu=nu, shuffle=True, fit_intercept=True, + max_iter=max_iter, random_state=random_state, + tol=-np.inf) + pipe_sgd = make_pipeline(transform, clf_sgd) + pipe_sgd.fit(X_train) + y_pred_sgdocsvm = pipe_sgd.predict(X_test) + dec_sgdocsvm = pipe_sgd.decision_function(X_test).reshape(1, -1) + + assert np.mean(y_pred_sgdocsvm == y_pred_ocsvm) >= 0.99 + corrcoef = np.corrcoef(np.concatenate((dec_ocsvm, dec_sgdocsvm)))[0, 1] + assert corrcoef >= 0.9 + + def test_l1_ratio(): # Test if l1 ratio extremes match L1 and L2 penalty settings. X, y = datasets.make_classification(n_samples=1000, @@ -1396,7 +1739,8 @@ def test_underflow_or_overlow(): msg_regxp = (r"Floating-point under-/overflow occurred at epoch #.*" " Scaling input data with StandardScaler or MinMaxScaler" " might help.") - assert_raises_regexp(ValueError, msg_regxp, model.fit, X, y) + with pytest.raises(ValueError, match=msg_regxp): + model.fit(X, y) def test_numerical_stability_large_gradient():
[ { "path": "doc/modules/classes.rst", "old_path": "a/doc/modules/classes.rst", "new_path": "b/doc/modules/classes.rst", "metadata": "diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst\nindex ceebfc337352a..45195dcedec64 100644\n--- a/doc/modules/classes.rst\n+++ b/doc/modules/classes.rst\n@@ -762,6 +762,7 @@ Linear classifiers\n linear_model.RidgeClassifier\n linear_model.RidgeClassifierCV\n linear_model.SGDClassifier\n+ linear_model.SGDOneClassSVM\n \n Classical linear regressors\n ---------------------------\n" }, { "path": "doc/modules/outlier_detection.rst", "old_path": "a/doc/modules/outlier_detection.rst", "new_path": "b/doc/modules/outlier_detection.rst", "metadata": "diff --git a/doc/modules/outlier_detection.rst b/doc/modules/outlier_detection.rst\nindex 5d2008f3c3f58..14495bc558dab 100644\n--- a/doc/modules/outlier_detection.rst\n+++ b/doc/modules/outlier_detection.rst\n@@ -110,9 +110,14 @@ does not perform very well for outlier detection. That being said, outlier\n detection in high-dimension, or without any assumptions on the distribution\n of the inlying data is very challenging. :class:`svm.OneClassSVM` may still\n be used with outlier detection but requires fine-tuning of its hyperparameter\n-`nu` to handle outliers and prevent overfitting. Finally,\n-:class:`covariance.EllipticEnvelope` assumes the data is Gaussian and learns\n-an ellipse. For more details on the different estimators refer to the example\n+`nu` to handle outliers and prevent overfitting.\n+:class:`linear_model.SGDOneClassSVM` provides an implementation of a\n+linear One-Class SVM with a linear complexity in the number of samples. This\n+implementation is here used with a kernel approximation technique to obtain\n+results similar to :class:`svm.OneClassSVM` which uses a Gaussian kernel\n+by default. Finally, :class:`covariance.EllipticEnvelope` assumes the data is\n+Gaussian and learns an ellipse. For more details on the different estimators\n+refer to the example\n :ref:`sphx_glr_auto_examples_miscellaneous_plot_anomaly_comparison.py` and the\n sections hereunder.\n \n@@ -173,6 +178,23 @@ but regular, observation outside the frontier.\n :scale: 75%\n \n \n+Scaling up the One-Class SVM\n+----------------------------\n+\n+An online linear version of the One-Class SVM is implemented in\n+:class:`linear_model.SGDOneClassSVM`. This implementation scales linearly with\n+the number of samples and can be used with a kernel approximation to\n+approximate the solution of a kernelized :class:`svm.OneClassSVM` whose\n+complexity is at best quadratic in the number of samples. See section\n+:ref:`sgd_online_one_class_svm` for more details.\n+\n+.. topic:: Examples:\n+\n+ * See :ref:`sphx_glr_auto_examples_linear_model_plot_sgdocsvm_vs_ocsvm.py`\n+ for an illustration of the approximation of a kernelized One-Class SVM\n+ with the `linear_model.SGDOneClassSVM` combined with kernel approximation.\n+\n+\n Outlier Detection\n =================\n \n@@ -278,8 +300,8 @@ allows you to add more trees to an already fitted model::\n for a comparison of :class:`ensemble.IsolationForest` with\n :class:`neighbors.LocalOutlierFactor`,\n :class:`svm.OneClassSVM` (tuned to perform like an outlier detection\n- method) and a covariance-based outlier detection with\n- :class:`covariance.EllipticEnvelope`.\n+ method), :class:`linear_model.SGDOneClassSVM`, and a covariance-based\n+ outlier detection with :class:`covariance.EllipticEnvelope`.\n \n .. topic:: References:\n \n" }, { "path": "doc/modules/sgd.rst", "old_path": "a/doc/modules/sgd.rst", "new_path": "b/doc/modules/sgd.rst", "metadata": "diff --git a/doc/modules/sgd.rst b/doc/modules/sgd.rst\nindex 1376947540e78..0a1d8407e64ae 100644\n--- a/doc/modules/sgd.rst\n+++ b/doc/modules/sgd.rst\n@@ -232,6 +232,58 @@ For regression with a squared loss and a l2 penalty, another variant of\n SGD with an averaging strategy is available with Stochastic Average\n Gradient (SAG) algorithm, available as a solver in :class:`Ridge`.\n \n+.. _sgd_online_one_class_svm:\n+\n+Online One-Class SVM\n+====================\n+\n+The class :class:`sklearn.linear_model.SGDOneClassSVM` implements an online\n+linear version of the One-Class SVM using a stochastic gradient descent.\n+Combined with kernel approximation techniques,\n+:class:`sklearn.linear_model.SGDOneClassSVM` can be used to approximate the\n+solution of a kernelized One-Class SVM, implemented in\n+:class:`sklearn.svm.OneClassSVM`, with a linear complexity in the number of\n+samples. Note that the complexity of a kernelized One-Class SVM is at best\n+quadratic in the number of samples.\n+:class:`sklearn.linear_model.SGDOneClassSVM` is thus well suited for datasets\n+with a large number of training samples (> 10,000) for which the SGD\n+variant can be several orders of magnitude faster.\n+\n+Its implementation is based on the implementation of the stochastic\n+gradient descent. Indeed, the original optimization problem of the One-Class\n+SVM is given by\n+\n+.. math::\n+\n+ \\begin{aligned}\n+ \\min_{w, \\rho, \\xi} & \\quad \\frac{1}{2}\\Vert w \\Vert^2 - \\rho + \\frac{1}{\\nu n} \\sum_{i=1}^n \\xi_i \\\\\n+ \\text{s.t.} & \\quad \\langle w, x_i \\rangle \\geq \\rho - \\xi_i \\quad 1 \\leq i \\leq n \\\\\n+ & \\quad \\xi_i \\geq 0 \\quad 1 \\leq i \\leq n\n+ \\end{aligned}\n+\n+where :math:`\\nu \\in (0, 1]` is the user-specified parameter controlling the\n+proportion of outliers and the proportion of support vectors. Getting rid of\n+the slack variables :math:`\\xi_i` this problem is equivalent to\n+\n+.. math::\n+\n+ \\min_{w, \\rho} \\frac{1}{2}\\Vert w \\Vert^2 - \\rho + \\frac{1}{\\nu n} \\sum_{i=1}^n \\max(0, \\rho - \\langle w, x_i \\rangle) \\, .\n+\n+Multiplying by the constant :math:`\\nu` and introducing the intercept\n+:math:`b = 1 - \\rho` we obtain the following equivalent optimization problem\n+\n+.. math::\n+\n+ \\min_{w, b} \\frac{\\nu}{2}\\Vert w \\Vert^2 + b\\nu + \\frac{1}{n} \\sum_{i=1}^n \\max(0, 1 - (\\langle w, x_i \\rangle + b)) \\, .\n+\n+This is similar to the optimization problems studied in section\n+:ref:`sgd_mathematical_formulation` with :math:`y_i = 1, 1 \\leq i \\leq n` and\n+:math:`\\alpha = \\nu/2`, :math:`L` being the hinge loss function and :math:`R`\n+being the L2 norm. We just need to add the term :math:`b\\nu` in the\n+optimization loop.\n+\n+As :class:`SGDClassifier` and :class:`SGDRegressor`, :class:`SGDOneClassSVM`\n+supports averaged SGD. Averaging can be enabled by setting ``average=True``.\n \n Stochastic Gradient Descent for sparse data\n ===========================================\n" }, { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 521e358ac2f02..c252f5df1074e 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -147,6 +147,13 @@ Changelog\n :mod:`sklearn.linear_model`\n ...........................\n \n+- |Feature| The new :class:`linear_model.SGDOneClassSVM` provides an SGD\n+ implementation of the linear One-Class SVM. Combined with kernel\n+ approximation techniques, this implementation approximates the solution of\n+ a kernelized One Class SVM while benefitting from a linear \n+ complexity in the number of samples.\n+ :pr:`10027` by :user:`Albert Thomas <albertcthomas>`.\n+\n - |Efficiency| The implementation of :class:`linear_model.LogisticRegression`\n has been optimised for dense matrices when using `solver='newton-cg'` and\n `multi_class!='multinomial'`.\n" } ]
1.00
81102146e35c81d7aab16d448f1c2b66d8a67ed9
[]
[ "sklearn/linear_model/tests/test_sgd.py::test_elasticnet_convergence[SGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_multi_thread_multi_class_and_early_stopping", "sklearn/linear_model/tests/test_sgd.py::test_warm_start[optimal-SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_equal_class_weight[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_bad_loss[SparseSGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_bad_nu_values[-0.5-SparseSGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_adaptive_longer_than_constant[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_early_stopping_with_partial_fit[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_predict_proba_method_access[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_partial_fit_exception[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_late_onset_averaging_not_reached[SparseSGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_huber_fit[SparseSGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_partial_fit[SparseSGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_n_iter_no_change[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_multiclass_njobs[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_averaged_partial_fit[SparseSGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_late_onset_averaging_not_reached[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_averaged_computed_correctly[SGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_loss_function_epsilon[SparseSGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_bad_alpha[SGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_adaptive_longer_than_constant[SparseSGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_partial_fit_oneclass[SparseSGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_late_onset_averaging_reached_oneclass[SparseSGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_large_regularization[elasticnet]", "sklearn/linear_model/tests/test_sgd.py::test_provide_coef[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_warm_start[optimal-SGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_early_stopping[SparseSGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_average_binary_computed_correctly[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_average_binary_computed_correctly[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_clf[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_deprecated_attr[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_clf[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_bad_penalty[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_multiclass_average[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_partial_fit_equal_fit_oneclass[optimal-SGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_warm_start[constant-SGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_wrong_sample_weights[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_argument_coef[SparseSGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_gradient_squared_hinge", "sklearn/linear_model/tests/test_sgd.py::test_plain_has_no_average_attr[SGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_bad_alpha_for_optimal_learning_rate[SGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_warm_start[invscaling-SparseSGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_average_sparse_oneclass[SGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_provide_coef[SparseSGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_bad_nu_values[-0.5-SGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_multi_core_gridsearch_and_early_stopping", "sklearn/linear_model/tests/test_sgd.py::test_provide_coef[SGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_fit_then_partial_fit[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_warm_start_oneclass[constant-SGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_tol_parameter", "sklearn/linear_model/tests/test_sgd.py::test_adaptive_longer_than_constant[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_late_onset_averaging_not_reached[SparseSGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_plain_has_no_average_attr[SGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_late_onset_averaging_reached_oneclass[SGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_l1[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_weights_multiplied[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_set_intercept_to_intercept[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_validation_set_not_used_for_training[SparseSGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_partial_fit_equal_fit_classif[adaptive-SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_partial_fit_equal_fit[invscaling-SparseSGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_averaged_computed_correctly_oneclass[SGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_bad_learning_rate_schedule[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_partial_fit_weight_class_balanced[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_bad_penalty[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_partial_fit_equal_fit_oneclass[adaptive-SGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_validation_set_not_used_for_training[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_validation_set_not_used_for_training[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_partial_fit_equal_fit[adaptive-SGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_partial_fit_multiclass_average[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_bad_alpha_for_optimal_learning_rate[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_bad_penalty[SGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_plain_has_no_average_attr[SparseSGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_late_onset_averaging_reached[SGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_not_enough_sample_for_early_stopping[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_equal_class_weight[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_n_iter_no_change[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_sample_weights[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_reg[SGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_n_iter_no_change[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_input_format[SparseSGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_reg[SparseSGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_warm_start_oneclass[constant-SparseSGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_wrong_class_weight_label[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_partial_fit_equal_fit[invscaling-SGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_multiclass_average[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_regression_losses[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_late_onset_averaging_reached[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_late_onset_averaging_not_reached[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_clone[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_partial_fit_equal_fit_classif[constant-SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_numerical_stability_large_gradient", "sklearn/linear_model/tests/test_sgd.py::test_sgd_bad_eta0[SGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_set_intercept_binary[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_multiclass[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_multiclass[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_warm_start[optimal-SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_bad_alpha[SparseSGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_partial_fit_weight_class_balanced[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_warm_start_oneclass[invscaling-SGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_partial_fit_equal_fit_oneclass[adaptive-SparseSGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_deprecated_attr[SGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_predict_proba_method_access[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_partial_fit_equal_fit[constant-SparseSGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_partial_fit_equal_fit_classif[invscaling-SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_early_stopping_with_partial_fit[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_wrong_class_weight_label[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_at_least_two_labels[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_set_coef_multiclass[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_plain_has_no_average_attr[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_bad_penalty[SparseSGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_n_iter_no_change[SparseSGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_partial_fit_multiclass[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_n_iter_no_change[SGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_loss_hinge", "sklearn/linear_model/tests/test_sgd.py::test_fit_then_partial_fit[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_least_squares_fit[SGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_warm_start_oneclass[optimal-SGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_clone_oneclass[SGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_loss_epsilon_insensitive", "sklearn/linear_model/tests/test_sgd.py::test_sgd_max_iter_param[SGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_huber_fit[SGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_input_format[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_bad_eta0[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_partial_fit_equal_fit_classif[constant-SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_partial_fit_multiclass_average[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_loss_squared_loss", "sklearn/linear_model/tests/test_sgd.py::test_warm_start_oneclass[adaptive-SGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_SGDClassifier_fit_for_all_backends[loky]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_bad_learning_rate_schedule[SparseSGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_partial_fit_equal_fit[constant-SGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_weights_multiplied[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_loss_function_epsilon[SGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_averaged_partial_fit_oneclass[SGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_epsilon_insensitive[SparseSGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_loss_huber", "sklearn/linear_model/tests/test_sgd.py::test_sgd_bad_loss[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_shuffle_param[SparseSGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_bad_nu_values[2-SparseSGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_partial_fit_oneclass[SGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_bad_alpha[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_bad_alpha_for_optimal_learning_rate[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_bad_nu_values[2-SGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_input_format[SGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_late_onset_averaging_not_reached[SGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_input_format[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_partial_fit[SGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_validation_set_not_used_for_training[SGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_multiple_fit[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_bad_alpha[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_warm_start_oneclass[adaptive-SparseSGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_provide_coef[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_multiclass_njobs[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_late_onset_averaging_not_reached[SGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_not_enough_sample_for_early_stopping[SGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_argument_coef[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_set_intercept_to_intercept[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_average_sparse[SGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_multiclass_with_init_coef[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_partial_fit_equal_fit_classif[optimal-SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_partial_fit_equal_fit_oneclass[invscaling-SGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_oneclass", "sklearn/linear_model/tests/test_sgd.py::test_sgd_max_iter_param[SparseSGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_clone_oneclass[SparseSGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_at_least_two_labels[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_balanced_weight[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_bad_alpha_for_optimal_learning_rate[SparseSGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_clone[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_bad_loss[SGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_warm_start[adaptive-SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_partial_fit_equal_fit_classif[optimal-SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_warm_start[adaptive-SparseSGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_loss_squared_loss_deprecated[SGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_set_intercept[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_SGDClassifier_fit_for_all_backends[threading]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_bad_eta0[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_proba[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_averaged_computed_correctly_oneclass[SparseSGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_loss_modified_huber", "sklearn/linear_model/tests/test_sgd.py::test_loss_squared_loss_deprecated[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_set_intercept[SparseSGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_large_regularization[l2]", "sklearn/linear_model/tests/test_sgd.py::test_class_weights[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_bad_learning_rate_schedule[SGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_late_onset_averaging_reached[SparseSGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_bad_loss[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_argument_coef[SGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_epsilon_insensitive[SGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_shuffle_param[SGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_early_stopping_param[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_not_enough_sample_for_early_stopping[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_balanced_weight[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_warm_start[optimal-SparseSGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_set_coef_multiclass[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_class_weights[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_partial_fit_binary[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_regression_losses[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_averaged_computed_correctly[SparseSGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_adaptive_longer_than_constant[SGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_proba[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_partial_fit_equal_fit_classif[invscaling-SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_validation_fraction[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_partial_fit_equal_fit_oneclass[constant-SGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_warm_start[adaptive-SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_early_stopping[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_set_intercept[SGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_wrong_sample_weights[SGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_not_enough_sample_for_early_stopping[SparseSGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_early_stopping_param[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_warm_start[constant-SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_partial_fit_equal_fit[adaptive-SparseSGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_clone[SGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_warm_start_oneclass[optimal-SparseSGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_ocsvm_vs_sgdocsvm", "sklearn/linear_model/tests/test_sgd.py::test_multiple_fit[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_partial_fit_equal_fit_oneclass[constant-SparseSGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_underflow_or_overlow", "sklearn/linear_model/tests/test_sgd.py::test_sgd_max_iter_param[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_bad_l1_ratio[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_argument_coef[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_multiclass_with_init_coef[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_partial_fit_exception[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_partial_fit_multiclass[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_l1[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_partial_fit_binary[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_loss_log", "sklearn/linear_model/tests/test_sgd.py::test_early_stopping[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_sample_weights[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_warm_start[adaptive-SGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_bad_eta0[SparseSGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_wrong_sample_weights[SparseSGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_loss_squared_epsilon_insensitive", "sklearn/linear_model/tests/test_sgd.py::test_partial_fit_equal_fit_classif[adaptive-SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_warm_start[constant-SparseSGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_validation_fraction[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_warm_start_multiclass[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_bad_learning_rate_schedule[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_plain_has_no_average_attr[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_warm_start_multiclass[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_average_sparse[SparseSGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_averaged_partial_fit[SGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_wrong_sample_weights[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_partial_fit_equal_fit[optimal-SGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_warm_start[invscaling-SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_plain_has_no_average_attr[SparseSGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_max_iter_param[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_shuffle_param[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_partial_fit_equal_fit[optimal-SparseSGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_partial_fit_equal_fit_oneclass[invscaling-SparseSGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_SGDClassifier_fit_for_all_backends[multiprocessing]", "sklearn/linear_model/tests/test_sgd.py::test_warm_start_oneclass[invscaling-SparseSGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_partial_fit_equal_fit_oneclass[optimal-SparseSGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_least_squares_fit[SparseSGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_warm_start[invscaling-SGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_bad_l1_ratio[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_warm_start[constant-SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_warm_start[invscaling-SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_set_intercept_binary[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_late_onset_averaging_reached[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_wrong_class_weight_format[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_wrong_class_weight_format[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_average_sparse_oneclass[SparseSGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_large_regularization[l1]", "sklearn/linear_model/tests/test_sgd.py::test_early_stopping[SGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_shuffle_param[SparseSGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_elasticnet_convergence[SparseSGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_l1_ratio", "sklearn/linear_model/tests/test_sgd.py::test_set_intercept[SGDClassifier]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_averaged_partial_fit_oneclass[SparseSGDOneClassSVM]", "sklearn/linear_model/tests/test_sgd.py::test_clone[SparseSGDRegressor]", "sklearn/linear_model/tests/test_sgd.py::test_sgd_n_iter_no_change[SGDClassifier]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [ { "type": "file", "name": "benchmarks/bench_online_ocsvm.py" }, { "type": "file", "name": "examples/linear_model/plot_sgdocsvm_vs_ocsvm.py" } ] }
[ { "path": "doc/modules/classes.rst", "old_path": "a/doc/modules/classes.rst", "new_path": "b/doc/modules/classes.rst", "metadata": "diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst\nindex ceebfc337352a..45195dcedec64 100644\n--- a/doc/modules/classes.rst\n+++ b/doc/modules/classes.rst\n@@ -762,6 +762,7 @@ Linear classifiers\n linear_model.RidgeClassifier\n linear_model.RidgeClassifierCV\n linear_model.SGDClassifier\n+ linear_model.SGDOneClassSVM\n \n Classical linear regressors\n ---------------------------\n" }, { "path": "doc/modules/outlier_detection.rst", "old_path": "a/doc/modules/outlier_detection.rst", "new_path": "b/doc/modules/outlier_detection.rst", "metadata": "diff --git a/doc/modules/outlier_detection.rst b/doc/modules/outlier_detection.rst\nindex 5d2008f3c3f58..14495bc558dab 100644\n--- a/doc/modules/outlier_detection.rst\n+++ b/doc/modules/outlier_detection.rst\n@@ -110,9 +110,14 @@ does not perform very well for outlier detection. That being said, outlier\n detection in high-dimension, or without any assumptions on the distribution\n of the inlying data is very challenging. :class:`svm.OneClassSVM` may still\n be used with outlier detection but requires fine-tuning of its hyperparameter\n-`nu` to handle outliers and prevent overfitting. Finally,\n-:class:`covariance.EllipticEnvelope` assumes the data is Gaussian and learns\n-an ellipse. For more details on the different estimators refer to the example\n+`nu` to handle outliers and prevent overfitting.\n+:class:`linear_model.SGDOneClassSVM` provides an implementation of a\n+linear One-Class SVM with a linear complexity in the number of samples. This\n+implementation is here used with a kernel approximation technique to obtain\n+results similar to :class:`svm.OneClassSVM` which uses a Gaussian kernel\n+by default. Finally, :class:`covariance.EllipticEnvelope` assumes the data is\n+Gaussian and learns an ellipse. For more details on the different estimators\n+refer to the example\n :ref:`sphx_glr_auto_examples_miscellaneous_plot_anomaly_comparison.py` and the\n sections hereunder.\n \n@@ -173,6 +178,23 @@ but regular, observation outside the frontier.\n :scale: 75%\n \n \n+Scaling up the One-Class SVM\n+----------------------------\n+\n+An online linear version of the One-Class SVM is implemented in\n+:class:`linear_model.SGDOneClassSVM`. This implementation scales linearly with\n+the number of samples and can be used with a kernel approximation to\n+approximate the solution of a kernelized :class:`svm.OneClassSVM` whose\n+complexity is at best quadratic in the number of samples. See section\n+:ref:`sgd_online_one_class_svm` for more details.\n+\n+.. topic:: Examples:\n+\n+ * See :ref:`sphx_glr_auto_examples_linear_model_plot_sgdocsvm_vs_ocsvm.py`\n+ for an illustration of the approximation of a kernelized One-Class SVM\n+ with the `linear_model.SGDOneClassSVM` combined with kernel approximation.\n+\n+\n Outlier Detection\n =================\n \n@@ -278,8 +300,8 @@ allows you to add more trees to an already fitted model::\n for a comparison of :class:`ensemble.IsolationForest` with\n :class:`neighbors.LocalOutlierFactor`,\n :class:`svm.OneClassSVM` (tuned to perform like an outlier detection\n- method) and a covariance-based outlier detection with\n- :class:`covariance.EllipticEnvelope`.\n+ method), :class:`linear_model.SGDOneClassSVM`, and a covariance-based\n+ outlier detection with :class:`covariance.EllipticEnvelope`.\n \n .. topic:: References:\n \n" }, { "path": "doc/modules/sgd.rst", "old_path": "a/doc/modules/sgd.rst", "new_path": "b/doc/modules/sgd.rst", "metadata": "diff --git a/doc/modules/sgd.rst b/doc/modules/sgd.rst\nindex 1376947540e78..0a1d8407e64ae 100644\n--- a/doc/modules/sgd.rst\n+++ b/doc/modules/sgd.rst\n@@ -232,6 +232,58 @@ For regression with a squared loss and a l2 penalty, another variant of\n SGD with an averaging strategy is available with Stochastic Average\n Gradient (SAG) algorithm, available as a solver in :class:`Ridge`.\n \n+.. _sgd_online_one_class_svm:\n+\n+Online One-Class SVM\n+====================\n+\n+The class :class:`sklearn.linear_model.SGDOneClassSVM` implements an online\n+linear version of the One-Class SVM using a stochastic gradient descent.\n+Combined with kernel approximation techniques,\n+:class:`sklearn.linear_model.SGDOneClassSVM` can be used to approximate the\n+solution of a kernelized One-Class SVM, implemented in\n+:class:`sklearn.svm.OneClassSVM`, with a linear complexity in the number of\n+samples. Note that the complexity of a kernelized One-Class SVM is at best\n+quadratic in the number of samples.\n+:class:`sklearn.linear_model.SGDOneClassSVM` is thus well suited for datasets\n+with a large number of training samples (> 10,000) for which the SGD\n+variant can be several orders of magnitude faster.\n+\n+Its implementation is based on the implementation of the stochastic\n+gradient descent. Indeed, the original optimization problem of the One-Class\n+SVM is given by\n+\n+.. math::\n+\n+ \\begin{aligned}\n+ \\min_{w, \\rho, \\xi} & \\quad \\frac{1}{2}\\Vert w \\Vert^2 - \\rho + \\frac{1}{\\nu n} \\sum_{i=1}^n \\xi_i \\\\\n+ \\text{s.t.} & \\quad \\langle w, x_i \\rangle \\geq \\rho - \\xi_i \\quad 1 \\leq i \\leq n \\\\\n+ & \\quad \\xi_i \\geq 0 \\quad 1 \\leq i \\leq n\n+ \\end{aligned}\n+\n+where :math:`\\nu \\in (0, 1]` is the user-specified parameter controlling the\n+proportion of outliers and the proportion of support vectors. Getting rid of\n+the slack variables :math:`\\xi_i` this problem is equivalent to\n+\n+.. math::\n+\n+ \\min_{w, \\rho} \\frac{1}{2}\\Vert w \\Vert^2 - \\rho + \\frac{1}{\\nu n} \\sum_{i=1}^n \\max(0, \\rho - \\langle w, x_i \\rangle) \\, .\n+\n+Multiplying by the constant :math:`\\nu` and introducing the intercept\n+:math:`b = 1 - \\rho` we obtain the following equivalent optimization problem\n+\n+.. math::\n+\n+ \\min_{w, b} \\frac{\\nu}{2}\\Vert w \\Vert^2 + b\\nu + \\frac{1}{n} \\sum_{i=1}^n \\max(0, 1 - (\\langle w, x_i \\rangle + b)) \\, .\n+\n+This is similar to the optimization problems studied in section\n+:ref:`sgd_mathematical_formulation` with :math:`y_i = 1, 1 \\leq i \\leq n` and\n+:math:`\\alpha = \\nu/2`, :math:`L` being the hinge loss function and :math:`R`\n+being the L2 norm. We just need to add the term :math:`b\\nu` in the\n+optimization loop.\n+\n+As :class:`SGDClassifier` and :class:`SGDRegressor`, :class:`SGDOneClassSVM`\n+supports averaged SGD. Averaging can be enabled by setting ``average=True``.\n \n Stochastic Gradient Descent for sparse data\n ===========================================\n" }, { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 521e358ac2f02..c252f5df1074e 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -147,6 +147,13 @@ Changelog\n :mod:`sklearn.linear_model`\n ...........................\n \n+- |Feature| The new :class:`linear_model.SGDOneClassSVM` provides an SGD\n+ implementation of the linear One-Class SVM. Combined with kernel\n+ approximation techniques, this implementation approximates the solution of\n+ a kernelized One Class SVM while benefitting from a linear \n+ complexity in the number of samples.\n+ :pr:`<PRID>` by :user:`<NAME>`.\n+\n - |Efficiency| The implementation of :class:`linear_model.LogisticRegression`\n has been optimised for dense matrices when using `solver='newton-cg'` and\n `multi_class!='multinomial'`.\n" } ]
diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst index ceebfc337352a..45195dcedec64 100644 --- a/doc/modules/classes.rst +++ b/doc/modules/classes.rst @@ -762,6 +762,7 @@ Linear classifiers linear_model.RidgeClassifier linear_model.RidgeClassifierCV linear_model.SGDClassifier + linear_model.SGDOneClassSVM Classical linear regressors --------------------------- diff --git a/doc/modules/outlier_detection.rst b/doc/modules/outlier_detection.rst index 5d2008f3c3f58..14495bc558dab 100644 --- a/doc/modules/outlier_detection.rst +++ b/doc/modules/outlier_detection.rst @@ -110,9 +110,14 @@ does not perform very well for outlier detection. That being said, outlier detection in high-dimension, or without any assumptions on the distribution of the inlying data is very challenging. :class:`svm.OneClassSVM` may still be used with outlier detection but requires fine-tuning of its hyperparameter -`nu` to handle outliers and prevent overfitting. Finally, -:class:`covariance.EllipticEnvelope` assumes the data is Gaussian and learns -an ellipse. For more details on the different estimators refer to the example +`nu` to handle outliers and prevent overfitting. +:class:`linear_model.SGDOneClassSVM` provides an implementation of a +linear One-Class SVM with a linear complexity in the number of samples. This +implementation is here used with a kernel approximation technique to obtain +results similar to :class:`svm.OneClassSVM` which uses a Gaussian kernel +by default. Finally, :class:`covariance.EllipticEnvelope` assumes the data is +Gaussian and learns an ellipse. For more details on the different estimators +refer to the example :ref:`sphx_glr_auto_examples_miscellaneous_plot_anomaly_comparison.py` and the sections hereunder. @@ -173,6 +178,23 @@ but regular, observation outside the frontier. :scale: 75% +Scaling up the One-Class SVM +---------------------------- + +An online linear version of the One-Class SVM is implemented in +:class:`linear_model.SGDOneClassSVM`. This implementation scales linearly with +the number of samples and can be used with a kernel approximation to +approximate the solution of a kernelized :class:`svm.OneClassSVM` whose +complexity is at best quadratic in the number of samples. See section +:ref:`sgd_online_one_class_svm` for more details. + +.. topic:: Examples: + + * See :ref:`sphx_glr_auto_examples_linear_model_plot_sgdocsvm_vs_ocsvm.py` + for an illustration of the approximation of a kernelized One-Class SVM + with the `linear_model.SGDOneClassSVM` combined with kernel approximation. + + Outlier Detection ================= @@ -278,8 +300,8 @@ allows you to add more trees to an already fitted model:: for a comparison of :class:`ensemble.IsolationForest` with :class:`neighbors.LocalOutlierFactor`, :class:`svm.OneClassSVM` (tuned to perform like an outlier detection - method) and a covariance-based outlier detection with - :class:`covariance.EllipticEnvelope`. + method), :class:`linear_model.SGDOneClassSVM`, and a covariance-based + outlier detection with :class:`covariance.EllipticEnvelope`. .. topic:: References: diff --git a/doc/modules/sgd.rst b/doc/modules/sgd.rst index 1376947540e78..0a1d8407e64ae 100644 --- a/doc/modules/sgd.rst +++ b/doc/modules/sgd.rst @@ -232,6 +232,58 @@ For regression with a squared loss and a l2 penalty, another variant of SGD with an averaging strategy is available with Stochastic Average Gradient (SAG) algorithm, available as a solver in :class:`Ridge`. +.. _sgd_online_one_class_svm: + +Online One-Class SVM +==================== + +The class :class:`sklearn.linear_model.SGDOneClassSVM` implements an online +linear version of the One-Class SVM using a stochastic gradient descent. +Combined with kernel approximation techniques, +:class:`sklearn.linear_model.SGDOneClassSVM` can be used to approximate the +solution of a kernelized One-Class SVM, implemented in +:class:`sklearn.svm.OneClassSVM`, with a linear complexity in the number of +samples. Note that the complexity of a kernelized One-Class SVM is at best +quadratic in the number of samples. +:class:`sklearn.linear_model.SGDOneClassSVM` is thus well suited for datasets +with a large number of training samples (> 10,000) for which the SGD +variant can be several orders of magnitude faster. + +Its implementation is based on the implementation of the stochastic +gradient descent. Indeed, the original optimization problem of the One-Class +SVM is given by + +.. math:: + + \begin{aligned} + \min_{w, \rho, \xi} & \quad \frac{1}{2}\Vert w \Vert^2 - \rho + \frac{1}{\nu n} \sum_{i=1}^n \xi_i \\ + \text{s.t.} & \quad \langle w, x_i \rangle \geq \rho - \xi_i \quad 1 \leq i \leq n \\ + & \quad \xi_i \geq 0 \quad 1 \leq i \leq n + \end{aligned} + +where :math:`\nu \in (0, 1]` is the user-specified parameter controlling the +proportion of outliers and the proportion of support vectors. Getting rid of +the slack variables :math:`\xi_i` this problem is equivalent to + +.. math:: + + \min_{w, \rho} \frac{1}{2}\Vert w \Vert^2 - \rho + \frac{1}{\nu n} \sum_{i=1}^n \max(0, \rho - \langle w, x_i \rangle) \, . + +Multiplying by the constant :math:`\nu` and introducing the intercept +:math:`b = 1 - \rho` we obtain the following equivalent optimization problem + +.. math:: + + \min_{w, b} \frac{\nu}{2}\Vert w \Vert^2 + b\nu + \frac{1}{n} \sum_{i=1}^n \max(0, 1 - (\langle w, x_i \rangle + b)) \, . + +This is similar to the optimization problems studied in section +:ref:`sgd_mathematical_formulation` with :math:`y_i = 1, 1 \leq i \leq n` and +:math:`\alpha = \nu/2`, :math:`L` being the hinge loss function and :math:`R` +being the L2 norm. We just need to add the term :math:`b\nu` in the +optimization loop. + +As :class:`SGDClassifier` and :class:`SGDRegressor`, :class:`SGDOneClassSVM` +supports averaged SGD. Averaging can be enabled by setting ``average=True``. Stochastic Gradient Descent for sparse data =========================================== diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index 521e358ac2f02..c252f5df1074e 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -147,6 +147,13 @@ Changelog :mod:`sklearn.linear_model` ........................... +- |Feature| The new :class:`linear_model.SGDOneClassSVM` provides an SGD + implementation of the linear One-Class SVM. Combined with kernel + approximation techniques, this implementation approximates the solution of + a kernelized One Class SVM while benefitting from a linear + complexity in the number of samples. + :pr:`<PRID>` by :user:`<NAME>`. + - |Efficiency| The implementation of :class:`linear_model.LogisticRegression` has been optimised for dense matrices when using `solver='newton-cg'` and `multi_class!='multinomial'`. If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names: [{'type': 'file', 'name': 'benchmarks/bench_online_ocsvm.py'}, {'type': 'file', 'name': 'examples/linear_model/plot_sgdocsvm_vs_ocsvm.py'}]
scikit-learn/scikit-learn
scikit-learn__scikit-learn-21330
https://github.com/scikit-learn/scikit-learn/pull/21330
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 542636b1642f7..208c950c6e43d 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -162,6 +162,15 @@ Changelog ndarray with `np.nan` when passed a `Float32` or `Float64` pandas extension array with `pd.NA`. :pr:`21278` by `Thomas Fan`_. +:mod:`sklearn.random_projection` +................................ + +- |API| Adds :term:`get_feature_names_out` to all transformers in the + :mod:`~sklearn.random_projection` module: + :class:`~sklearn.random_projection.GaussianRandomProjection` and + :class:`~sklearn.random_projection.SparseRandomProjection`. :pr:`21330` by + :user:`Loïc Estève <lesteve>`. + Code and Documentation Contributors ----------------------------------- diff --git a/sklearn/random_projection.py b/sklearn/random_projection.py index 6b2c9217713e0..3ddbecb677710 100644 --- a/sklearn/random_projection.py +++ b/sklearn/random_projection.py @@ -34,6 +34,7 @@ import scipy.sparse as sp from .base import BaseEstimator, TransformerMixin +from .base import _ClassNamePrefixFeaturesOutMixin from .utils import check_random_state from .utils.extmath import safe_sparse_dot @@ -290,7 +291,9 @@ def _sparse_random_matrix(n_components, n_features, density="auto", random_state return np.sqrt(1 / density) / np.sqrt(n_components) * components -class BaseRandomProjection(TransformerMixin, BaseEstimator, metaclass=ABCMeta): +class BaseRandomProjection( + TransformerMixin, BaseEstimator, _ClassNamePrefixFeaturesOutMixin, metaclass=ABCMeta +): """Base class for random projections. Warning: This class should not be used directly. @@ -420,6 +423,14 @@ def transform(self, X): X_new = safe_sparse_dot(X, self.components_.T, dense_output=self.dense_output) return X_new + @property + def _n_features_out(self): + """Number of transformed output features. + + Used by _ClassNamePrefixFeaturesOutMixin.get_feature_names_out. + """ + return self.n_components + class GaussianRandomProjection(BaseRandomProjection): """Reduce dimensionality through Gaussian random projection.
diff --git a/sklearn/tests/test_common.py b/sklearn/tests/test_common.py index a476ba7dc8da5..c3eade24be412 100644 --- a/sklearn/tests/test_common.py +++ b/sklearn/tests/test_common.py @@ -371,7 +371,6 @@ def test_pandas_column_name_consistency(estimator): "manifold", "neighbors", "neural_network", - "random_projection", ] diff --git a/sklearn/tests/test_random_projection.py b/sklearn/tests/test_random_projection.py index 5866fde29d73b..1e894d906a3ad 100644 --- a/sklearn/tests/test_random_projection.py +++ b/sklearn/tests/test_random_projection.py @@ -24,7 +24,7 @@ all_SparseRandomProjection: List[Any] = [SparseRandomProjection] all_DenseRandomProjection: List[Any] = [GaussianRandomProjection] -all_RandomProjection = set(all_SparseRandomProjection + all_DenseRandomProjection) +all_RandomProjection = all_SparseRandomProjection + all_DenseRandomProjection # Make some random data with uniformly located non zero entries with @@ -359,3 +359,17 @@ def test_johnson_lindenstrauss_min_dim(): Regression test for #17111: before #19374, 32-bit systems would fail. """ assert johnson_lindenstrauss_min_dim(100, eps=1e-5) == 368416070986 + + [email protected]("random_projection_cls", all_RandomProjection) +def test_random_projection_feature_names_out(random_projection_cls): + random_projection = random_projection_cls(n_components=2) + random_projection.fit(data) + names_out = random_projection.get_feature_names_out() + class_name_lower = random_projection_cls.__name__.lower() + expected_names_out = np.array( + [f"{class_name_lower}{i}" for i in range(random_projection.n_components_)], + dtype=object, + ) + + assert_array_equal(names_out, expected_names_out)
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 542636b1642f7..208c950c6e43d 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -162,6 +162,15 @@ Changelog\n ndarray with `np.nan` when passed a `Float32` or `Float64` pandas extension\n array with `pd.NA`. :pr:`21278` by `Thomas Fan`_.\n \n+:mod:`sklearn.random_projection`\n+................................\n+\n+- |API| Adds :term:`get_feature_names_out` to all transformers in the\n+ :mod:`~sklearn.random_projection` module:\n+ :class:`~sklearn.random_projection.GaussianRandomProjection` and\n+ :class:`~sklearn.random_projection.SparseRandomProjection`. :pr:`21330` by\n+ :user:`Loïc Estève <lesteve>`.\n+\n Code and Documentation Contributors\n -----------------------------------\n \n" } ]
1.01
8cfbc38ab8864b68f9a504f96857bb2e527c9bbb
[ "sklearn/tests/test_random_projection.py::test_johnson_lindenstrauss_min_dim", "sklearn/tests/test_random_projection.py::test_sparse_random_projection_transformer_invalid_density[0]", "sklearn/tests/test_random_projection.py::test_sparse_random_projection_transformer_invalid_density[1.1]", "sklearn/tests/test_random_projection.py::test_invalid_jl_domain[0-0.5]", "sklearn/tests/test_random_projection.py::test_basic_property_of_random_matrix[_gaussian_random_matrix]", "sklearn/tests/test_random_projection.py::test_try_to_transform_before_fit", "sklearn/tests/test_random_projection.py::test_random_projection_transformer_invalid_input[-10-fit_data1]", "sklearn/tests/test_random_projection.py::test_warning_n_components_greater_than_n_features", "sklearn/tests/test_random_projection.py::test_invalid_jl_domain[100-1.1]", "sklearn/tests/test_random_projection.py::test_invalid_jl_domain[100--0.1]", "sklearn/tests/test_random_projection.py::test_basic_property_of_sparse_random_matrix[_sparse_random_matrix]", "sklearn/tests/test_random_projection.py::test_input_size_jl_min_dim", "sklearn/tests/test_random_projection.py::test_works_with_sparse_data", "sklearn/tests/test_random_projection.py::test_random_projection_embedding_quality", "sklearn/tests/test_random_projection.py::test_random_projection_transformer_invalid_input[auto-fit_data0]", "sklearn/tests/test_random_projection.py::test_sparse_random_matrix", "sklearn/tests/test_random_projection.py::test_SparseRandomProj_output_representation", "sklearn/tests/test_random_projection.py::test_sparse_random_projection_transformer_invalid_density[-0.1]", "sklearn/tests/test_random_projection.py::test_gaussian_random_matrix", "sklearn/tests/test_random_projection.py::test_basic_property_of_random_matrix[_sparse_random_matrix]", "sklearn/tests/test_random_projection.py::test_invalid_jl_domain[100-0.0]", "sklearn/tests/test_random_projection.py::test_too_many_samples_to_find_a_safe_embedding", "sklearn/tests/test_random_projection.py::test_correct_RandomProjection_dimensions_embedding" ]
[ "sklearn/tests/test_random_projection.py::test_random_projection_feature_names_out[GaussianRandomProjection]", "sklearn/tests/test_random_projection.py::test_random_projection_feature_names_out[SparseRandomProjection]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 542636b1642f7..208c950c6e43d 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -162,6 +162,15 @@ Changelog\n ndarray with `np.nan` when passed a `Float32` or `Float64` pandas extension\n array with `pd.NA`. :pr:`<PRID>` by `<NAME>`_.\n \n+:mod:`sklearn.random_projection`\n+................................\n+\n+- |API| Adds :term:`get_feature_names_out` to all transformers in the\n+ :mod:`~sklearn.random_projection` module:\n+ :class:`~sklearn.random_projection.GaussianRandomProjection` and\n+ :class:`~sklearn.random_projection.SparseRandomProjection`. :pr:`<PRID>` by\n+ :user:`<NAME>`.\n+\n Code and Documentation Contributors\n -----------------------------------\n \n" } ]
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 542636b1642f7..208c950c6e43d 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -162,6 +162,15 @@ Changelog ndarray with `np.nan` when passed a `Float32` or `Float64` pandas extension array with `pd.NA`. :pr:`<PRID>` by `<NAME>`_. +:mod:`sklearn.random_projection` +................................ + +- |API| Adds :term:`get_feature_names_out` to all transformers in the + :mod:`~sklearn.random_projection` module: + :class:`~sklearn.random_projection.GaussianRandomProjection` and + :class:`~sklearn.random_projection.SparseRandomProjection`. :pr:`<PRID>` by + :user:`<NAME>`. + Code and Documentation Contributors -----------------------------------
scikit-learn/scikit-learn
scikit-learn__scikit-learn-22218
https://github.com/scikit-learn/scikit-learn/pull/22218
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 39f8e405ebf7c..2b53301c40b99 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -617,6 +617,9 @@ Changelog left corner of the HTML representation to show how the elements are clickable. :pr:`21298` by `Thomas Fan`_. +- |Enhancement| :func:`utils.validation.check_scalar` now has better messages + when displaying the type. :pr:`22218` by `Thomas Fan`_. + - |Fix| :func:`check_scalar` raises an error when `include_boundaries={"left", "right"}` and the boundaries are not set. :pr:`22027` by `Marie Lanternier <mlant>`. diff --git a/sklearn/utils/validation.py b/sklearn/utils/validation.py index 8f0459b0d8760..cf2265d5b21cd 100644 --- a/sklearn/utils/validation.py +++ b/sklearn/utils/validation.py @@ -1406,8 +1406,29 @@ def check_scalar( If `min_val`, `max_val` and `include_boundaries` are inconsistent. """ + def type_name(t): + """Convert type into humman readable string.""" + module = t.__module__ + qualname = t.__qualname__ + if module == "builtins": + return qualname + elif t == numbers.Real: + return "float" + elif t == numbers.Integral: + return "int" + return f"{module}.{qualname}" + if not isinstance(x, target_type): - raise TypeError(f"{name} must be an instance of {target_type}, not {type(x)}.") + if isinstance(target_type, tuple): + types_str = ", ".join(type_name(t) for t in target_type) + target_type_str = f"{{{types_str}}}" + else: + target_type_str = type_name(target_type) + + raise TypeError( + f"{name} must be an instance of {target_type_str}, not" + f" {type(x).__qualname__}." + ) expected_include_boundaries = ("left", "right", "both", "neither") if include_boundaries not in expected_include_boundaries:
diff --git a/sklearn/cluster/tests/test_birch.py b/sklearn/cluster/tests/test_birch.py index 4e64524e2cb11..e0051704653ae 100644 --- a/sklearn/cluster/tests/test_birch.py +++ b/sklearn/cluster/tests/test_birch.py @@ -195,16 +195,14 @@ def test_birch_fit_attributes_deprecated(attribute): ( {"branching_factor": 1.5}, TypeError, - "branching_factor must be an instance of <class 'numbers.Integral'>, not" - " <class 'float'>.", + "branching_factor must be an instance of int, not float.", ), ({"branching_factor": -2}, ValueError, "branching_factor == -2, must be > 1."), ({"n_clusters": 0}, ValueError, "n_clusters == 0, must be >= 1."), ( {"n_clusters": 2.5}, TypeError, - "n_clusters must be an instance of <class 'numbers.Integral'>, not <class" - " 'float'>.", + "n_clusters must be an instance of int, not float.", ), ( {"n_clusters": "whatever"}, diff --git a/sklearn/cluster/tests/test_dbscan.py b/sklearn/cluster/tests/test_dbscan.py index 08ca937d3e25f..b3b58b7a79b4b 100644 --- a/sklearn/cluster/tests/test_dbscan.py +++ b/sklearn/cluster/tests/test_dbscan.py @@ -436,24 +436,21 @@ def test_dbscan_precomputed_metric_with_initial_rows_zero(): ( {"min_samples": 1.5}, TypeError, - "min_samples must be an instance of <class 'numbers.Integral'>, not <class" - " 'float'>.", + "min_samples must be an instance of int, not float.", ), ({"min_samples": -2}, ValueError, "min_samples == -2, must be >= 1."), ({"leaf_size": 0}, ValueError, "leaf_size == 0, must be >= 1."), ( {"leaf_size": 2.5}, TypeError, - "leaf_size must be an instance of <class 'numbers.Integral'>, not <class" - " 'float'>.", + "leaf_size must be an instance of int, not float.", ), ({"leaf_size": -3}, ValueError, "leaf_size == -3, must be >= 1."), ({"p": -2}, ValueError, "p == -2, must be >= 0.0."), ( {"n_jobs": 2.5}, TypeError, - "n_jobs must be an instance of <class 'numbers.Integral'>, not <class" - " 'float'>.", + "n_jobs must be an instance of int, not float.", ), ], ) diff --git a/sklearn/cluster/tests/test_spectral.py b/sklearn/cluster/tests/test_spectral.py index 8ea26b36de2d7..c3249b1917582 100644 --- a/sklearn/cluster/tests/test_spectral.py +++ b/sklearn/cluster/tests/test_spectral.py @@ -121,8 +121,7 @@ def test_spectral_unknown_assign_labels(): X, {"n_clusters": 1.5}, TypeError, - "n_clusters must be an instance of <class 'numbers.Integral'>," - " not <class 'float'>", + "n_clusters must be an instance of int, not float", ), (X, {"n_init": -1}, ValueError, "n_init == -1, must be >= 1"), (X, {"n_init": 0}, ValueError, "n_init == 0, must be >= 1"), @@ -130,8 +129,7 @@ def test_spectral_unknown_assign_labels(): X, {"n_init": 1.5}, TypeError, - "n_init must be an instance of <class 'numbers.Integral'>," - " not <class 'float'>", + "n_init must be an instance of int, not float", ), (X, {"gamma": -1}, ValueError, "gamma == -1, must be >= 1"), (X, {"gamma": 0}, ValueError, "gamma == 0, must be >= 1"), diff --git a/sklearn/cross_decomposition/tests/test_pls.py b/sklearn/cross_decomposition/tests/test_pls.py index 1118e8c33a9c0..7e704ced0f2af 100644 --- a/sklearn/cross_decomposition/tests/test_pls.py +++ b/sklearn/cross_decomposition/tests/test_pls.py @@ -476,7 +476,7 @@ def test_scale_and_stability(Est, X, Y): ( 2.0, TypeError, - "n_components must be an instance of <class 'numbers.Integral'>", + "n_components must be an instance of int", ), ], ) @@ -498,7 +498,7 @@ def test_n_components_bounds(Est, n_components, err_type, err_msg): ( 2.0, TypeError, - "n_components must be an instance of <class 'numbers.Integral'>", + "n_components must be an instance of int", ), ], ) diff --git a/sklearn/decomposition/tests/test_pca.py b/sklearn/decomposition/tests/test_pca.py index 83b8b166597a6..1715bcefe96e8 100644 --- a/sklearn/decomposition/tests/test_pca.py +++ b/sklearn/decomposition/tests/test_pca.py @@ -702,7 +702,7 @@ def test_pca_randomized_svd_n_oversamples(): ( {"n_oversamples": 1.5}, TypeError, - "n_oversamples must be an instance of <class 'numbers.Integral'>", + "n_oversamples must be an instance of int", ), ], ) diff --git a/sklearn/ensemble/tests/test_gradient_boosting.py b/sklearn/ensemble/tests/test_gradient_boosting.py index 88e77751c2013..f18893b5d5744 100644 --- a/sklearn/ensemble/tests/test_gradient_boosting.py +++ b/sklearn/ensemble/tests/test_gradient_boosting.py @@ -84,13 +84,13 @@ def test_classification_toy(loss): ( {"learning_rate": "foo"}, TypeError, - "learning_rate must be an instance of <class 'numbers.Real'>", + "learning_rate must be an instance of float", ), ({"n_estimators": 0}, ValueError, "n_estimators == 0, must be >= 1"), ( {"n_estimators": 1.5}, TypeError, - "n_estimators must be an instance of <class 'numbers.Integral'>,", + "n_estimators must be an instance of int,", ), ({"loss": "foobar"}, ValueError, "Loss 'foobar' not supported"), ({"subsample": 0.0}, ValueError, "subsample == 0.0, must be > 0.0"), @@ -98,7 +98,7 @@ def test_classification_toy(loss): ( {"subsample": "foo"}, TypeError, - "subsample must be an instance of <class 'numbers.Real'>", + "subsample must be an instance of float", ), ({"init": {}}, ValueError, "The init parameter must be an estimator or 'zero'"), ({"max_features": 0}, ValueError, "max_features == 0, must be >= 1"), @@ -125,19 +125,19 @@ def test_classification_toy(loss): ( {"validation_fraction": "foo"}, TypeError, - "validation_fraction must be an instance of <class 'numbers.Real'>", + "validation_fraction must be an instance of float", ), ({"n_iter_no_change": 0}, ValueError, "n_iter_no_change == 0, must be >= 1"), ( {"n_iter_no_change": 1.5}, TypeError, - "n_iter_no_change must be an instance of <class 'numbers.Integral'>,", + "n_iter_no_change must be an instance of int,", ), ({"tol": 0.0}, ValueError, "tol == 0.0, must be > 0.0"), ( {"tol": "foo"}, TypeError, - "tol must be an instance of <class 'numbers.Real'>,", + "tol must be an instance of float,", ), # The following parameters are checked in BaseDecisionTree ({"min_samples_leaf": 0}, ValueError, "min_samples_leaf == 0, must be >= 1"), @@ -145,7 +145,7 @@ def test_classification_toy(loss): ( {"min_samples_leaf": "foo"}, TypeError, - "min_samples_leaf must be an instance of <class 'numbers.Real'>", + "min_samples_leaf must be an instance of float", ), ({"min_samples_split": 1}, ValueError, "min_samples_split == 1, must be >= 2"), ( @@ -161,7 +161,7 @@ def test_classification_toy(loss): ( {"min_samples_split": "foo"}, TypeError, - "min_samples_split must be an instance of <class 'numbers.Real'>", + "min_samples_split must be an instance of float", ), ( {"min_weight_fraction_leaf": -1}, @@ -176,19 +176,19 @@ def test_classification_toy(loss): ( {"min_weight_fraction_leaf": "foo"}, TypeError, - "min_weight_fraction_leaf must be an instance of <class 'numbers.Real'>", + "min_weight_fraction_leaf must be an instance of float", ), ({"max_leaf_nodes": 0}, ValueError, "max_leaf_nodes == 0, must be >= 2"), ( {"max_leaf_nodes": 1.5}, TypeError, - "max_leaf_nodes must be an instance of <class 'numbers.Integral'>", + "max_leaf_nodes must be an instance of int", ), ({"max_depth": -1}, ValueError, "max_depth == -1, must be >= 1"), ( {"max_depth": 1.1}, TypeError, - "max_depth must be an instance of <class 'numbers.Integral'>", + "max_depth must be an instance of int", ), ( {"min_impurity_decrease": -1}, @@ -198,13 +198,13 @@ def test_classification_toy(loss): ( {"min_impurity_decrease": "foo"}, TypeError, - "min_impurity_decrease must be an instance of <class 'numbers.Real'>", + "min_impurity_decrease must be an instance of float", ), ({"ccp_alpha": -1.0}, ValueError, "ccp_alpha == -1.0, must be >= 0.0"), ( {"ccp_alpha": "foo"}, TypeError, - "ccp_alpha must be an instance of <class 'numbers.Real'>", + "ccp_alpha must be an instance of float", ), ({"criterion": "mae"}, ValueError, "criterion='mae' is not supported."), ], diff --git a/sklearn/ensemble/tests/test_weight_boosting.py b/sklearn/ensemble/tests/test_weight_boosting.py index 5027dbd02c859..0348641d39453 100755 --- a/sklearn/ensemble/tests/test_weight_boosting.py +++ b/sklearn/ensemble/tests/test_weight_boosting.py @@ -564,8 +564,7 @@ def test_adaboostregressor_sample_weight(): ( {"n_estimators": 1.5}, TypeError, - "n_estimators must be an instance of <class 'numbers.Integral'>," - " not <class 'float'>", + "n_estimators must be an instance of int, not float", ), ({"learning_rate": -1}, ValueError, "learning_rate == -1, must be > 0."), ({"learning_rate": 0}, ValueError, "learning_rate == 0, must be > 0."), diff --git a/sklearn/feature_extraction/tests/test_text.py b/sklearn/feature_extraction/tests/test_text.py index 4930debd8350f..acc1a93f1a16f 100644 --- a/sklearn/feature_extraction/tests/test_text.py +++ b/sklearn/feature_extraction/tests/test_text.py @@ -869,8 +869,7 @@ def test_vectorizer_min_df(): ( {"max_features": 3.5}, TypeError, - "max_features must be an instance of <class 'numbers.Integral'>, not <class" - " 'float'>", + "max_features must be an instance of int, not float", ), ), ) diff --git a/sklearn/linear_model/_glm/tests/test_glm.py b/sklearn/linear_model/_glm/tests/test_glm.py index b90e273cbd246..87fe2b51f4d28 100644 --- a/sklearn/linear_model/_glm/tests/test_glm.py +++ b/sklearn/linear_model/_glm/tests/test_glm.py @@ -142,26 +142,23 @@ def test_glm_solver_argument(solver): ( {"max_iter": "not a number"}, TypeError, - "max_iter must be an instance of <class 'numbers.Integral'>, not <class" - " 'str'>", + "max_iter must be an instance of int, not str", ), ( {"max_iter": [1]}, TypeError, - "max_iter must be an instance of <class 'numbers.Integral'>," - " not <class 'list'>", + "max_iter must be an instance of int, not list", ), ( {"max_iter": 5.5}, TypeError, - "max_iter must be an instance of <class 'numbers.Integral'>," - " not <class 'float'>", + "max_iter must be an instance of int, not float", ), ({"alpha": -1}, ValueError, "alpha == -1, must be >= 0.0"), ( {"alpha": "1"}, TypeError, - "alpha must be an instance of <class 'numbers.Real'>, not <class 'str'>", + "alpha must be an instance of float, not str", ), ({"tol": -1.0}, ValueError, "tol == -1.0, must be > 0."), ({"tol": 0.0}, ValueError, "tol == 0.0, must be > 0.0"), @@ -169,25 +166,23 @@ def test_glm_solver_argument(solver): ( {"tol": "1"}, TypeError, - "tol must be an instance of <class 'numbers.Real'>, not <class 'str'>", + "tol must be an instance of float, not str", ), ( {"tol": [1e-3]}, TypeError, - "tol must be an instance of <class 'numbers.Real'>, not <class 'list'>", + "tol must be an instance of float, not list", ), ({"verbose": -1}, ValueError, "verbose == -1, must be >= 0."), ( {"verbose": "1"}, TypeError, - "verbose must be an instance of <class 'numbers.Integral'>, not <class" - " 'str'>", + "verbose must be an instance of int, not str", ), ( {"verbose": 1.0}, TypeError, - "verbose must be an instance of <class 'numbers.Integral'>, not <class" - " 'float'>", + "verbose must be an instance of int, not float", ), ], ) diff --git a/sklearn/linear_model/tests/test_coordinate_descent.py b/sklearn/linear_model/tests/test_coordinate_descent.py index de3c9b164a350..78193518e131e 100644 --- a/sklearn/linear_model/tests/test_coordinate_descent.py +++ b/sklearn/linear_model/tests/test_coordinate_descent.py @@ -115,20 +115,19 @@ def test_assure_warning_when_normalize(CoordinateDescentModel, normalize, n_warn ( {"l1_ratio": "1"}, TypeError, - "l1_ratio must be an instance of <class 'numbers.Real'>, not <class 'str'>", + "l1_ratio must be an instance of float, not str", ), ({"tol": -1.0}, ValueError, "tol == -1.0, must be >= 0."), ( {"tol": "1"}, TypeError, - "tol must be an instance of <class 'numbers.Real'>, not <class 'str'>", + "tol must be an instance of float, not str", ), ({"max_iter": 0}, ValueError, "max_iter == 0, must be >= 1."), ( {"max_iter": "1"}, TypeError, - "max_iter must be an instance of <class 'numbers.Integral'>, not <class" - " 'str'>", + "max_iter must be an instance of int, not str", ), ], ) diff --git a/sklearn/linear_model/tests/test_ridge.py b/sklearn/linear_model/tests/test_ridge.py index eb76814da8b17..60e437e4e0420 100644 --- a/sklearn/linear_model/tests/test_ridge.py +++ b/sklearn/linear_model/tests/test_ridge.py @@ -342,20 +342,19 @@ def test_ridge_individual_penalties(): ( {"alpha": "1"}, TypeError, - "alpha must be an instance of <class 'numbers.Real'>, not <class 'str'>", + "alpha must be an instance of float, not str", ), ({"max_iter": 0}, ValueError, "max_iter == 0, must be >= 1."), ( {"max_iter": "1"}, TypeError, - "max_iter must be an instance of <class 'numbers.Integral'>, not <class" - " 'str'>", + "max_iter must be an instance of int, not str", ), ({"tol": -1.0}, ValueError, "tol == -1.0, must be >= 0."), ( {"tol": "1"}, TypeError, - "tol must be an instance of <class 'numbers.Real'>, not <class 'str'>", + "tol must be an instance of float, not str", ), ], ) @@ -1283,8 +1282,7 @@ def test_ridgecv_int_alphas(): ( {"alphas": (1, 1.0, "1")}, TypeError, - r"alphas\[2\] must be an instance of <class 'numbers.Real'>, not <class" - r" 'str'>", + r"alphas\[2\] must be an instance of float, not str", ), ], ) diff --git a/sklearn/preprocessing/tests/test_discretization.py b/sklearn/preprocessing/tests/test_discretization.py index fa8240893f7c3..51e854eba40b1 100644 --- a/sklearn/preprocessing/tests/test_discretization.py +++ b/sklearn/preprocessing/tests/test_discretization.py @@ -395,10 +395,7 @@ def test_kbinsdiscretizer_subsample_invalid_type(): n_bins=10, encode="ordinal", strategy="quantile", subsample="full" ) - msg = ( - "subsample must be an instance of <class 'numbers.Integral'>, not " - "<class 'str'>." - ) + msg = "subsample must be an instance of int, not str." with pytest.raises(TypeError, match=msg): kbd.fit(X) diff --git a/sklearn/tree/tests/test_tree.py b/sklearn/tree/tests/test_tree.py index e8c08e0fba05f..a2064383b86b0 100644 --- a/sklearn/tree/tests/test_tree.py +++ b/sklearn/tree/tests/test_tree.py @@ -621,14 +621,14 @@ def test_error(): ( {"max_depth": 1.1}, TypeError, - "max_depth must be an instance of <class 'numbers.Integral'>", + "max_depth must be an instance of int", ), ({"min_samples_leaf": 0}, ValueError, "min_samples_leaf == 0, must be >= 1"), ({"min_samples_leaf": 0.0}, ValueError, "min_samples_leaf == 0.0, must be > 0"), ( {"min_samples_leaf": "foo"}, TypeError, - "min_samples_leaf must be an instance of <class 'numbers.Real'>", + "min_samples_leaf must be an instance of float", ), ({"min_samples_split": 1}, ValueError, "min_samples_split == 1, must be >= 2"), ( @@ -644,7 +644,7 @@ def test_error(): ( {"min_samples_split": "foo"}, TypeError, - "min_samples_split must be an instance of <class 'numbers.Real'>", + "min_samples_split must be an instance of float", ), ( {"min_weight_fraction_leaf": -1}, @@ -659,7 +659,7 @@ def test_error(): ( {"min_weight_fraction_leaf": "foo"}, TypeError, - "min_weight_fraction_leaf must be an instance of <class 'numbers.Real'>", + "min_weight_fraction_leaf must be an instance of float", ), ({"max_features": 0}, ValueError, "max_features == 0, must be >= 1"), ({"max_features": 0.0}, ValueError, "max_features == 0.0, must be > 0.0"), @@ -669,7 +669,7 @@ def test_error(): ( {"max_leaf_nodes": 1.5}, TypeError, - "max_leaf_nodes must be an instance of <class 'numbers.Integral'>", + "max_leaf_nodes must be an instance of int", ), ( {"min_impurity_decrease": -1}, @@ -679,13 +679,13 @@ def test_error(): ( {"min_impurity_decrease": "foo"}, TypeError, - "min_impurity_decrease must be an instance of <class 'numbers.Real'>", + "min_impurity_decrease must be an instance of float", ), ({"ccp_alpha": -1.0}, ValueError, "ccp_alpha == -1.0, must be >= 0.0"), ( {"ccp_alpha": "foo"}, TypeError, - "ccp_alpha must be an instance of <class 'numbers.Real'>", + "ccp_alpha must be an instance of float", ), ], ) diff --git a/sklearn/utils/tests/test_validation.py b/sklearn/utils/tests/test_validation.py index 89666c8840748..b104d1721090b 100644 --- a/sklearn/utils/tests/test_validation.py +++ b/sklearn/utils/tests/test_validation.py @@ -1106,9 +1106,34 @@ def test_check_scalar_valid(x): 2, 4, "neither", - TypeError( - "test_name1 must be an instance of <class 'float'>, not <class 'int'>." - ), + TypeError("test_name1 must be an instance of float, not int."), + ), + ( + None, + "test_name1", + numbers.Real, + 2, + 4, + "neither", + TypeError("test_name1 must be an instance of float, not NoneType."), + ), + ( + None, + "test_name1", + numbers.Integral, + 2, + 4, + "neither", + TypeError("test_name1 must be an instance of int, not NoneType."), + ), + ( + 1, + "test_name1", + (float, bool), + 2, + 4, + "neither", + TypeError("test_name1 must be an instance of {float, bool}, not int."), ), ( 1,
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 39f8e405ebf7c..2b53301c40b99 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -617,6 +617,9 @@ Changelog\n left corner of the HTML representation to show how the elements are\n clickable. :pr:`21298` by `Thomas Fan`_.\n \n+- |Enhancement| :func:`utils.validation.check_scalar` now has better messages\n+ when displaying the type. :pr:`22218` by `Thomas Fan`_.\n+\n - |Fix| :func:`check_scalar` raises an error when `include_boundaries={\"left\", \"right\"}`\n and the boundaries are not set.\n :pr:`22027` by `Marie Lanternier <mlant>`.\n" } ]
1.01
39c341ad91b545c895ede9c6240a04659b82defb
[ "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-True-Lasso-params0]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_store_cv_values[neg_mean_squared_error]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape1-asarray-eigen]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params0-ValueError-max_depth == -1, must be >= 1-DecisionTreeRegressor-DecisionTreeRegressor]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[int64-longlong-integer]", "sklearn/cluster/tests/test_spectral.py::test_spectral_params_validation[input8-params8-ValueError-n_neighbors == -1, must be >= 1]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_mem_layout", "sklearn/tree/tests/test_tree.py::test_prune_tree_classifier_are_subtrees[ExtraTreeClassifier-zeros-gini]", "sklearn/ensemble/tests/test_weight_boosting.py::test_diabetes[linear]", "sklearn/cross_decomposition/tests/test_pls.py::test_singular_value_helpers[2-100-10]", "sklearn/cluster/tests/test_birch.py::test_birch_params_validation[params0-ValueError-threshold == -1.0, must be > 0.0.]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_sparse_input[csr_matrix-GradientBoostingRegressor]", "sklearn/tree/tests/test_tree.py::test_diabetes_overfit[absolute_error-ExtraTreeRegressor-ExtraTreeRegressor]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params8-ValueError-tol == 0.0, must be > 0.0-GeneralizedLinearRegressor]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[MultiTaskLasso-params11]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[SPARSE_FILTER-cv1-None]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingRegressor-X0-y0-params21-ValueError-tol == 0.0]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params3-ValueError-min_samples_leaf == 0.0, must be > 0-DecisionTreeClassifier-DecisionTreeClassifier]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_cv_with_some_model_selection", "sklearn/cross_decomposition/tests/test_pls.py::test_singular_value_helpers[8-100-10]", "sklearn/decomposition/tests/test_pca.py::test_pca_sparse_input[auto]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-csr_matrix-None-False]", "sklearn/decomposition/tests/test_pca.py::test_pca_score[randomized]", "sklearn/tree/tests/test_tree.py::test_prune_tree_classifier_are_subtrees[ExtraTreeClassifier-toy-gini]", "sklearn/cross_decomposition/tests/test_pls.py::test_scale_and_stability[X2-Y2-CCA]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_log_regression[family1-True]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingRegressor-X0-y0-params33-ValueError-max_leaf_n]", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_ridge_cv]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_elasticnet_precompute_gram_weighted_samples", "sklearn/tree/tests/test_tree.py::test_sparse_input[sparse-pos-ExtraTreeRegressor]", "sklearn/decomposition/tests/test_pca.py::test_pca_score[arpack]", "sklearn/ensemble/tests/test_weight_boosting.py::test_base_estimator", "sklearn/linear_model/_glm/tests/test_glm.py::test_tags[estimator3-False]", "sklearn/feature_extraction/tests/test_text.py::test_vectorizer_max_df", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.1-True-auto]", "sklearn/cluster/tests/test_dbscan.py::test_dbscan_params_validation[params7-ValueError-leaf_size == -3, must be >= 1.]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-lsqr-False]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingClassifier-X1-y1-params8-ValueError-The init p]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[dtype0-float32-Int8]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[DecisionTreeRegressor-toy-poisson]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-sparse_cg-True]", "sklearn/decomposition/tests/test_pca.py::test_pca_sanity_noise_variance[full]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-ridgecv-True]", "sklearn/utils/tests/test_validation.py::test_check_is_fitted_with_is_fitted", "sklearn/linear_model/tests/test_ridge.py::test_ridge_individual_penalties", "sklearn/ensemble/tests/test_gradient_boosting.py::test_check_inputs_predict_stages", "sklearn/utils/tests/test_validation.py::test_check_dataframe_fit_attribute", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-cholesky-False]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_raise_exception[coo]", "sklearn/preprocessing/tests/test_discretization.py::test_invalid_n_bins", "sklearn/feature_extraction/tests/test_text.py::test_callable_analyzer_change_behavior[filename-<lambda>0-TfidfVectorizer]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-csr_matrix-sample_weight1-True]", "sklearn/cross_decomposition/tests/test_pls.py::test_n_components_bounds_pls_regression[6-ValueError-n_components == 6, must be <= 5.]", "sklearn/cluster/tests/test_birch.py::test_branching_factor", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-cholesky-False]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingRegressor-X0-y0-params11-ValueError-max_featur]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params0-ValueError-max_iter == 0, must be >= 1-TweedieRegressor]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_more_verbose_output", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params9-ValueError-min_weight_fraction_leaf == -1, must be >= 0.0-DecisionTreeRegressor-DecisionTreeRegressor]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-sag]", "sklearn/feature_extraction/tests/test_text.py::test_tfidfvectorizer_binary", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape1-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape0-csr_matrix-svd]", "sklearn/cluster/tests/test_birch.py::test_birch_params_validation[params6-ValueError-n_clusters == 0, must be >= 1.]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_vs_lstsq", "sklearn/linear_model/tests/test_ridge.py::test_sparse_design_with_sample_weights", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_consistency[True-False-0.01-False]", "sklearn/tree/tests/test_tree.py::test_prune_tree_classifier_are_subtrees[ExtraTreeClassifier-multilabel-gini]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-lsqr-False]", "sklearn/cluster/tests/test_spectral.py::test_spectral_clustering[discretize-arpack]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[DecisionTreeRegressor-sparse-pos-squared_error]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_sparse_dense_descent_paths", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[asarray-inf-X-allow-nan-Input X contains infinity]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params6-ValueError-min_samples_split == 0.0, must be > 0.0-DecisionTreeClassifier-DecisionTreeClassifier]", "sklearn/tree/tests/test_tree.py::test_min_weight_fraction_leaf_on_dense_input[DecisionTreeRegressor]", "sklearn/linear_model/_glm/tests/test_glm.py::test_poisson_glmnet", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape0-asarray-svd]", "sklearn/decomposition/tests/test_pca.py::test_n_components_none[data1-randomized-4]", "sklearn/utils/tests/test_validation.py::test_check_scalar_invalid[1-test_name2-int-2-4-neither-err_msg4]", "sklearn/tree/tests/test_tree.py::test_arrayrepr", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[lsqr-True]", "sklearn/tree/tests/test_tree.py::test_balance_property[ExtraTreeRegressor-poisson]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[1.0-True-auto]", "sklearn/decomposition/tests/test_pca.py::test_small_eigenvalues_mle", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_tolerance]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-ridgecv-False]", "sklearn/tree/tests/test_tree.py::test_max_features", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape0-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape1-asarray-svd]", "sklearn/decomposition/tests/test_pca.py::test_pca_check_projection[auto]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[ordinal-float16-float64]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_link_auto[gamma-LogLink]", "sklearn/tree/tests/test_tree.py::test_memory_layout", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape1-csr_matrix-eigen]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_sample_weight_invariance[estimator0]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-ridgecv-False]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_classification_toy[deviance]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_classification_toy[exponential]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_ridge_consistency[False-0.1]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[MultiTaskElasticNet-params10]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingRegressor-X0-y0-params23-ValueError-min_sample]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_warm_start[GradientBoostingClassifier]", "sklearn/feature_extraction/tests/test_text.py::test_unused_parameters_warn[None-None-None-ngram_range4-None-<lambda>-'ngram_range'-'analyzer'-is callable-HashingVectorizer]", "sklearn/cross_decomposition/tests/test_pls.py::test_copy[CCA]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape0-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-ridgecv-False]", "sklearn/cross_decomposition/tests/test_pls.py::test_univariate_equivalence[PLSRegression]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-float64-float32]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[MultiTaskElasticNet-params9]", "sklearn/cluster/tests/test_dbscan.py::test_dbscan_core_samples_toy[ball_tree]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingRegressor-X0-y0-params41-ValueError-criterion=]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-lsqr-False]", "sklearn/decomposition/tests/test_pca.py::test_n_components_mle_error[arpack]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-dense-float16-float64]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-ridgecv-True]", "sklearn/cluster/tests/test_birch.py::test_threshold", "sklearn/cluster/tests/test_dbscan.py::test_dbscan_precomputed_metric_with_degenerate_input_arrays", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_raise_exception[bsr]", "sklearn/tree/tests/test_tree.py::test_prune_tree_classifier_are_subtrees[DecisionTreeClassifier-multilabel-gini]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[int8-byte-integer]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_loss_deprecated[ls-squared_error]", "sklearn/ensemble/tests/test_weight_boosting.py::test_adaboost_params_validation[AdaBoostClassifier-X0-y0-params4-ValueError-learning_rate == 0, must be > 0.]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_oob_multilcass_iris", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params0-ValueError-max_depth == -1, must be >= 1-ExtraTreeClassifier-ExtraTreeClassifier]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-sparse_cg-True]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[ExtraTreeRegressor-toy-poisson]", "sklearn/feature_extraction/tests/test_text.py::test_callable_analyzer_error[file-AttributeError-'str' object has no attribute 'read'-HashingVectorizer]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[Ridge-params5]", "sklearn/cross_decomposition/tests/test_pls.py::test_n_components_bounds[4-ValueError-n_components == 4, must be <= 3.-PLSSVD]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_loss_alpha_error[params3-alpha == 1.2, must be < 1.0]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[DecisionTreeRegressor-reg_small-friedman_mse]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[False-shape4]", "sklearn/tree/tests/test_tree.py::test_n_features_deprecated[ExtraTreeRegressor]", "sklearn/decomposition/tests/test_pca.py::test_assess_dimesion_rank_one", "sklearn/tree/tests/test_tree.py::test_criterion_deprecated[mae-absolute_error-ExtraTreeRegressor]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape1-csr_matrix-eigen]", "sklearn/cross_decomposition/tests/test_pls.py::test_singular_value_helpers[2-100-200]", "sklearn/decomposition/tests/test_pca.py::test_pca[3-auto]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[array-bool]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_zero", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[True-shape1]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[sparse_cg]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_fit_intercept_argument[not bool]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-lsqr-False]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params5-ValueError-alpha == -1, must be >= 0.0-GammaRegressor]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingRegressor-X0-y0-params28-ValueError-min_sample]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_staged_functions_defensive[GradientBoostingClassifier]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_log_regression[family2-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_path_unknown_parameter[enet_path]", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_valid[True-insignificant_imag]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_cv_store_cv_values[accuracy]", "sklearn/cross_decomposition/tests/test_pls.py::test_copy[PLSRegression]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-False-Ridge-params4]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[ExtraTreeRegressor-diabetes-squared_error]", "sklearn/tree/tests/test_tree.py::test_public_apply_sparse_trees[ExtraTreeRegressor]", "sklearn/feature_extraction/tests/test_text.py::test_callable_analyzer_error[filename-FileNotFoundError--CountVectorizer]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params7-ValueError-tol == -1.0, must be > 0.-PoissonRegressor]", "sklearn/utils/tests/test_validation.py::test_get_feature_names_invalid_dtypes_warns[int-str]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-20-asarray-svd]", "sklearn/decomposition/tests/test_pca.py::test_whitening[randomized-False]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[numeric-float64-UInt16]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[ExtraTreeRegressor-clf_small-absolute_error]", "sklearn/ensemble/tests/test_weight_boosting.py::test_classification_toy[SAMME.R]", "sklearn/preprocessing/tests/test_discretization.py::test_encode_options", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[csr_matrix-nan--True-Input contains NaN]", "sklearn/decomposition/tests/test_pca.py::test_pca_check_projection[full]", "sklearn/cross_decomposition/tests/test_pls.py::test_scale_and_stability[X2-Y2-PLSCanonical]", "sklearn/utils/tests/test_validation.py::test_num_features[sparse_csc]", "sklearn/tree/tests/test_tree.py::test_min_samples_leaf", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-8-asarray-svd]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_warm_start_argument[not bool]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-ridgecv-True]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[True-X3-cannot convert float NaN to integer]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[ExtraTreeRegressor-diabetes-poisson]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-sparse_cg-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_warm_start_convergence", "sklearn/preprocessing/tests/test_discretization.py::test_nonuniform_strategies[quantile-expected_2bins2-expected_3bins2-expected_5bins2]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-20-asarray-svd]", "sklearn/tree/tests/test_tree.py::test_min_samples_split", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[DecisionTreeRegressor-iris-squared_error]", "sklearn/feature_extraction/tests/test_text.py::test_sublinear_tf", "sklearn/preprocessing/tests/test_discretization.py::test_32_equal_64[onehot-float16]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-ridgecv-False]", "sklearn/decomposition/tests/test_pca.py::test_infer_dim_by_explained_variance[X1-0.01-1]", "sklearn/tree/tests/test_tree.py::test_prune_tree_classifier_are_subtrees[ExtraTreeClassifier-multilabel-entropy]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_store_cv_values[None]", "sklearn/cluster/tests/test_spectral.py::test_affinities", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingClassifier-X1-y1-params9-ValueError-max_featur]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape1-asarray-svd]", "sklearn/tree/tests/test_tree.py::test_sparse[check_sparse_criterion-sparse-pos-DecisionTreeClassifier]", "sklearn/tree/tests/test_tree.py::test_iris", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[numeric-float64-Int16]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-array-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape1-csr_matrix-eigen]", "sklearn/tree/tests/test_tree.py::test_min_weight_fraction_leaf_on_dense_input[ExtraTreeClassifier]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_link_auto[inverse-gaussian-LogLink]", "sklearn/tree/tests/test_tree.py::test_sparse[check_sparse_parameters-sparse-pos-DecisionTreeRegressor]", "sklearn/linear_model/_glm/tests/test_glm.py::test_sample_weights_validation", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[dtype0-float32-UInt8]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[uint16-ushort-unsignedinteger]", "sklearn/feature_extraction/tests/test_text.py::test_pickling_built_processors[build_analyzer]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_fit_intercept_argument[0]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_path_return_models_vs_new_return_gives_same_coefficients", "sklearn/tree/tests/test_tree.py::test_sample_weight", "sklearn/tree/tests/test_tree.py::test_min_weight_fraction_leaf_on_dense_input[DecisionTreeClassifier]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_scalars[bool]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_consistency[False-False-0.01-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-csr_matrix-sample_weight1-True]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingClassifier-X1-y1-params41-ValueError-criterion=]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params14-ValueError-max_features == 1.1, must be <= 1.0-DecisionTreeClassifier-DecisionTreeClassifier]", "sklearn/cluster/tests/test_birch.py::test_partial_fit", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-array-None-False]", "sklearn/utils/tests/test_validation.py::test_check_memory", "sklearn/tree/tests/test_tree.py::test_class_weights[DecisionTreeClassifier]", "sklearn/cross_decomposition/tests/test_pls.py::test_scale_and_stability[X4-Y4-CCA]", "sklearn/tree/tests/test_tree.py::test_diabetes_overfit[absolute_error-DecisionTreeRegressor-DecisionTreeRegressor]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[False-X2-Input contains infinity or a value too large for.*int]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_warm_start_fortran[GradientBoostingClassifier]", "sklearn/tree/tests/test_tree.py::test_prune_tree_classifier_are_subtrees[ExtraTreeClassifier-zeros-entropy]", "sklearn/tree/tests/test_tree.py::test_importances_gini_equal_squared_error", "sklearn/utils/tests/test_validation.py::test_check_non_negative[dok_matrix]", "sklearn/ensemble/tests/test_weight_boosting.py::test_oneclass_adaboost_proba", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[lbfgs-True]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_identity_regression[True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_random_descent", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_alphas_validation[params0-ValueError-alphas\\\\[1\\\\] == -1, must be > 0.0-RidgeClassifierCV]", "sklearn/tree/tests/test_tree.py::test_prune_tree_classifier_are_subtrees[ExtraTreeClassifier-sparse-neg-gini]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-sag-False]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[ExtraTreeRegressor-iris-squared_error]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_no_exception[csc]", "sklearn/tree/tests/test_tree.py::test_sparse[check_sparse_parameters-sparse-mix-ExtraTreeRegressor]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingRegressor-X0-y0-params9-ValueError-max_featur]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[ElasticNet-params4]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[False-shape3]", "sklearn/cluster/tests/test_birch.py::test_partial_fit_second_call_error_checks", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_valid[True-insignificant neg]", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_ridge_classifiers]", "sklearn/cluster/tests/test_spectral.py::test_precomputed_nearest_neighbors_filtering", "sklearn/cluster/tests/test_birch.py::test_n_clusters", "sklearn/tree/tests/test_tree.py::test_huge_allocations", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[False-shape2]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape1-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-20-asarray-eigen]", "sklearn/ensemble/tests/test_weight_boosting.py::test_adaboost_negative_weight_error[model0-X0-y0]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_sample_weight", "sklearn/utils/tests/test_validation.py::test_check_array_numeric_warns[X4]", "sklearn/preprocessing/tests/test_discretization.py::test_32_equal_64[onehot-float64]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-8-csr_matrix-eigen]", "sklearn/utils/tests/test_validation.py::test_deprecate_positional_args_warns_for_function", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[tuple-float]", "sklearn/tree/tests/test_tree.py::test_decision_path[ExtraTreeClassifier]", "sklearn/cluster/tests/test_dbscan.py::test_dbscan_params_validation[params2-ValueError-min_samples == 0, must be >= 1.]", "sklearn/decomposition/tests/test_pca.py::test_pca[3-randomized]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[True-1-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-cholesky-False]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params8-ValueError-tol == 0.0, must be > 0.0-PoissonRegressor]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[ExtraTreeRegressor-sparse-mix-poisson]", "sklearn/feature_extraction/tests/test_text.py::test_n_features_in[HashingVectorizer-X0]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[svd-False]", "sklearn/preprocessing/tests/test_discretization.py::test_fit_transform[quantile-expected2]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape0-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_params_validation[params2-ValueError-max_iter == 0, must be >= 1.]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-ridgecv-False]", "sklearn/tree/tests/test_tree.py::test_decision_tree_regressor_sample_weight_consistentcy[friedman_mse]", "sklearn/decomposition/tests/test_pca.py::test_pca_validation[auto-3-n_components={}L? must be between {}L? and min\\\\(n_samples, n_features\\\\)={}L? with svd_solver=\\\\'{}\\\\'-data0]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingClassifier-X1-y1-params5-ValueError-subsample ]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params18-ValueError-min_impurity_decrease == -1, must be >= 0.0-ExtraTreeRegressor-ExtraTreeRegressor]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-csr_matrix-None-True]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_complete_regression", "sklearn/linear_model/tests/test_coordinate_descent.py::test_param_invalid[params1-ValueError-l1_ratio == -1, must be >= 0.0]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[SPARSE_FILTER-cv1-accuracy]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_alphas_validation[params0-ValueError-alphas\\\\[1\\\\] == -1, must be > 0.0-RidgeCV]", "sklearn/utils/tests/test_validation.py::test_deprecate_positional_args_warns_for_function_version", "sklearn/ensemble/tests/test_weight_boosting.py::test_importances", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-False-RidgeCV-params6]", "sklearn/tree/tests/test_tree.py::test_different_endianness_pickle", "sklearn/linear_model/tests/test_ridge.py::test_lbfgs_solver_consistency[0.001]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params5-ValueError-min_samples_split == 1, must be >= 2-ExtraTreeClassifier-ExtraTreeClassifier]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params3-ValueError-min_samples_leaf == 0.0, must be > 0-DecisionTreeRegressor-DecisionTreeRegressor]", "sklearn/ensemble/tests/test_weight_boosting.py::test_staged_predict[SAMME.R]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_log_regression[family2-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge[sag]", "sklearn/tree/tests/test_tree.py::test_no_sparse_y_support[ExtraTreeRegressor]", "sklearn/tree/tests/test_tree.py::test_prune_tree_classifier_are_subtrees[DecisionTreeClassifier-iris-gini]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params1-ValueError-max_iter == -1, must be >= 1-PoissonRegressor]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[DecisionTreeRegressor-clf_small-squared_error]", "sklearn/utils/tests/test_validation.py::test_check_non_negative[dia_matrix]", "sklearn/tree/tests/test_tree.py::test_apply_path_readonly_all_trees[DecisionTreeClassifier]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params5-ValueError-alpha == -1, must be >= 0.0-TweedieRegressor]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[False-shape3]", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_invalid[significant neg]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[DecisionTreeRegressor-digits-absolute_error]", "sklearn/utils/tests/test_validation.py::test_np_matrix", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[uintc-uint32-unsignedinteger]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params0-ValueError-max_iter == 0, must be >= 1-GeneralizedLinearRegressor]", "sklearn/cross_decomposition/tests/test_pls.py::test_scale_and_stability[X1-Y1-PLSRegression]", "sklearn/cross_decomposition/tests/test_pls.py::test_singular_value_helpers[7-100-200]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[DecisionTreeRegressor-sparse-mix-squared_error]", "sklearn/linear_model/tests/test_ridge.py::test_X_CenterStackOp[n_col1]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[ExtraTreeRegressor-sparse-neg-poisson]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_custom_scoring[DENSE_FILTER-cv1]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_error_test[saga]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingRegressor-X0-y0-params30-ValueError-min_weight]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_warm_start_max_depth[GradientBoostingRegressor]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-8-asarray-svd]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_nonfinite_params", "sklearn/tree/tests/test_tree.py::test_prune_tree_classifier_are_subtrees[DecisionTreeClassifier-sparse-mix-entropy]", "sklearn/tree/tests/test_tree.py::test_prune_tree_classifier_are_subtrees[ExtraTreeClassifier-sparse-mix-entropy]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[1.0-False-auto]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[dtype0-float32-Float32]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params12-ValueError-verbose == -1, must be >= 0.-TweedieRegressor]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_log_regression[family1-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_set_order_sparse[C-C]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-array-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_cv_values_not_stored[ridge0-make_regression]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_warm_start_clear[GradientBoostingRegressor]", "sklearn/cross_decomposition/tests/test_pls.py::test_scale_and_stability[X3-Y3-PLSSVD]", "sklearn/utils/tests/test_validation.py::test_check_array_complex_data_error", "sklearn/ensemble/tests/test_gradient_boosting.py::test_monitor_early_stopping[GradientBoostingRegressor]", "sklearn/decomposition/tests/test_pca.py::test_pca_explained_variance_empirical[arpack-random-data]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sag_with_X_fortran", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-cholesky-False]", "sklearn/utils/tests/test_validation.py::test_check_array_links_to_imputer_doc_only_for_X[csr_matrix-X]", "sklearn/tree/tests/test_tree.py::test_classification_toy", "sklearn/tree/tests/test_tree.py::test_sparse[check_sparse_parameters-zeros-ExtraTreeRegressor]", "sklearn/preprocessing/tests/test_discretization.py::test_numeric_stability[7]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_cv_individual_penalties", "sklearn/linear_model/tests/test_coordinate_descent.py::test_multi_task_lasso_readonly_data", "sklearn/ensemble/tests/test_weight_boosting.py::test_adaboost_params_validation[AdaBoostRegressor-X1-y1-params1-ValueError-n_estimators == 0, must be >= 1]", "sklearn/utils/tests/test_validation.py::test_check_array_dtype_numeric_errors[X0]", "sklearn/tree/tests/test_tree.py::test_prune_tree_classifier_are_subtrees[ExtraTreeClassifier-sparse-pos-entropy]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params6-ValueError-min_samples_split == 0.0, must be > 0.0-ExtraTreeClassifier-ExtraTreeClassifier]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[svd]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_consistency[False-True-0.01-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape0-asarray-eigen]", "sklearn/decomposition/tests/test_pca.py::test_pca[1-auto]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-array-None-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lassoCV_does_not_set_precompute[True-True]", "sklearn/ensemble/tests/test_weight_boosting.py::test_diabetes[exponential]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[ExtraTreeRegressor-multilabel-absolute_error]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[DecisionTreeRegressor-digits-poisson]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_singular", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[saga-False]", "sklearn/tree/tests/test_tree.py::test_min_weight_fraction_leaf_on_sparse_input[DecisionTreeRegressor]", "sklearn/linear_model/tests/test_ridge.py::test_class_weight_vs_sample_weight[RidgeClassifierCV]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-True-Ridge-params4]", "sklearn/utils/tests/test_validation.py::test_check_scalar_invalid[2-test_name4-int-2-4-right-err_msg6]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params20-ValueError-ccp_alpha == -1.0, must be >= 0.0-DecisionTreeClassifier-DecisionTreeClassifier]", "sklearn/feature_extraction/tests/test_text.py::test_pickling_built_processors[build_tokenizer]", "sklearn/decomposition/tests/test_pca.py::test_pca_sanity_noise_variance[randomized]", "sklearn/cross_decomposition/tests/test_pls.py::test_univariate_equivalence[PLSCanonical]", "sklearn/cross_decomposition/tests/test_pls.py::test_singular_value_helpers[3-100-200]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_coordinate_descent[Lasso-1-kwargs0]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[DecisionTreeRegressor-diabetes-poisson]", "sklearn/linear_model/tests/test_ridge.py::test_X_CenterStackOp[n_col0]", "sklearn/cross_decomposition/tests/test_pls.py::test_scale_and_stability[X3-Y3-PLSCanonical]", "sklearn/cluster/tests/test_birch.py::test_feature_names_out", "sklearn/decomposition/tests/test_pca.py::test_pca_n_components_mostly_explained_variance_ratio", "sklearn/utils/tests/test_validation.py::test_check_array_dtype_numeric_errors[X1]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[None-svd-eigen-True]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_solver_argument[solver2]", "sklearn/decomposition/tests/test_pca.py::test_pca_explained_variance_empirical[full-correlated-data]", "sklearn/decomposition/tests/test_pca.py::test_pca_validation[arpack-0-must be between 1 and min\\\\(n_samples, n_features\\\\)-data0]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-saga-False]", "sklearn/tree/tests/test_tree.py::test_mae", "sklearn/linear_model/_glm/tests/test_glm.py::test_convergence_warning", "sklearn/feature_extraction/tests/test_text.py::test_callable_analyzer_change_behavior[file-<lambda>1-TfidfVectorizer]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-sparse_cg-False]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[ExtraTreeRegressor-clf_small-friedman_mse]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_min_impurity_decrease[GradientBoostingClassifier]", "sklearn/cluster/tests/test_spectral.py::test_discretize[150]", "sklearn/tree/tests/test_tree.py::test_prune_tree_classifier_are_subtrees[ExtraTreeClassifier-clf_small-gini]", "sklearn/tree/tests/test_tree.py::test_realloc", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingClassifier-X1-y1-params2-ValueError-n_estimato]", "sklearn/preprocessing/tests/test_discretization.py::test_transform_1d_behavior", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_ridge_consistency[False-1.0]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params15-ValueError-Invalid value for max_features.-DecisionTreeRegressor-DecisionTreeRegressor]", "sklearn/cluster/tests/test_spectral.py::test_spectral_clustering[kmeans-lobpcg]", "sklearn/linear_model/tests/test_ridge.py::test_class_weights_cv", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_ridge_consistency[True-1.0]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_sparse[ElasticNet]", "sklearn/tree/tests/test_tree.py::test_sparse[check_sparse_criterion-sparse-neg-ExtraTreeClassifier]", "sklearn/tree/tests/test_tree.py::test_sparse_input[toy-DecisionTreeRegressor]", "sklearn/cluster/tests/test_spectral.py::test_spectral_clustering_np_matrix_raises", "sklearn/utils/tests/test_validation.py::test_num_features[dataframe]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-8-asarray-eigen]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_check_input_false", "sklearn/cluster/tests/test_birch.py::test_birch_params_validation[params3-ValueError-branching_factor == 1, must be > 1.]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_sparse_input[csr_matrix-GradientBoostingClassifier]", "sklearn/tree/tests/test_tree.py::test_prune_tree_classifier_are_subtrees[DecisionTreeClassifier-iris-entropy]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[RidgeClassifier-params2]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_positive_constraint", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[csr_matrix-inf-sample_weight-True-Input sample_weight contains infinity]", "sklearn/tree/tests/test_tree.py::test_min_weight_fraction_leaf_with_min_samples_leaf_on_sparse_input[DecisionTreeClassifier]", "sklearn/decomposition/tests/test_pca.py::test_whitening[auto-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-sparse_cg-True]", "sklearn/tree/tests/test_tree.py::test_apply_path_readonly_all_trees[DecisionTreeRegressor]", "sklearn/preprocessing/tests/test_discretization.py::test_valid_n_bins", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-csr_matrix-None-False]", "sklearn/feature_extraction/tests/test_text.py::test_tfidf_transformer_type[float64]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_error_test[cholesky]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_family_argument[normal-instance0]", "sklearn/preprocessing/tests/test_discretization.py::test_invalid_strategy_option", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[ExtraTreeRegressor-zeros-poisson]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_intercept", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingClassifier-X1-y1-params13-ValueError-verbose ==]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_degenerate_targets", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingRegressor-X0-y0-params31-ValueError-min_weight]", "sklearn/tree/tests/test_tree.py::test_public_apply_all_trees[DecisionTreeClassifier]", "sklearn/feature_extraction/tests/test_text.py::test_hashing_vectorizer", "sklearn/cross_decomposition/tests/test_pls.py::test_singular_value_helpers[9-100-200]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-csr_matrix-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[cholesky-True]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params15-ValueError-Invalid value for max_features.-ExtraTreeClassifier-ExtraTreeClassifier]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape0-csr_matrix-svd]", "sklearn/feature_extraction/tests/test_text.py::test_pickling_transformer", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_sample_weight_consistentcy[gamma-1.0-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_fit_intercept_sparse_error[svd]", "sklearn/cross_decomposition/tests/test_pls.py::test_scale_and_stability[X0-Y0-CCA]", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_equals[csc_matrix]", "sklearn/utils/tests/test_validation.py::test_check_scalar_invalid[4-test_name7-int-None-4-left-err_msg9]", "sklearn/tree/tests/test_tree.py::test_error", "sklearn/utils/tests/test_validation.py::test_check_array_accept_sparse_type_exception", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_sample_weight_consistentcy[normal-1.0-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[Ridge-params6]", "sklearn/tree/tests/test_tree.py::test_sparse_input[clf_small-ExtraTreeClassifier]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params16-ValueError-max_leaf_nodes == 0, must be >= 2-ExtraTreeRegressor-ExtraTreeRegressor]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_iris[1-0.5]", "sklearn/decomposition/tests/test_pca.py::test_n_components_none[data1-full-4]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_shapes", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params12-ValueError-verbose == -1, must be >= 0.-GeneralizedLinearRegressor]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[ExtraTreeRegressor-multilabel-poisson]", "sklearn/preprocessing/tests/test_discretization.py::test_numeric_stability[2]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-saga-False]", "sklearn/tree/tests/test_tree.py::test_min_weight_fraction_leaf_with_min_samples_leaf_on_sparse_input[ExtraTreeRegressor]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[0.001-True]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_sparse_input[coo_matrix-GradientBoostingRegressor]", "sklearn/decomposition/tests/test_pca.py::test_n_components_none[data0-arpack-3]", "sklearn/feature_extraction/tests/test_text.py::test_countvectorizer_custom_vocabulary_gap_index", "sklearn/ensemble/tests/test_gradient_boosting.py::test_wrong_type_loss_function[GradientBoostingClassifier-quantile]", "sklearn/preprocessing/tests/test_discretization.py::test_inverse_transform[onehot-dense-uniform-expected_inv0]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_path", "sklearn/tree/tests/test_tree.py::test_no_sparse_y_support[DecisionTreeRegressor]", "sklearn/tree/tests/test_tree.py::test_diabetes_overfit[friedman_mse-DecisionTreeRegressor-DecisionTreeRegressor]", "sklearn/decomposition/tests/test_pca.py::test_whitening[arpack-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-sparse_cg-True]", "sklearn/tree/tests/test_tree.py::test_sparse[check_sparse_criterion-sparse-neg-ExtraTreeRegressor]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_warm_start_smaller_n_estimators[GradientBoostingRegressor]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-array-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_error[5]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingClassifier-X1-y1-params35-ValueError-max_depth ]", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_invalid[significant_imag]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingRegressor-X0-y0-params37-ValueError-min_impuri]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingRegressor-X0-y0-params39-ValueError-ccp_alpha ]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[False-1-True]", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_raise[csr_matrix]", "sklearn/linear_model/tests/test_ridge.py::test_lbfgs_solver_consistency[0.1]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[False-0-False]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[ExtraTreeRegressor-sparse-neg-friedman_mse]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[asarray-inf-sample_weight-True-Input sample_weight contains infinity]", "sklearn/tree/tests/test_tree.py::test_min_weight_fraction_leaf_on_dense_input[ExtraTreeRegressor]", "sklearn/decomposition/tests/test_pca.py::test_pca_deterministic_output[randomized]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-lsqr-False]", "sklearn/tree/tests/test_tree.py::test_prune_tree_classifier_are_subtrees[DecisionTreeClassifier-digits-gini]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[True-False-Ridge-params4]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[LassoLars-params1]", "sklearn/tree/tests/test_tree.py::test_sparse_input[multilabel-ExtraTreeClassifier]", "sklearn/feature_extraction/tests/test_text.py::test_vectorizers_invalid_ngram_range[vec2]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[False-shape1]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape1-csr_matrix-svd]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params0-ValueError-max_depth == -1, must be >= 1-ExtraTreeRegressor-ExtraTreeRegressor]", "sklearn/cluster/tests/test_spectral.py::test_discretize[500]", "sklearn/feature_extraction/tests/test_text.py::test_unused_parameters_warn[None-<lambda>-None-ngram_range1-None-char-'tokenizer'-'analyzer'-!= 'word'-TfidfVectorizer]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params18-ValueError-min_impurity_decrease == -1, must be >= 0.0-DecisionTreeRegressor-DecisionTreeRegressor]", "sklearn/cluster/tests/test_spectral.py::test_verbose[discretize]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.001-False-lbfgs]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_uniform_targets", "sklearn/tree/tests/test_tree.py::test_min_weight_fraction_leaf_with_min_samples_leaf_on_sparse_input[DecisionTreeRegressor]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_consistency[True-False-0.01-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[False-0.5-False]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[numeric-float64-Int8]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[tuple-int]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-saga-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_consistency[False-False-0.01-True]", "sklearn/tree/tests/test_tree.py::test_weighted_classification_toy", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-saga-False]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_warm_start_wo_nestimators_change", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params7-ValueError-tol == -1.0, must be > 0.-GammaRegressor]", "sklearn/cluster/tests/test_spectral.py::test_spectral_clustering[cluster_qr-arpack]", "sklearn/cluster/tests/test_dbscan.py::test_dbscan_params_validation[params8-ValueError-p == -2, must be >= 0.0.]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[ExtraTreeRegressor-digits-poisson]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_consistency[False-True-0.01-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[0.01-False]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingClassifier-X1-y1-params39-ValueError-ccp_alpha ]", "sklearn/preprocessing/tests/test_discretization.py::test_transform_outside_fit_range[uniform]", "sklearn/preprocessing/tests/test_discretization.py::test_same_min_max[uniform]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[LassoLarsIC-params14]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[False-shape2]", "sklearn/cross_decomposition/tests/test_pls.py::test_pls_feature_names_out[PLSRegression]", "sklearn/utils/tests/test_validation.py::test_get_feature_names_pandas", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-sag-False]", "sklearn/preprocessing/tests/test_discretization.py::test_kbinsdiscretizer_subsample_values[200000]", "sklearn/cross_decomposition/tests/test_pls.py::test_singular_value_helpers[6-100-10]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-20-csr_matrix-eigen]", "sklearn/feature_extraction/tests/test_text.py::test_fit_countvectorizer_twice", "sklearn/tree/tests/test_tree.py::test_1d_input[DecisionTreeRegressor]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[DecisionTreeRegressor-digits-squared_error]", "sklearn/tree/tests/test_tree.py::test_sparse_input[sparse-mix-ExtraTreeClassifier]", "sklearn/cluster/tests/test_spectral.py::test_discretize[100]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-cholesky-False]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_staged_functions_defensive[GradientBoostingRegressor]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[numeric-float64-UInt8]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-csr_matrix-None-False]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-dense-float32-float64]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_wrong_type_loss_function[GradientBoostingClassifier-absolute_error]", "sklearn/tree/tests/test_tree.py::test_sample_weight_invalid", "sklearn/utils/tests/test_validation.py::test_check_is_fitted_with_attributes[tuple]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[longdouble-float16]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_coordinate_descent[MultiTaskLasso-2-kwargs3]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_regression_synthetic", "sklearn/tree/tests/test_tree.py::test_n_features_deprecated[DecisionTreeClassifier]", "sklearn/linear_model/_glm/tests/test_glm.py::test_normal_ridge_comparison[None-False-10-100]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-sparse_cg-False]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingRegressor-X0-y0-params6-ValueError-subsample ]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_criterion_mse_deprecated[GradientBoostingRegressor]", "sklearn/feature_extraction/tests/test_text.py::test_callable_analyzer_change_behavior[file-<lambda>0-HashingVectorizer]", "sklearn/feature_extraction/tests/test_text.py::test_unused_parameters_warn[None-<lambda>-None-ngram_range2-\\\\w+-word-'token_pattern'-'tokenizer'-is not None-HashingVectorizer]", "sklearn/cluster/tests/test_spectral.py::test_cluster_qr_permutation_invariance", "sklearn/tree/tests/test_tree.py::test_prune_tree_classifier_are_subtrees[DecisionTreeClassifier-clf_small-gini]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_sample_weight_invariance[estimator1]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_sparse[ElasticNetCV]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingClassifier-X1-y1-params37-ValueError-min_impuri]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params9-ValueError-tol == 0, must be > 0.0-PoissonRegressor]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-sag-False]", "sklearn/tree/tests/test_tree.py::test_sparse_input[digits-ExtraTreeClassifier]", "sklearn/cluster/tests/test_birch.py::test_sparse_X", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[ExtraTreeRegressor-sparse-neg-squared_error]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_valid[csr_matrix-nan-False]", "sklearn/cluster/tests/test_spectral.py::test_spectral_clustering[kmeans-arpack]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-ridgecv-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[RidgeCV-params8]", "sklearn/cross_decomposition/tests/test_pls.py::test_pls_feature_names_out[PLSSVD]", "sklearn/feature_extraction/tests/test_text.py::test_unused_parameters_warn[None-None-None-ngram_range5-\\\\w+-char-'token_pattern'-'analyzer'-!= 'word'-TfidfVectorizer]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[1.0-True]", "sklearn/tree/tests/test_tree.py::test_sparse[check_sparse_criterion-zeros-ExtraTreeRegressor]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-array-None-True]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params16-ValueError-max_leaf_nodes == 0, must be >= 2-DecisionTreeRegressor-DecisionTreeRegressor]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[float64-float64-Float32]", "sklearn/tree/tests/test_tree.py::test_max_leaf_nodes_max_depth", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-float64-float16]", "sklearn/cross_decomposition/tests/test_pls.py::test_scale_and_stability[X1-Y1-CCA]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_probability_exponential", "sklearn/decomposition/tests/test_pca.py::test_pca_deterministic_output[full]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_regression_dataset[1.0-huber]", "sklearn/decomposition/tests/test_pca.py::test_mle_redundant_data", "sklearn/ensemble/tests/test_weight_boosting.py::test_staged_predict[SAMME]", "sklearn/preprocessing/tests/test_discretization.py::test_32_equal_64[onehot-dense-float64]", "sklearn/decomposition/tests/test_pca.py::test_pca_bad_solver", "sklearn/tree/tests/test_tree.py::test_balance_property[DecisionTreeRegressor-poisson]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[DecisionTreeRegressor-sparse-mix-poisson]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[SPARSE_FILTER-None-_accuracy_callable]", "sklearn/feature_extraction/tests/test_text.py::test_callable_analyzer_error[filename-FileNotFoundError--TfidfVectorizer]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_error_test[lsqr]", "sklearn/utils/tests/test_validation.py::test_check_non_negative[lil_matrix]", "sklearn/linear_model/_glm/tests/test_glm.py::test_normal_ridge_comparison[None-True-100-10]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-csr_matrix-None-True]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-float32-float64]", "sklearn/cross_decomposition/tests/test_pls.py::test_sanity_check_pls_canonical_random", "sklearn/tree/tests/test_tree.py::test_diabetes_underfit[friedman_mse-15-mean_squared_error-60-ExtraTreeRegressor-ExtraTreeRegressor]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_oob_improvement_raise", "sklearn/feature_extraction/tests/test_text.py::test_unused_parameters_warn[None-<lambda>-None-ngram_range2-\\\\w+-word-'token_pattern'-'tokenizer'-is not None-CountVectorizer]", "sklearn/tree/tests/test_tree.py::test_decision_path[DecisionTreeRegressor]", "sklearn/feature_extraction/tests/test_text.py::test_countvectorizer_vocab_sets_when_pickling[get_feature_names]", "sklearn/decomposition/tests/test_pca.py::test_pca_dtype_preservation[auto]", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_ridge_loo]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[True-0-False]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_warm_start_fortran[GradientBoostingRegressor]", "sklearn/preprocessing/tests/test_discretization.py::test_inverse_transform[ordinal-kmeans-expected_inv1]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params5-ValueError-min_samples_split == 1, must be >= 2-ExtraTreeRegressor-ExtraTreeRegressor]", "sklearn/cross_decomposition/tests/test_pls.py::test_singular_value_helpers[5-100-10]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[byte-uint16]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params15-ValueError-Invalid value for max_features.-ExtraTreeRegressor-ExtraTreeRegressor]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[lbfgs]", "sklearn/utils/tests/test_validation.py::test_check_array_min_samples_and_features_messages", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-array-None-True]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_warm_start[GradientBoostingRegressor]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_valid[asarray-nan-False]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_sparse_input[csc_matrix-GradientBoostingClassifier]", "sklearn/tree/tests/test_tree.py::test_1d_input[ExtraTreeClassifier]", "sklearn/cluster/tests/test_spectral.py::test_spectral_unknown_mode", "sklearn/utils/tests/test_validation.py::test_check_feature_names_in_pandas", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-array-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge[svd]", "sklearn/decomposition/tests/test_pca.py::test_pca_inverse[False-arpack]", "sklearn/decomposition/tests/test_pca.py::test_pca_singular_values_consistency[randomized]", "sklearn/feature_extraction/tests/test_text.py::test_unused_parameters_warn[None-None-None-ngram_range5-\\\\w+-char-'token_pattern'-'analyzer'-!= 'word'-CountVectorizer]", "sklearn/tree/tests/test_tree.py::test_prune_tree_classifier_are_subtrees[DecisionTreeClassifier-sparse-neg-gini]", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_valid[True-insignificant neg float32]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_non_float_y[ElasticNet]", "sklearn/ensemble/tests/test_weight_boosting.py::test_adaboostregressor_sample_weight", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[False-shape0]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_raise_exception[csr]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-8-csr_matrix-svd]", "sklearn/tree/tests/test_tree.py::test_balance_property[ExtraTreeRegressor-friedman_mse]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-8-csr_matrix-svd]", "sklearn/feature_extraction/tests/test_text.py::test_vectorizer_params_validation[params1-ValueError-min_df == 1.5, must be <= 1.0.]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingClassifier-X1-y1-params6-ValueError-subsample ]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[csr_matrix-nan--allow-inf-force_all_finite should be a bool or \"allow-nan\"]", "sklearn/decomposition/tests/test_pca.py::test_pca_sparse_input[full]", "sklearn/feature_extraction/tests/test_text.py::test_vectorizer_params_validation[params0-ValueError-max_df == 2.0, must be <= 1.0.]", "sklearn/cross_decomposition/tests/test_pls.py::test_scale_and_stability[X0-Y0-PLSRegression]", "sklearn/tree/tests/test_tree.py::test_sparse_input_reg_trees[diabetes-DecisionTreeRegressor]", "sklearn/tree/tests/test_tree.py::test_different_bitness_joblib_pickle", "sklearn/feature_extraction/tests/test_text.py::test_countvectorizer_sort_features_64bit_sparse_indices", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[intc-int32-integer]", "sklearn/tree/tests/test_tree.py::test_sparse[check_sparse_parameters-zeros-DecisionTreeClassifier]", "sklearn/preprocessing/tests/test_discretization.py::test_numeric_stability[6]", "sklearn/preprocessing/tests/test_discretization.py::test_redundant_bins[kmeans-expected_bin_edges1]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_sparse_input[csc_matrix-GradientBoostingRegressor]", "sklearn/linear_model/tests/test_ridge.py::test_ridgeclassifier_multilabel[RidgeClassifier-params0]", "sklearn/feature_extraction/tests/test_text.py::test_vectorizer_params_validation[params5-ValueError-min_df == 1.5, must be <= 1.0.]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-20-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-ridgecv-False]", "sklearn/utils/tests/test_validation.py::test_get_feature_names_invalid_dtypes_warns[list-str]", "sklearn/decomposition/tests/test_pca.py::test_pca_dtype_preservation[randomized]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-sparse_cg-False]", "sklearn/preprocessing/tests/test_discretization.py::test_invalid_n_bins_array", "sklearn/feature_extraction/tests/test_text.py::test_callable_analyzer_change_behavior[file-<lambda>1-CountVectorizer]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[saga]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-csr_matrix-sample_weight1-False]", "sklearn/cross_decomposition/tests/test_pls.py::test_copy[PLSCanonical]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[DENSE_FILTER-cv1-_accuracy_callable]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-csr_matrix-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-cholesky-False]", "sklearn/decomposition/tests/test_pca.py::test_pca_singular_values[auto]", "sklearn/tree/tests/test_tree.py::test_min_weight_fraction_leaf_on_sparse_input[DecisionTreeClassifier]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[asarray-inf-X-True-Input X contains infinity]", "sklearn/ensemble/tests/test_weight_boosting.py::test_samme_proba", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[RidgeClassifier-params3]", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_not_equals[csc_matrix]", "sklearn/tree/tests/test_tree.py::test_n_features_deprecated[ExtraTreeClassifier]", "sklearn/decomposition/tests/test_pca.py::test_pca_validation[randomized-0-must be between 1 and min\\\\(n_samples, n_features\\\\)-data0]", "sklearn/utils/tests/test_validation.py::test_check_array_links_to_imputer_doc_only_for_X[asarray-X]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_cv_store_cv_values[_accuracy_callable]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sparse_svd", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_cv_positive_constraint", "sklearn/ensemble/tests/test_gradient_boosting.py::test_feature_importances[GradientBoostingRegressor-X0-y0]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-csr_matrix-None-False]", "sklearn/feature_extraction/tests/test_text.py::test_unused_parameters_warn[None-<lambda>-None-ngram_range1-None-char-'tokenizer'-'analyzer'-!= 'word'-CountVectorizer]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[DecisionTreeRegressor-diabetes-squared_error]", "sklearn/decomposition/tests/test_pca.py::test_pca_validation[auto-1.0-must be of type int-data1]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gradient_boosting_with_init[binary classification]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingRegressor-X0-y0-params5-ValueError-subsample ]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[False-1-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-sag-False]", "sklearn/decomposition/tests/test_pca.py::test_pca_randomized_svd_n_oversamples", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_invalid[significant neg float64]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-lsqr-False]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params7-ValueError-tol == -1.0, must be > 0.-GeneralizedLinearRegressor]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params1-ValueError-max_iter == -1, must be >= 1-GammaRegressor]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[True-False-RidgeCV-params6]", "sklearn/decomposition/tests/test_pca.py::test_n_components_mle_error[randomized]", "sklearn/cluster/tests/test_dbscan.py::test_dbscan_metric_params", "sklearn/cluster/tests/test_dbscan.py::test_dbscan_sparse", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-lsqr-False]", "sklearn/decomposition/tests/test_pca.py::test_pca_check_projection[arpack]", "sklearn/tree/tests/test_tree.py::test_sparse_input[sparse-neg-DecisionTreeClassifier]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[tuple-bool]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-sparse_cg-False]", "sklearn/utils/tests/test_validation.py::test_check_sample_weight", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-lsqr-False]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[uint32-uint64]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_single_class_with_sample_weight", "sklearn/cross_decomposition/tests/test_pls.py::test_univariate_equivalence[CCA]", "sklearn/tree/tests/test_tree.py::test_sparse_input[multilabel-ExtraTreeRegressor]", "sklearn/linear_model/_glm/tests/test_glm.py::test_warm_start[True]", "sklearn/feature_extraction/tests/test_text.py::test_char_ngram_analyzer", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[SPARSE_FILTER-cv1-_accuracy_callable]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-sparse_cg-False]", "sklearn/cross_decomposition/tests/test_pls.py::test_scale_and_stability[X0-Y0-PLSSVD]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-ridgecv-True]", "sklearn/preprocessing/tests/test_discretization.py::test_fit_transform[uniform-expected0]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[RidgeClassifierCV-params9]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[DecisionTreeRegressor-sparse-mix-absolute_error]", "sklearn/tree/tests/test_tree.py::test_sparse[check_sparse_criterion-zeros-DecisionTreeRegressor]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[ordinal-None-float64]", "sklearn/tree/tests/test_tree.py::test_regression_toy[friedman_mse-ExtraTreeRegressor]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_regression_dataset[0.5-absolute_error]", "sklearn/cross_decomposition/tests/test_pls.py::test_singular_value_helpers[6-100-200]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-False-RidgeClassifier-params1]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[uintp-ulonglong-unsignedinteger]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-sparse_cg-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_elasticnet_precompute_incorrect_gram", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-ridgecv-False]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params8-ValueError-tol == 0.0, must be > 0.0-GammaRegressor]", "sklearn/tree/tests/test_tree.py::test_prune_tree_classifier_are_subtrees[DecisionTreeClassifier-digits-entropy]", "sklearn/preprocessing/tests/test_discretization.py::test_numeric_stability[3]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[DecisionTreeRegressor-diabetes-absolute_error]", "sklearn/cross_decomposition/tests/test_pls.py::test_singular_value_helpers[0-100-200]", "sklearn/preprocessing/tests/test_discretization.py::test_nonuniform_strategies[uniform-expected_2bins0-expected_3bins0-expected_5bins0]", "sklearn/feature_extraction/tests/test_text.py::test_hashed_binary_occurrences", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_solver_argument[not a solver]", "sklearn/tree/tests/test_tree.py::test_min_weight_fraction_leaf_on_sparse_input[ExtraTreeClassifier]", "sklearn/linear_model/_glm/tests/test_glm.py::test_normal_ridge_comparison[True-True-100-10]", "sklearn/decomposition/tests/test_pca.py::test_pca_score3", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-ridgecv-False]", "sklearn/decomposition/tests/test_pca.py::test_pca_check_projection[randomized]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params12-ValueError-verbose == -1, must be >= 0.-PoissonRegressor]", "sklearn/utils/tests/test_validation.py::test_check_sparse_pandas_sp_format[bsr]", "sklearn/cluster/tests/test_dbscan.py::test_boundaries", "sklearn/linear_model/_glm/tests/test_glm.py::test_tweedie_regression_family", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[DecisionTreeRegressor-diabetes-friedman_mse]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape1-asarray-eigen]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_sample_weight_consistentcy[normal-0.0-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_loo_cv_asym_scoring", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.001-False-auto]", "sklearn/cluster/tests/test_dbscan.py::test_dbscan_input_not_modified[minkowski-False]", "sklearn/utils/tests/test_validation.py::test_check_array_numeric_warns[X2]", "sklearn/utils/tests/test_validation.py::test_num_features[list]", "sklearn/tree/tests/test_tree.py::test_balance_property[DecisionTreeRegressor-friedman_mse]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-csr_matrix-None-True]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_wrong_type_loss_function[GradientBoostingRegressor-deviance]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-array-None-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_copy_X_False_check_input_False", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[0.1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-array-sample_weight1-True]", "sklearn/decomposition/tests/test_pca.py::test_n_components_none[data0-full-4]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-True-RidgeClassifier-params1]", "sklearn/tree/tests/test_tree.py::test_sparse_input[digits-DecisionTreeRegressor]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_consistency[True-True-0.01-False]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_warm_start_argument[1]", "sklearn/feature_extraction/tests/test_text.py::test_callable_analyzer_change_behavior[filename-<lambda>1-HashingVectorizer]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_toy", "sklearn/linear_model/tests/test_ridge.py::test_ridge[cholesky]", "sklearn/decomposition/tests/test_pca.py::test_pca_sparse_input[randomized]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-array-None-True]", "sklearn/cross_decomposition/tests/test_pls.py::test_attibutes_shapes[PLSSVD]", "sklearn/tree/tests/test_tree.py::test_min_impurity_decrease", "sklearn/linear_model/tests/test_ridge.py::test_ridgeclassifier_multilabel[RidgeClassifierCV-params1]", "sklearn/cluster/tests/test_dbscan.py::test_dbscan_similarity", "sklearn/feature_extraction/tests/test_text.py::test_callable_analyzer_reraise_error[TfidfVectorizer]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[DecisionTreeRegressor-toy-squared_error]", "sklearn/cluster/tests/test_dbscan.py::test_pickle", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[DecisionTreeRegressor-iris-absolute_error]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_dtype_object_conversion", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_valid[csr_matrix-nan-allow-nan]", "sklearn/utils/tests/test_validation.py::test_check_consistent_length", "sklearn/decomposition/tests/test_pca.py::test_pca_validation[arpack-0-must be between 1 and min\\\\(n_samples, n_features\\\\)-data1]", "sklearn/tree/tests/test_tree.py::test_sparse_input[sparse-neg-DecisionTreeRegressor]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_alphas_validation[params1-ValueError-alphas\\\\[0\\\\] == -0.1, must be > 0.0-RidgeCV]", "sklearn/decomposition/tests/test_pca.py::test_pca[3-full]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-svd]", "sklearn/feature_extraction/tests/test_text.py::test_unused_parameters_warn[None-None-None-ngram_range5-\\\\w+-char-'token_pattern'-'analyzer'-!= 'word'-HashingVectorizer]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_log_regression[family4-False]", "sklearn/tree/tests/test_tree.py::test_max_leaf_nodes", "sklearn/cluster/tests/test_spectral.py::test_spectral_params_validation[input4-params4-ValueError-n_init == 0, must be >= 1]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_warm_start_equal_n_estimators[GradientBoostingClassifier]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-20-csr_matrix-svd]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_correctness[False]", "sklearn/feature_extraction/tests/test_text.py::test_unused_parameters_warn[None-None-<lambda>-ngram_range3-\\\\w+-<lambda>-'preprocessor'-'analyzer'-is callable-TfidfVectorizer]", "sklearn/decomposition/tests/test_pca.py::test_pca_svd_solver_auto[data1-5-full]", "sklearn/preprocessing/tests/test_discretization.py::test_transform_outside_fit_range[kmeans]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-saga-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_multitask_enet_and_lasso_cv", "sklearn/ensemble/tests/test_gradient_boosting.py::test_complete_classification", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params0-ValueError-max_iter == 0, must be >= 1-GammaRegressor]", "sklearn/tree/tests/test_tree.py::test_min_weight_fraction_leaf_with_min_samples_leaf_on_dense_input[DecisionTreeRegressor]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[uint-uint64-unsignedinteger]", "sklearn/cross_decomposition/tests/test_pls.py::test_scale_and_stability[X2-Y2-PLSRegression]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[ordinal-None-float32]", "sklearn/feature_extraction/tests/test_text.py::test_countvectorizer_vocab_dicts_when_pickling[get_feature_names]", "sklearn/feature_extraction/tests/test_text.py::test_count_vectorizer_max_features[get_feature_names]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_warm_start_multitask_lasso", "sklearn/linear_model/tests/test_ridge.py::test_n_iter", "sklearn/tree/tests/test_tree.py::test_regression_toy[squared_error-DecisionTreeRegressor]", "sklearn/feature_extraction/tests/test_text.py::test_countvectorizer_stop_words", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_l1_ratio", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params0-ValueError-max_depth == -1, must be >= 1-DecisionTreeClassifier-DecisionTreeClassifier]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_scalars[int]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingRegressor-X0-y0-params24-ValueError-min_sample]", "sklearn/decomposition/tests/test_pca.py::test_pca_validation[randomized-0-must be between 1 and min\\\\(n_samples, n_features\\\\)-data1]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[DecisionTreeRegressor-reg_small-poisson]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params2-ValueError-min_samples_leaf == 0, must be >= 1-DecisionTreeRegressor-DecisionTreeRegressor]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-sag-False]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params7-ValueError-tol == -1.0, must be > 0.-TweedieRegressor]", "sklearn/feature_extraction/tests/test_text.py::test_strip_accents", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-20-csr_matrix-svd]", "sklearn/utils/tests/test_validation.py::test_check_array_memmap[False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-sag-False]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingRegressor-X0-y0-params17-ValueError-validation]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_fit_intercept_sparse_error[cholesky]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params9-ValueError-min_weight_fraction_leaf == -1, must be >= 0.0-DecisionTreeClassifier-DecisionTreeClassifier]", "sklearn/cross_decomposition/tests/test_pls.py::test_singular_value_helpers[4-100-10]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_dual_gap", "sklearn/tree/tests/test_tree.py::test_sparse_input[digits-ExtraTreeRegressor]", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_ridge_cv_normalize]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.1-True-lbfgs]", "sklearn/feature_extraction/tests/test_text.py::test_nonnegative_hashing_vectorizer_result_indices", "sklearn/decomposition/tests/test_pca.py::test_pca_sparse_input[arpack]", "sklearn/feature_extraction/tests/test_text.py::test_countvectorizer_custom_token_pattern[get_feature_names_out]", "sklearn/feature_extraction/tests/test_text.py::test_n_features_in[CountVectorizer-X1]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_iris[None-1.0]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[DecisionTreeRegressor-multilabel-poisson]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.1-False-lbfgs]", "sklearn/tree/tests/test_tree.py::test_min_weight_leaf_split_level[DecisionTreeRegressor]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[None-svd-eigen-False]", "sklearn/decomposition/tests/test_pca.py::test_pca_inverse[True-randomized]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_raise_exception[csc]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[DecisionTreeRegressor-clf_small-friedman_mse]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-ridgecv-True]", "sklearn/linear_model/_glm/tests/test_glm.py::test_normal_ridge_comparison[True-True-10-100]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_error[gcv]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-8-csr_matrix-eigen]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_warm_start_oob[GradientBoostingClassifier]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-sparse_cg-False]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[series-dict]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[ordinal-float64-float32]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-20-asarray-svd]", "sklearn/tree/tests/test_tree.py::test_decision_tree_regressor_sample_weight_consistentcy[squared_error]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.01-False-auto]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_custom_scoring[SPARSE_FILTER-None]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-float16-float16]", "sklearn/linear_model/_glm/tests/test_glm.py::test_normal_ridge_comparison[True-False-10-100]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.001-True-auto]", "sklearn/tree/tests/test_tree.py::test_check_node_ndarray", "sklearn/linear_model/tests/test_ridge.py::test_lbfgs_solver_consistency[0.01]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_warm_start_argument[0]", "sklearn/feature_extraction/tests/test_text.py::test_countvectorizer_empty_vocabulary", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_equals[csr_matrix]", "sklearn/tree/tests/test_tree.py::test_poisson_zero_nodes[1]", "sklearn/tree/tests/test_tree.py::test_diabetes_underfit[absolute_error-20-mean_squared_error-60-DecisionTreeRegressor-DecisionTreeRegressor]", "sklearn/tree/tests/test_tree.py::test_sparse_input[multilabel-DecisionTreeClassifier]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-sparse_cg-False]", "sklearn/cluster/tests/test_spectral.py::test_spectral_params_validation[input3-params3-ValueError-n_init == -1, must be >= 1]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[True-shape4]", "sklearn/feature_extraction/tests/test_text.py::test_word_ngram_analyzer", "sklearn/cross_decomposition/tests/test_pls.py::test_n_components_bounds[0-ValueError-n_components == 0, must be >= 1.-PLSSVD]", "sklearn/decomposition/tests/test_pca.py::test_n_components_none[data1-arpack-3]", "sklearn/feature_extraction/tests/test_text.py::test_tfidf_vectorizer_setters", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-sag-False]", "sklearn/decomposition/tests/test_pca.py::test_pca_validation[auto-3-n_components={}L? must be between {}L? and min\\\\(n_samples, n_features\\\\)={}L? with svd_solver=\\\\'{}\\\\'-data1]", "sklearn/cross_decomposition/tests/test_pls.py::test_copy[PLSSVD]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingRegressor-X0-y0-params14-TypeError-verbose mu]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-False-ElasticNet-params2]", "sklearn/tree/tests/test_tree.py::test_pure_set", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-array-None-True]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params1-ValueError-max_iter == -1, must be >= 1-GeneralizedLinearRegressor]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-array-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape0-csr_matrix-eigen]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-dense-None-float32]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-cholesky-False]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_log_regression[family5-True]", "sklearn/linear_model/tests/test_ridge.py::test_class_weight_vs_sample_weight[RidgeClassifier]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-True-RidgeClassifierCV-params7]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingClassifier-X1-y1-params19-ValueError-n_iter_no_]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingClassifier-X1-y1-params11-ValueError-max_featur]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_coordinate_descent[Lasso-1-kwargs1]", "sklearn/decomposition/tests/test_pca.py::test_fit_mle_too_few_samples", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[ExtraTreeRegressor-iris-poisson]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gradient_boosting_with_init[multiclass classification]", "sklearn/tree/tests/test_tree.py::test_sparse_input[sparse-pos-DecisionTreeRegressor]", "sklearn/preprocessing/tests/test_discretization.py::test_numeric_stability[1]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params18-ValueError-min_impurity_decrease == -1, must be >= 0.0-ExtraTreeClassifier-ExtraTreeClassifier]", "sklearn/decomposition/tests/test_pca.py::test_pca_explained_variance_empirical[full-random-data]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-sag-False]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-dense-float64-float16]", "sklearn/tree/tests/test_tree.py::test_criterion_deprecated[mae-absolute_error-DecisionTreeRegressor]", "sklearn/tree/tests/test_tree.py::test_empty_leaf_infinite_threshold", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingRegressor-X0-y0-params13-ValueError-verbose ==]", "sklearn/preprocessing/tests/test_discretization.py::test_kbinsdiscretizer_subsample_default[None]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape0-asarray-svd]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_min_impurity_decrease[GradientBoostingRegressor]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape1-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-sparse_cg-True]", "sklearn/tree/tests/test_tree.py::test_arrays_persist", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-sag-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[Lasso-params0]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params2-ValueError-min_samples_leaf == 0, must be >= 1-DecisionTreeClassifier-DecisionTreeClassifier]", "sklearn/feature_extraction/tests/test_text.py::test_unused_parameters_warn[stop_words0-None-None-ngram_range0-None-char-'stop_words'-'analyzer'-!= 'word'-HashingVectorizer]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_valid[asarray-nan-allow-nan]", "sklearn/utils/tests/test_validation.py::test_check_array_links_to_imputer_doc_only_for_X[csr_matrix-sample_weight]", "sklearn/tree/tests/test_tree.py::test_decision_path[ExtraTreeRegressor]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[False-shape1]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_identity_regression[False]", "sklearn/cluster/tests/test_spectral.py::test_verbose[cluster_qr]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-array-None-True]", "sklearn/decomposition/tests/test_pca.py::test_pca_singular_values[full]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[lsqr]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_param_invalid[params6-ValueError-max_iter == 0, must be >= 1.]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-array-sample_weight1-True]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingRegressor-X0-y0-params15-TypeError-warm_start]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params12-ValueError-verbose == -1, must be >= 0.-GammaRegressor]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-sparse_cg-True]", "sklearn/preprocessing/tests/test_discretization.py::test_32_equal_64[onehot-float32]", "sklearn/decomposition/tests/test_pca.py::test_pca_explained_variance_equivalence_solver[randomized]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[int16-int32]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_loss_deprecated[lad-absolute_error]", "sklearn/cluster/tests/test_spectral.py::test_spectral_clustering_sparse[discretize]", "sklearn/feature_extraction/tests/test_text.py::test_unused_parameters_warn[None-None-<lambda>-ngram_range3-\\\\w+-<lambda>-'preprocessor'-'analyzer'-is callable-HashingVectorizer]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.001-True-lbfgs]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params6-ValueError-min_samples_split == 0.0, must be > 0.0-DecisionTreeRegressor-DecisionTreeRegressor]", "sklearn/preprocessing/tests/test_discretization.py::test_overwrite", "sklearn/cluster/tests/test_spectral.py::test_spectral_clustering_not_infinite_loop", "sklearn/utils/tests/test_validation.py::test_check_fit_params[indices1]", "sklearn/feature_extraction/tests/test_text.py::test_count_binary_occurrences[get_feature_names_out]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params10-ValueError-min_weight_fraction_leaf == 0.6, must be <= 0.5-DecisionTreeClassifier-DecisionTreeClassifier]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-saga-False]", "sklearn/tree/tests/test_tree.py::test_sparse[check_sparse_criterion-sparse-mix-DecisionTreeRegressor]", "sklearn/ensemble/tests/test_weight_boosting.py::test_adaboost_consistent_predict[SAMME.R]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params9-ValueError-tol == 0, must be > 0.0-TweedieRegressor]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-array-None-False]", "sklearn/cluster/tests/test_dbscan.py::test_dbscan_input_not_modified[precomputed-True]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params5-ValueError-alpha == -1, must be >= 0.0-GeneralizedLinearRegressor]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_sample_weight_consistentcy[gamma-1.0-False]", "sklearn/decomposition/tests/test_pca.py::test_pca[2-arpack]", "sklearn/decomposition/tests/test_pca.py::test_pca_sanity_noise_variance[arpack]", "sklearn/cluster/tests/test_dbscan.py::test_input_validation", "sklearn/feature_extraction/tests/test_text.py::test_vectorizer_string_object_as_input[CountVectorizer]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_shape_y", "sklearn/tree/tests/test_tree.py::test_sparse[check_sparse_criterion-zeros-ExtraTreeClassifier]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[ExtraTreeRegressor-reg_small-friedman_mse]", "sklearn/tree/tests/test_tree.py::test_unbalanced_iris", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape1-csr_matrix-eigen]", "sklearn/utils/tests/test_validation.py::test_check_non_negative[bsr_matrix]", "sklearn/tree/tests/test_tree.py::test_only_constant_features", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-csr_matrix-None-False]", "sklearn/tree/tests/test_tree.py::test_regression_toy[squared_error-ExtraTreeRegressor]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingRegressor-X0-y0-params26-ValueError-min_sample]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape0-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[DENSE_FILTER-cv1-None]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-array-sample_weight1-True]", "sklearn/decomposition/tests/test_pca.py::test_pca_check_projection_list[full]", "sklearn/tree/tests/test_tree.py::test_min_weight_fraction_leaf_with_min_samples_leaf_on_dense_input[ExtraTreeClassifier]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[ExtraTreeRegressor-reg_small-squared_error]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params12-ValueError-max_features == 0, must be >= 1-DecisionTreeRegressor-DecisionTreeRegressor]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_loss_alpha_error[params0-alpha == 0.0, must be > 0.0]", "sklearn/tree/tests/test_tree.py::test_numerical_stability", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_error_test[sparse_cg]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_set_order_sparse[C-F]", "sklearn/decomposition/tests/test_pca.py::test_pca[2-auto]", "sklearn/linear_model/tests/test_ridge.py::test_class_weights", "sklearn/tree/tests/test_tree.py::test_sparse[check_sparse_parameters-sparse-pos-ExtraTreeRegressor]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_oob_improvement", "sklearn/ensemble/tests/test_weight_boosting.py::test_iris", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[DecisionTreeRegressor-reg_small-squared_error]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[ElasticNet-params5]", "sklearn/utils/tests/test_validation.py::test_check_array_series", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-cholesky-False]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_wrong_type_loss_function[GradientBoostingClassifier-ls]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_fit_intercept_argument[fit_intercept3]", "sklearn/tree/tests/test_tree.py::test_regression_toy[absolute_error-DecisionTreeRegressor]", "sklearn/tree/tests/test_tree.py::test_sparse_input[zeros-DecisionTreeClassifier]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-csr_matrix-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape0-csr_matrix-eigen]", "sklearn/decomposition/tests/test_pca.py::test_feature_names_out", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params3-ValueError-min_samples_leaf == 0.0, must be > 0-ExtraTreeClassifier-ExtraTreeClassifier]", "sklearn/preprocessing/tests/test_discretization.py::test_32_equal_64[onehot-dense-float16]", "sklearn/feature_extraction/tests/test_text.py::test_char_wb_ngram_analyzer", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[True-0-True]", "sklearn/decomposition/tests/test_pca.py::test_whitening[full-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-sparse_cg-True]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingClassifier-X1-y1-params26-ValueError-min_sample]", "sklearn/decomposition/tests/test_pca.py::test_pca_singular_values[arpack]", "sklearn/feature_extraction/tests/test_text.py::test_vectorizer_inverse_transform[CountVectorizer]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[asarray-nan--allow-inf-force_all_finite should be a bool or \"allow-nan\"]", "sklearn/utils/tests/test_validation.py::test_check_symmetric", "sklearn/linear_model/tests/test_ridge.py::test_positive_ridge_loss[0.001]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_alpha_warning", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape0-csr_matrix-svd]", "sklearn/cluster/tests/test_dbscan.py::test_dbscan_input_not_modified[precomputed-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-8-asarray-eigen]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[asarray-nan-X-True-Input X contains NaN]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[float64-float64-Int8]", "sklearn/linear_model/tests/test_ridge.py::test_positive_ridge_loss[0.01]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[auto-svd-eigen-False]", "sklearn/decomposition/tests/test_pca.py::test_pca_deterministic_output[auto]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_no_exception[bsr]", "sklearn/tree/tests/test_tree.py::test_sparse[check_sparse_parameters-sparse-mix-DecisionTreeClassifier]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_solver_argument[1]", "sklearn/linear_model/tests/test_ridge.py::test_toy_ridge_object", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params5-ValueError-min_samples_split == 1, must be >= 2-DecisionTreeClassifier-DecisionTreeClassifier]", "sklearn/feature_extraction/tests/test_text.py::test_tfidfvectorizer_invalid_idf_attr", "sklearn/tree/tests/test_tree.py::test_min_weight_fraction_leaf_on_sparse_input[ExtraTreeRegressor]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[tuple-str]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-csr_matrix-None-True]", "sklearn/feature_extraction/tests/test_text.py::test_countvectorizer_custom_token_pattern[get_feature_names]", "sklearn/cluster/tests/test_birch.py::test_birch_params_validation[params2-ValueError-branching_factor == 0, must be > 1.]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-lsqr-False]", "sklearn/tree/tests/test_tree.py::test_prune_tree_classifier_are_subtrees[ExtraTreeClassifier-sparse-pos-gini]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[True-X2-Input contains infinity or a value too large for.*int]", "sklearn/tree/tests/test_tree.py::test_regression_toy[poisson-ExtraTreeRegressor]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_link_auto[normal-IdentityLink]", "sklearn/tree/tests/test_tree.py::test_regression_toy[absolute_error-ExtraTreeRegressor]", "sklearn/tree/tests/test_tree.py::test_explicit_sparse_zeros[ExtraTreeRegressor]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-float32-float32]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_no_exception[csr]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-saga-False]", "sklearn/cross_decomposition/tests/test_pls.py::test_pls_constant_y", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[list-bool]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-float16-float32]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params12-ValueError-max_features == 0, must be >= 1-DecisionTreeClassifier-DecisionTreeClassifier]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[False-X0-Input contains NaN.]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-array-sample_weight1-True]", "sklearn/feature_extraction/tests/test_text.py::test_callable_analyzer_change_behavior[filename-<lambda>1-TfidfVectorizer]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingClassifier-X1-y1-params17-ValueError-validation]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_sample_weight_consistentcy[poisson-0.0-False]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params7-ValueError-min_samples_split == 1.1, must be <= 1.0-ExtraTreeRegressor-ExtraTreeRegressor]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_staged_predict_proba", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingClassifier-X1-y1-params31-ValueError-min_weight]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-csr_matrix-sample_weight1-False]", "sklearn/tree/tests/test_tree.py::test_sparse[check_sparse_criterion-sparse-neg-DecisionTreeRegressor]", "sklearn/tree/tests/test_tree.py::test_prune_tree_classifier_are_subtrees[DecisionTreeClassifier-multilabel-entropy]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[series-int]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params1-ValueError-max_iter == -1, must be >= 1-TweedieRegressor]", "sklearn/tree/tests/test_tree.py::test_diabetes_overfit[squared_error-ExtraTreeRegressor-ExtraTreeRegressor]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-False-LinearRegression-params5]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-sparse_cg-False]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params13-ValueError-max_features == 0.0, must be > 0.0-DecisionTreeClassifier-DecisionTreeClassifier]", "sklearn/tree/tests/test_tree.py::test_prune_tree_classifier_are_subtrees[DecisionTreeClassifier-sparse-pos-entropy]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[1.0-False-lbfgs]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params9-ValueError-min_weight_fraction_leaf == -1, must be >= 0.0-ExtraTreeRegressor-ExtraTreeRegressor]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params16-ValueError-max_leaf_nodes == 0, must be >= 2-ExtraTreeClassifier-ExtraTreeClassifier]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingRegressor-X0-y0-params0-ValueError-learning_r]", "sklearn/ensemble/tests/test_weight_boosting.py::test_adaboost_params_validation[AdaBoostClassifier-X0-y0-params0-ValueError-n_estimators == -1, must be >= 1]", "sklearn/tree/tests/test_tree.py::test_diabetes_underfit[squared_error-15-mean_squared_error-60-DecisionTreeRegressor-DecisionTreeRegressor]", "sklearn/utils/tests/test_validation.py::test_as_float_array_nan[X0]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[True-False-RidgeClassifier-params1]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[ExtraTreeRegressor-digits-absolute_error]", "sklearn/utils/tests/test_validation.py::test_deprecate_positional_args_warns_for_class", "sklearn/tree/tests/test_tree.py::test_sparse[check_sparse_parameters-sparse-pos-ExtraTreeClassifier]", "sklearn/feature_extraction/tests/test_text.py::test_unused_parameters_warn[None-<lambda>-None-ngram_range2-\\\\w+-word-'token_pattern'-'tokenizer'-is not None-TfidfVectorizer]", "sklearn/preprocessing/tests/test_discretization.py::test_kbinsdiscretizer_subsample_default[warn]", "sklearn/decomposition/tests/test_pca.py::test_whitening[arpack-False]", "sklearn/tree/tests/test_tree.py::test_behaviour_constant_feature_after_splits", "sklearn/tree/tests/test_tree.py::test_decision_path[DecisionTreeClassifier]", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_ridge_diabetes]", "sklearn/tree/tests/test_tree.py::test_probability", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-dense-float32-float32]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_multioutput_enetcv_error", "sklearn/decomposition/tests/test_pca.py::test_pca[1-randomized]", "sklearn/feature_extraction/tests/test_text.py::test_unused_parameters_warn[None-None-None-ngram_range4-None-<lambda>-'ngram_range'-'analyzer'-is callable-CountVectorizer]", "sklearn/cluster/tests/test_dbscan.py::test_dbscan_badargs[args0]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[csr_matrix-nan--1-Input contains NaN]", "sklearn/feature_extraction/tests/test_text.py::test_word_analyzer_unigrams_and_bigrams", "sklearn/decomposition/tests/test_pca.py::test_pca_explained_variance_equivalence_solver[arpack]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-dense-float16-float16]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-sparse_cg-True]", "sklearn/tree/tests/test_tree.py::test_diabetes_overfit[poisson-DecisionTreeRegressor-DecisionTreeRegressor]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-20-asarray-svd]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[array-str]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_loss_alpha_error[params2-alpha == 1.2, must be < 1.0]", "sklearn/cluster/tests/test_spectral.py::test_spectral_clustering_sparse[kmeans]", "sklearn/cross_decomposition/tests/test_pls.py::test_n_components_bounds_pls_regression[0-ValueError-n_components == 0, must be >= 1.]", "sklearn/preprocessing/tests/test_discretization.py::test_fit_transform_n_bins_array[quantile-expected2]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-sag-False]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-float32-float16]", "sklearn/linear_model/tests/test_ridge.py::test_lbfgs_solver_error", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params9-ValueError-min_weight_fraction_leaf == -1, must be >= 0.0-ExtraTreeClassifier-ExtraTreeClassifier]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params5-ValueError-min_samples_split == 1, must be >= 2-DecisionTreeRegressor-DecisionTreeRegressor]", "sklearn/utils/tests/test_validation.py::test_check_non_negative[csc_matrix]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_error_test[svd]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[False-X1-Input contains NaN.]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[ExtraTreeRegressor-zeros-absolute_error]", "sklearn/cross_decomposition/tests/test_pls.py::test_sanity_check_pls_regression", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[float64-float64-Float64]", "sklearn/cluster/tests/test_spectral.py::test_spectral_clustering[discretize-lobpcg]", "sklearn/ensemble/tests/test_weight_boosting.py::test_sparse_classification", "sklearn/decomposition/tests/test_pca.py::test_pca_params_validation[params0-ValueError-n_oversamples == 0, must be >= 1.]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[OrthogonalMatchingPursuit-params8]", "sklearn/cluster/tests/test_birch.py::test_n_samples_leaves_roots", "sklearn/utils/tests/test_validation.py::test_num_features[sparse_csr]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_does_not_overwrite_sample_weight[False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[True-False-RidgeClassifierCV-params7]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-True-RidgeCV-params6]", "sklearn/tree/tests/test_tree.py::test_balance_property[ExtraTreeRegressor-squared_error]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[SPARSE_FILTER-None-accuracy]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params13-ValueError-max_features == 0.0, must be > 0.0-DecisionTreeRegressor-DecisionTreeRegressor]", "sklearn/tree/tests/test_tree.py::test_1d_input[ExtraTreeRegressor]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_sample_weight_consistentcy[poisson-1.0-True]", "sklearn/tree/tests/test_tree.py::test_sparse[check_sparse_parameters-sparse-mix-ExtraTreeClassifier]", "sklearn/feature_extraction/tests/test_text.py::test_unused_parameters_warn[stop_words0-None-None-ngram_range0-None-char-'stop_words'-'analyzer'-!= 'word'-TfidfVectorizer]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[numeric-float64-Float64]", "sklearn/feature_extraction/tests/test_text.py::test_unused_parameters_warn[None-<lambda>-None-ngram_range1-None-char-'tokenizer'-'analyzer'-!= 'word'-HashingVectorizer]", "sklearn/preprocessing/tests/test_discretization.py::test_fit_transform_n_bins_array[kmeans-expected1]", "sklearn/cluster/tests/test_spectral.py::test_spectral_params_validation[input11-params11-ValueError-degree == -1, must be >= 1]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingClassifier-X1-y1-params12-ValueError-Invalid va]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_overrided_gram_matrix", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[ExtraTreeRegressor-reg_small-absolute_error]", "sklearn/tree/tests/test_tree.py::test_multioutput", "sklearn/decomposition/tests/test_pca.py::test_pca_score[full]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[DecisionTreeRegressor-sparse-pos-friedman_mse]", "sklearn/tree/tests/test_tree.py::test_sparse[check_sparse_parameters-zeros-DecisionTreeRegressor]", "sklearn/cross_decomposition/tests/test_pls.py::test_scale_and_stability[X4-Y4-PLSRegression]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_warm_start_sparse[GradientBoostingRegressor]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[BayesianRidge-params6]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_best_score[3-ridge1-make_classification]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[array-float]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingClassifier-X1-y1-params33-ValueError-max_leaf_n]", "sklearn/decomposition/tests/test_pca.py::test_pca[1-arpack]", "sklearn/tree/tests/test_tree.py::test_prune_tree_classifier_are_subtrees[DecisionTreeClassifier-sparse-pos-gini]", "sklearn/cluster/tests/test_dbscan.py::test_dbscan_sparse_precomputed_different_eps", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[DecisionTreeRegressor-multilabel-friedman_mse]", "sklearn/decomposition/tests/test_pca.py::test_pca_explained_variance_empirical[arpack-correlated-data]", "sklearn/tree/tests/test_tree.py::test_prune_single_node_tree", "sklearn/ensemble/tests/test_gradient_boosting.py::test_classification_synthetic[exponential]", "sklearn/cluster/tests/test_dbscan.py::test_dbscan_params_validation[params4-ValueError-min_samples == -2, must be >= 1.]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params10-ValueError-min_weight_fraction_leaf == 0.6, must be <= 0.5-DecisionTreeRegressor-DecisionTreeRegressor]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape1-asarray-eigen]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[list-float]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_warm_start_oob[GradientBoostingRegressor]", "sklearn/tree/tests/test_tree.py::test_class_weight_errors[ExtraTreeClassifier]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[DecisionTreeRegressor-zeros-absolute_error]", "sklearn/tree/tests/test_tree.py::test_diabetes_overfit[squared_error-DecisionTreeRegressor-DecisionTreeRegressor]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-csr_matrix-sample_weight1-True]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[DecisionTreeRegressor-sparse-mix-friedman_mse]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gradient_boosting_validation_fraction", "sklearn/tree/tests/test_tree.py::test_poisson_zero_nodes[2]", "sklearn/feature_extraction/tests/test_text.py::test_pickling_vectorizer", "sklearn/feature_extraction/tests/test_text.py::test_non_unique_vocab", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_family_argument[inverse-gaussian-instance3]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-ridgecv-False]", "sklearn/decomposition/tests/test_pca.py::test_pca_inverse[True-arpack]", "sklearn/preprocessing/tests/test_discretization.py::test_numeric_stability[8]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[svd-svd-svd-True]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_zero_estimator_reg", "sklearn/utils/tests/test_validation.py::test_get_feature_names_numpy", "sklearn/feature_extraction/tests/test_text.py::test_get_feature_names_deprecated", "sklearn/cross_decomposition/tests/test_pls.py::test_n_components_bounds[0-ValueError-n_components == 0, must be >= 1.-CCA]", "sklearn/decomposition/tests/test_pca.py::test_pca_validation[arpack-2-must be strictly less than min-data0]", "sklearn/tree/tests/test_tree.py::test_sparse_input[toy-DecisionTreeClassifier]", "sklearn/utils/tests/test_validation.py::test_check_array_on_mock_dataframe", "sklearn/tree/tests/test_tree.py::test_sparse_input[zeros-ExtraTreeClassifier]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[float64-float64-Int16]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_sample_weight_consistentcy[gamma-0.0-False]", "sklearn/utils/tests/test_validation.py::test_as_float_array_nan[X1]", "sklearn/decomposition/tests/test_pca.py::test_pca_inverse[False-randomized]", "sklearn/linear_model/tests/test_ridge.py::test_raises_value_error_if_sample_weights_greater_than_1d", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[LassoCV-params1]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_error[True]", "sklearn/cluster/tests/test_spectral.py::test_spectral_clustering[cluster_qr-lobpcg]", "sklearn/feature_extraction/tests/test_text.py::test_vectorizer_string_object_as_input[HashingVectorizer]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-array-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[True-shape0]", "sklearn/cluster/tests/test_spectral.py::test_spectral_params_validation[input6-params6-ValueError-gamma == -1, must be >= 1]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape0-asarray-svd]", "sklearn/decomposition/tests/test_pca.py::test_pca_inverse[True-full]", "sklearn/ensemble/tests/test_weight_boosting.py::test_adaboostclassifier_without_sample_weight[SAMME.R]", "sklearn/cluster/tests/test_birch.py::test_birch_params_validation[params5-ValueError-branching_factor == -2, must be > 1.]", "sklearn/utils/tests/test_validation.py::test_check_sparse_pandas_sp_format[csr]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge[sparse_cg]", "sklearn/tree/tests/test_tree.py::test_check_value_ndarray", "sklearn/preprocessing/tests/test_discretization.py::test_inverse_transform[ordinal-uniform-expected_inv0]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_params_validation[params0-ValueError-alpha == -1, must be >= 0.0]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match_cholesky", "sklearn/linear_model/_glm/tests/test_glm.py::test_tags[estimator1-True]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_early_stopping_stratified", "sklearn/tree/tests/test_tree.py::test_regression_toy[poisson-DecisionTreeRegressor]", "sklearn/utils/tests/test_validation.py::test_num_features[array]", "sklearn/tree/tests/test_tree.py::test_apply_path_readonly_all_trees[ExtraTreeRegressor]", "sklearn/tree/tests/test_tree.py::test_sparse_input[toy-ExtraTreeClassifier]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[DecisionTreeRegressor-sparse-neg-absolute_error]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params8-ValueError-tol == 0.0, must be > 0.0-TweedieRegressor]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-ridgecv-False]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[ExtraTreeRegressor-sparse-pos-squared_error]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-dense-float64-float64]", "sklearn/utils/tests/test_validation.py::test_check_array_dtype_warning", "sklearn/decomposition/tests/test_pca.py::test_pca_score[auto]", "sklearn/utils/tests/test_validation.py::test_as_float_array", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_custom_scoring[SPARSE_FILTER-cv1]", "sklearn/tree/tests/test_tree.py::test_criterion_deprecated[mse-squared_error-DecisionTreeRegressor]", "sklearn/feature_extraction/tests/test_text.py::test_callable_analyzer_error[filename-FileNotFoundError--HashingVectorizer]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_readonly_data", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape0-asarray-eigen]", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_not_equals[csr_matrix]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-8-asarray-svd]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[ExtraTreeRegressor-multilabel-squared_error]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-csr_matrix-None-False]", "sklearn/cross_decomposition/tests/test_pls.py::test_singular_value_helpers[1-100-10]", "sklearn/ensemble/tests/test_weight_boosting.py::test_sparse_regression", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-ridgecv-True]", "sklearn/tree/tests/test_tree.py::test_public_apply_all_trees[DecisionTreeRegressor]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-20-csr_matrix-svd]", "sklearn/tree/tests/test_tree.py::test_public_apply_all_trees[ExtraTreeRegressor]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[cholesky]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[True-shape1]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[asarray-nan-y-True-Input y contains NaN]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[True-shape0]", "sklearn/tree/tests/test_tree.py::test_sparse_input_reg_trees[diabetes-ExtraTreeRegressor]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-sparse_cg-False]", "sklearn/cluster/tests/test_dbscan.py::test_dbscan_params_validation[params0-ValueError-eps == -1.0, must be > 0.0.]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_warm_start_smaller_n_estimators[GradientBoostingClassifier]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_sparse_no_exception", "sklearn/tree/tests/test_tree.py::test_sparse[check_sparse_parameters-zeros-ExtraTreeClassifier]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-sag-False]", "sklearn/tree/tests/test_tree.py::test_sparse_input[clf_small-ExtraTreeRegressor]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_warm_start", "sklearn/decomposition/tests/test_pca.py::test_pca_explained_variance_empirical[auto-random-data]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-float16-float64]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_symbol_labels", "sklearn/decomposition/tests/test_pca.py::test_pca_dim", "sklearn/cross_decomposition/tests/test_pls.py::test_scale_and_stability[X0-Y0-PLSCanonical]", "sklearn/preprocessing/tests/test_discretization.py::test_inverse_transform[onehot-dense-kmeans-expected_inv1]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-dense-float64-float32]", "sklearn/tree/tests/test_tree.py::test_prune_tree_classifier_are_subtrees[DecisionTreeClassifier-zeros-entropy]", "sklearn/linear_model/tests/test_ridge.py::test_primal_dual_relationship", "sklearn/utils/tests/test_validation.py::test_check_scalar_invalid[4-test_name5-int-2-4-left-err_msg7]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape1-csr_matrix-eigen]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[float16-float32]", "sklearn/tree/tests/test_tree.py::test_criterion_deprecated[mse-squared_error-ExtraTreeRegressor]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingRegressor-X0-y0-params10-ValueError-max_featur]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_models_cv_fit_with_loky[LassoCV]", "sklearn/tree/tests/test_tree.py::test_decision_tree_regressor_sample_weight_consistentcy[poisson]", "sklearn/feature_extraction/tests/test_text.py::test_vectorizer_max_features[TfidfVectorizer]", "sklearn/feature_extraction/tests/test_text.py::test_feature_names[get_feature_names_out]", "sklearn/cross_decomposition/tests/test_pls.py::test_convergence_fail", "sklearn/decomposition/tests/test_pca.py::test_n_components_none[data0-randomized-4]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-sparse_cg-False]", "sklearn/preprocessing/tests/test_discretization.py::test_fit_transform_n_bins_array[uniform-expected0]", "sklearn/linear_model/tests/test_ridge.py::test_positive_ridge_loss[1.0]", "sklearn/tree/tests/test_tree.py::test_balance_property[DecisionTreeRegressor-squared_error]", "sklearn/utils/tests/test_validation.py::test_num_features[tuple]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[DecisionTreeRegressor-reg_small-absolute_error]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_path_positive", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-ridgecv-True]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_float_class_labels", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[True-0.5-False]", "sklearn/ensemble/tests/test_weight_boosting.py::test_regression_toy", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[ordinal-float16-float16]", "sklearn/feature_extraction/tests/test_text.py::test_vectorizer", "sklearn/tree/tests/test_tree.py::test_sparse[check_sparse_parameters-sparse-neg-DecisionTreeClassifier]", "sklearn/linear_model/_glm/tests/test_glm.py::test_tags[estimator2-True]", "sklearn/feature_extraction/tests/test_text.py::test_unicode_decode_error", "sklearn/feature_extraction/tests/test_text.py::test_vectorizer_unicode", "sklearn/preprocessing/tests/test_discretization.py::test_same_min_max[quantile]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_sample_weight_consistentcy[poisson-0.0-True]", "sklearn/utils/tests/test_validation.py::test_check_array_memmap[True]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[DecisionTreeRegressor-multilabel-squared_error]", "sklearn/tree/tests/test_tree.py::test_regression_toy[friedman_mse-DecisionTreeRegressor]", "sklearn/preprocessing/tests/test_discretization.py::test_inverse_transform[onehot-quantile-expected_inv2]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[DecisionTreeRegressor-iris-friedman_mse]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_float_precision", "sklearn/utils/tests/test_validation.py::test_check_scalar_invalid[4-test_name6-int-2-4-bad parameter value-err_msg8]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-ridgecv-False]", "sklearn/tree/tests/test_tree.py::test_sparse_input[multilabel-DecisionTreeRegressor]", "sklearn/cross_decomposition/tests/test_pls.py::test_singular_value_helpers[1-100-200]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-csr_matrix-None-True]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_quantile_loss", "sklearn/feature_extraction/tests/test_text.py::test_countvectorizer_custom_vocabulary_pipeline", "sklearn/decomposition/tests/test_pca.py::test_pca_explained_variance_empirical[auto-correlated-data]", "sklearn/tree/tests/test_tree.py::test_min_weight_leaf_split_level[DecisionTreeClassifier]", "sklearn/cluster/tests/test_spectral.py::test_spectral_unknown_assign_labels", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[dtype0-float32-Int16]", "sklearn/tree/tests/test_tree.py::test_sparse_input[toy-ExtraTreeRegressor]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params13-ValueError-max_features == 0.0, must be > 0.0-ExtraTreeClassifier-ExtraTreeClassifier]", "sklearn/cluster/tests/test_dbscan.py::test_dbscan_params_validation[params5-ValueError-leaf_size == 0, must be >= 1.]", "sklearn/tree/tests/test_tree.py::test_importances", "sklearn/feature_extraction/tests/test_text.py::test_tfidf_transformer_sparse", "sklearn/decomposition/tests/test_pca.py::test_whitening[randomized-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_cv_store_cv_values[None]", "sklearn/linear_model/_glm/tests/test_glm.py::test_poisson_regression_family", "sklearn/linear_model/tests/test_coordinate_descent.py::test_param_invalid[params4-ValueError-tol == -1.0, must be >= 0.]", "sklearn/cluster/tests/test_dbscan.py::test_dbscan_core_samples_toy[brute]", "sklearn/decomposition/tests/test_pca.py::test_pca_score_consistency_solvers[randomized]", "sklearn/decomposition/tests/test_pca.py::test_pca_zero_noise_variance_edge_cases[full]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-csr_matrix-None-True]", "sklearn/ensemble/tests/test_weight_boosting.py::test_gridsearch", "sklearn/decomposition/tests/test_pca.py::test_pca_validation[auto--1-n_components={}L? must be between {}L? and min\\\\(n_samples, n_features\\\\)={}L? with svd_solver=\\\\'{}\\\\'-data1]", "sklearn/feature_extraction/tests/test_text.py::test_to_ascii", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-saga]", "sklearn/preprocessing/tests/test_discretization.py::test_numeric_stability[4]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_non_uniform_weights_toy_edge_case_reg", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[1.0-True-lbfgs]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_valid[csr_matrix-inf-False]", "sklearn/linear_model/_glm/tests/test_glm.py::test_tags[estimator0-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape0-csr_matrix-eigen]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[ordinal-float64-float16]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_warm_start_n_estimators[GradientBoostingRegressor]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_error_test[sag]", "sklearn/decomposition/tests/test_pca.py::test_pca_check_projection_list[randomized]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-cholesky-False]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-None-float64]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[1.0-False]", "sklearn/decomposition/tests/test_pca.py::test_pca[2-full]", "sklearn/tree/tests/test_tree.py::test_decision_path_hardcoded", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[True-shape4]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-sag-False]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params20-ValueError-ccp_alpha == -1.0, must be >= 0.0-ExtraTreeRegressor-ExtraTreeRegressor]", "sklearn/preprocessing/tests/test_discretization.py::test_32_equal_64[onehot-dense-float32]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[LinearRegression-params7]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params10-ValueError-min_weight_fraction_leaf == 0.6, must be <= 0.5-ExtraTreeRegressor-ExtraTreeRegressor]", "sklearn/feature_extraction/tests/test_text.py::test_tfidf_vectorizer_type[int64-float64-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-lbfgs]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[DecisionTreeRegressor-sparse-neg-squared_error]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_grid_search[False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-ridgecv-True]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-None-float16]", "sklearn/tree/tests/test_tree.py::test_diabetes_underfit[friedman_mse-15-mean_squared_error-60-DecisionTreeRegressor-DecisionTreeRegressor]", "sklearn/preprocessing/tests/test_discretization.py::test_inverse_transform[onehot-dense-quantile-expected_inv2]", "sklearn/tree/tests/test_tree.py::test_sparse[check_sparse_criterion-sparse-pos-DecisionTreeRegressor]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[DENSE_FILTER-None-_accuracy_callable]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingRegressor-X0-y0-params12-ValueError-Invalid va]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_sample_weight_consistentcy[normal-0.0-True]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_fit_intercept_argument[1]", "sklearn/feature_extraction/tests/test_text.py::test_transformer_idf_setter", "sklearn/tree/tests/test_tree.py::test_different_endianness_joblib_pickle", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingClassifier-X1-y1-params14-TypeError-verbose mu]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_coef_shape_not_zero", "sklearn/tree/tests/test_tree.py::test_sparse[check_sparse_criterion-sparse-neg-DecisionTreeClassifier]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-array-sample_weight1-False]", "sklearn/tree/tests/test_tree.py::test_prune_tree_classifier_are_subtrees[DecisionTreeClassifier-toy-entropy]", "sklearn/decomposition/tests/test_pca.py::test_pca_validation[auto-1.0-must be of type int-data0]", "sklearn/tree/tests/test_tree.py::test_sparse[check_sparse_parameters-sparse-neg-ExtraTreeClassifier]", "sklearn/feature_extraction/tests/test_text.py::test_tfidf_no_smoothing", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[float64-float64-UInt8]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-csr_matrix-sample_weight1-True]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[short-int16-integer]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape0-asarray-eigen]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params13-ValueError-max_features == 0.0, must be > 0.0-ExtraTreeRegressor-ExtraTreeRegressor]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_max_feature_auto", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape1-csr_matrix-svd]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_set_order_sparse[F-C]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[svd-svd-svd-False]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbr_degenerate_feature_importances", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[lsqr-False]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params12-ValueError-max_features == 0, must be >= 1-ExtraTreeClassifier-ExtraTreeClassifier]", "sklearn/feature_extraction/tests/test_text.py::test_vectorizer_inverse_transform[TfidfVectorizer]", "sklearn/decomposition/tests/test_pca.py::test_pca_sanity_noise_variance[auto]", "sklearn/cross_decomposition/tests/test_pls.py::test_scale_and_stability[X4-Y4-PLSCanonical]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingClassifier-X1-y1-params24-ValueError-min_sample]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_n_features_deprecation[GradientBoostingRegressor]", "sklearn/cross_decomposition/tests/test_pls.py::test_n_components_bounds[0-ValueError-n_components == 0, must be >= 1.-PLSCanonical]", "sklearn/ensemble/tests/test_weight_boosting.py::test_adaboost_params_validation[AdaBoostRegressor-X1-y1-params3-ValueError-learning_rate == -1, must be > 0.]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-True-ElasticNet-params2]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_criterion_mse_deprecated[GradientBoostingClassifier]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-sparse_cg]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_max_leaf_nodes_max_depth[GradientBoostingClassifier]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[list-str]", "sklearn/utils/tests/test_validation.py::test_check_feature_names_in", "sklearn/ensemble/tests/test_gradient_boosting.py::test_wrong_type_loss_function[GradientBoostingClassifier-huber]", "sklearn/utils/tests/test_validation.py::test_check_array_dtype_stability", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[False-shape0]", "sklearn/utils/tests/test_validation.py::test_check_is_fitted_attributes", "sklearn/utils/tests/test_validation.py::test_suppress_validation", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_alphas_validation[params1-ValueError-alphas\\\\[0\\\\] == -0.1, must be > 0.0-RidgeClassifierCV]", "sklearn/feature_extraction/tests/test_text.py::test_vectorizer_params_validation[params4-ValueError-max_df == 2.0, must be <= 1.0.]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_warm_start_convergence_with_regularizer_decrement", "sklearn/feature_extraction/tests/test_text.py::test_vectorizer_vocab_clone", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-dense-float32-float16]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gradient_boosting_init_wrong_methods[estimator0-predict_proba]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-saga-False]", "sklearn/decomposition/tests/test_pca.py::test_pca_score_consistency_solvers[arpack]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_path_parameters", "sklearn/cluster/tests/test_birch.py::test_birch_params_validation[params8-TypeError-n_clusters should be an instance of ClusterMixin or an int]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingRegressor-X0-y0-params16-ValueError-validation]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-20-asarray-eigen]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[ExtraTreeRegressor-toy-friedman_mse]", "sklearn/cross_decomposition/tests/test_pls.py::test_sanity_check_pls_canonical", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.01-True-lbfgs]", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_valid[True-insignificant pos]", "sklearn/decomposition/tests/test_pca.py::test_infer_dim_3", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[auto-svd-eigen-True]", "sklearn/decomposition/tests/test_pca.py::test_infer_dim_2", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[False-0.5-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_store_cv_values[_mean_squared_error_callable]", "sklearn/ensemble/tests/test_weight_boosting.py::test_classification_toy[SAMME]", "sklearn/preprocessing/tests/test_discretization.py::test_numeric_stability[5]", "sklearn/tree/tests/test_tree.py::test_public_apply_all_trees[ExtraTreeClassifier]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[0.1-True]", "sklearn/preprocessing/tests/test_discretization.py::test_kbinsdiscretizer_subsample_values[0]", "sklearn/tree/tests/test_tree.py::test_criterion_copy", "sklearn/ensemble/tests/test_weight_boosting.py::test_sample_weights_infinite", "sklearn/tree/tests/test_tree.py::test_prune_tree_classifier_are_subtrees[ExtraTreeClassifier-clf_small-entropy]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params2-ValueError-min_samples_leaf == 0, must be >= 1-ExtraTreeClassifier-ExtraTreeClassifier]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gradient_boosting_with_init_pipeline", "sklearn/tree/tests/test_tree.py::test_diabetes_underfit[poisson-15-mean_poisson_deviance-30-ExtraTreeRegressor-ExtraTreeRegressor]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[ExtraTreeRegressor-sparse-pos-poisson]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_multi_task_lasso_and_enet", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[float64-float64-UInt16]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[int_-intp-integer]", "sklearn/preprocessing/tests/test_discretization.py::test_redundant_bins[quantile-expected_bin_edges0]", "sklearn/utils/tests/test_validation.py::test_check_fit_params[None]", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_invalid[all negative]", "sklearn/cluster/tests/test_spectral.py::test_spectral_params_validation[input9-params9-ValueError-n_neighbors == 0, must be >= 1]", "sklearn/decomposition/tests/test_pca.py::test_pca_zero_noise_variance_edge_cases[randomized]", "sklearn/cross_decomposition/tests/test_pls.py::test_attibutes_shapes[PLSRegression]", "sklearn/feature_extraction/tests/test_text.py::test_unused_parameters_warn[stop_words0-None-None-ngram_range0-None-char-'stop_words'-'analyzer'-!= 'word'-CountVectorizer]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[svd-True]", "sklearn/utils/tests/test_validation.py::test_check_non_negative[asarray]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[csr_matrix-inf-X-allow-nan-Input X contains infinity]", "sklearn/cross_decomposition/tests/test_pls.py::test_scale_and_stability[X4-Y4-PLSSVD]", "sklearn/ensemble/tests/test_weight_boosting.py::test_adaboost_params_validation[AdaBoostClassifier-X0-y0-params1-ValueError-n_estimators == 0, must be >= 1]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[numeric-float64-Float32]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[csr_matrix-nan-y-True-Input y contains NaN]", "sklearn/cluster/tests/test_dbscan.py::test_dbscan_sparse_precomputed[True]", "sklearn/tree/tests/test_tree.py::test_public_apply_sparse_trees[DecisionTreeRegressor]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[ExtraTreeRegressor-iris-friedman_mse]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_non_float_y[Lasso]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-array-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-8-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_best_score[3-ridge0-make_regression]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_warm_start_sparse[GradientBoostingClassifier]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_set_order_dense[C-C]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_family_argument[poisson-instance1]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape0-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-lsqr]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-csr_matrix-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape1-csr_matrix-svd]", "sklearn/preprocessing/tests/test_discretization.py::test_same_min_max[kmeans]", "sklearn/utils/tests/test_validation.py::test_check_dataframe_mixed_float_dtypes", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params12-ValueError-max_features == 0, must be >= 1-ExtraTreeRegressor-ExtraTreeRegressor]", "sklearn/utils/tests/test_validation.py::test_check_scalar_invalid[4-test_name8-int-2-None-right-err_msg10]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params14-ValueError-max_features == 1.1, must be <= 1.0-DecisionTreeRegressor-DecisionTreeRegressor]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingClassifier-X1-y1-params4-ValueError-Loss 'foob]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_scalars[str]", "sklearn/utils/tests/test_validation.py::test_check_array_links_to_imputer_doc_only_for_X[asarray-sample_weight]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[True-shape3]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_coordinate_descent[MultiTaskLasso-2-kwargs2]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-20-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-array-sample_weight1-True]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-None-float32]", "sklearn/tree/tests/test_tree.py::test_no_sparse_y_support[ExtraTreeClassifier]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[csr_matrix-inf-X-True-Input X contains infinity]", "sklearn/feature_extraction/tests/test_text.py::test_tf_transformer_feature_names_out", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-20-csr_matrix-eigen]", "sklearn/cluster/tests/test_spectral.py::test_spectral_params_validation[input10-params10-ValueError-eigen_tol == -1, must be >= 0]", "sklearn/cross_decomposition/tests/test_pls.py::test_attibutes_shapes[PLSCanonical]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[DecisionTreeRegressor-clf_small-poisson]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape1-asarray-svd]", "sklearn/tree/tests/test_tree.py::test_with_only_one_non_constant_features", "sklearn/utils/tests/test_validation.py::test_check_array_dtype_numeric_errors[X2]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params20-ValueError-ccp_alpha == -1.0, must be >= 0.0-DecisionTreeRegressor-DecisionTreeRegressor]", "sklearn/cluster/tests/test_dbscan.py::test_dbscan_precomputed_metric_with_initial_rows_zero", "sklearn/decomposition/tests/test_pca.py::test_pca_singular_values[randomized]", "sklearn/utils/tests/test_validation.py::test_check_array_numeric_warns[X3]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lassoCV_does_not_set_precompute[auto-False]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[ubyte-uint8-unsignedinteger]", "sklearn/decomposition/tests/test_pca.py::test_n_components_mle[auto]", "sklearn/feature_extraction/tests/test_text.py::test_vectorizer_pipeline_cross_validation", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-False-ElasticNet-params3]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[DENSE_FILTER-cv1-accuracy]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_sample_weights", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingClassifier-X1-y1-params21-ValueError-tol == 0.0]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_toy", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[ExtraTreeRegressor-sparse-mix-friedman_mse]", "sklearn/decomposition/tests/test_pca.py::test_pca_validation[auto--1-n_components={}L? must be between {}L? and min\\\\(n_samples, n_features\\\\)={}L? with svd_solver=\\\\'{}\\\\'-data0]", "sklearn/ensemble/tests/test_weight_boosting.py::test_adaboost_consistent_predict[SAMME]", "sklearn/decomposition/tests/test_pca.py::test_pca_explained_variance_empirical[randomized-random-data]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[sag]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[ExtraTreeRegressor-sparse-neg-absolute_error]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_params_validation[params4-ValueError-tol == -1.0, must be >= 0.]", "sklearn/preprocessing/tests/test_discretization.py::test_invalid_encode_option", "sklearn/decomposition/tests/test_pca.py::test_pca_singular_values_consistency[arpack]", "sklearn/cross_decomposition/tests/test_pls.py::test_singular_value_helpers[7-100-10]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-sparse_cg-True]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_iris[None-0.5]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-dense-float16-float32]", "sklearn/utils/tests/test_validation.py::test_check_array", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-saga-False]", "sklearn/utils/tests/test_validation.py::test_check_array_links_to_imputer_doc_only_for_X[csr_matrix-y]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_sparse_input[coo_matrix-GradientBoostingClassifier]", "sklearn/cross_decomposition/tests/test_pls.py::test_scale_and_stability[X3-Y3-CCA]", "sklearn/tree/tests/test_tree.py::test_sparse[check_sparse_criterion-sparse-mix-DecisionTreeClassifier]", "sklearn/ensemble/tests/test_weight_boosting.py::test_adaboost_params_validation[AdaBoostRegressor-X1-y1-params4-ValueError-learning_rate == 0, must be > 0.]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[ElasticNet-params4]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-ridgecv-True]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[ExtraTreeRegressor-diabetes-absolute_error]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-saga-False]", "sklearn/tree/tests/test_tree.py::test_poisson_zero_nodes[0]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_ridge_consistency[True-0.1]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[DecisionTreeRegressor-toy-friedman_mse]", "sklearn/decomposition/tests/test_pca.py::test_pca_inverse[False-full]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_ridge_consistency[False-1000000.0]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_copy_X_True[False]", "sklearn/feature_extraction/tests/test_text.py::test_vectorizers_invalid_ngram_range[vec0]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_max_feature_regression", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_error[bad]", "sklearn/cross_decomposition/tests/test_pls.py::test_n_components_bounds[4-ValueError-n_components == 4, must be <= 3.-PLSCanonical]", "sklearn/cross_decomposition/tests/test_pls.py::test_n_components_bounds[4-ValueError-n_components == 4, must be <= 3.-CCA]", "sklearn/decomposition/tests/test_pca.py::test_pca_svd_solver_auto[data2-50-full]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.01-True-auto]", "sklearn/feature_extraction/tests/test_text.py::test_pickling_built_processors[build_preprocessor]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[False-shape4]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[ExtraTreeRegressor-iris-absolute_error]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_log_regression[family4-True]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_link_argument[identity-instance0]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape0-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-sparse_cg-True]", "sklearn/cross_decomposition/tests/test_pls.py::test_scale_and_stability[X1-Y1-PLSSVD]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingRegressor-X0-y0-params27-ValueError-min_sample]", "sklearn/feature_extraction/tests/test_text.py::test_tfidfvectorizer_export_idf", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[series-float]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_log_regression[family0-False]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_warm_start_n_estimators[GradientBoostingClassifier]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_multitarget", "sklearn/feature_extraction/tests/test_text.py::test_callable_analyzer_change_behavior[file-<lambda>0-TfidfVectorizer]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-csr_matrix-sample_weight1-True]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_link_argument[log-instance1]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[ordinal-float16-float32]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[ExtraTreeRegressor-digits-squared_error]", "sklearn/decomposition/tests/test_pca.py::test_pca_deterministic_output[arpack]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_ridge_consistency[True-1000000.0]", "sklearn/ensemble/tests/test_weight_boosting.py::test_multidimensional_X", "sklearn/cross_decomposition/tests/test_pls.py::test_one_component_equivalence", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingRegressor-X0-y0-params2-ValueError-n_estimato]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[asarray-nan--True-Input contains NaN]", "sklearn/tree/tests/test_tree.py::test_min_weight_fraction_leaf_with_min_samples_leaf_on_dense_input[DecisionTreeClassifier]", "sklearn/cluster/tests/test_dbscan.py::test_dbscan_no_core_samples", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params20-ValueError-ccp_alpha == -1.0, must be >= 0.0-ExtraTreeClassifier-ExtraTreeClassifier]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_regression_dataset[0.5-huber]", "sklearn/preprocessing/tests/test_discretization.py::test_transform_outside_fit_range[quantile]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_param_invalid[params0-ValueError-alpha == -1, must be >= 0.0]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params7-ValueError-min_samples_split == 1.1, must be <= 1.0-ExtraTreeClassifier-ExtraTreeClassifier]", "sklearn/cluster/tests/test_spectral.py::test_spectral_params_validation[input0-params0-ValueError-n_clusters == -1, must be >= 1]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-csr_matrix-sample_weight1-True]", "sklearn/feature_extraction/tests/test_text.py::test_callable_analyzer_change_behavior[file-<lambda>0-CountVectorizer]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[DecisionTreeRegressor-sparse-neg-friedman_mse]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[True-shape3]", "sklearn/tree/tests/test_tree.py::test_decision_tree_regressor_sample_weight_consistentcy[absolute_error]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[DecisionTreeRegressor-toy-absolute_error]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[False-0-True]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params14-ValueError-max_features == 1.1, must be <= 1.0-ExtraTreeRegressor-ExtraTreeRegressor]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_wrong_type_loss_function[GradientBoostingRegressor-exponential]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-array-None-True]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_dtype_casting", "sklearn/tree/tests/test_tree.py::test_sparse[check_sparse_parameters-sparse-neg-ExtraTreeRegressor]", "sklearn/feature_extraction/tests/test_text.py::test_vectorizer_pipeline_grid_selection", "sklearn/cross_decomposition/tests/test_pls.py::test_sanity_check_pls_regression_constant_column_Y", "sklearn/cluster/tests/test_dbscan.py::test_dbscan_feature", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingClassifier-X1-y1-params10-ValueError-max_featur]", "sklearn/feature_extraction/tests/test_text.py::test_tfidf_vectorizer_type[int32-float64-True]", "sklearn/utils/tests/test_validation.py::test_ordering", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-ridgecv-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_set_order_dense[C-F]", "sklearn/cluster/tests/test_spectral.py::test_discretize[50]", "sklearn/tree/tests/test_tree.py::test_prune_tree_classifier_are_subtrees[ExtraTreeClassifier-iris-gini]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[ExtraTreeRegressor-digits-friedman_mse]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[DecisionTreeRegressor-zeros-poisson]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_copy_X_True[True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_convergence_fail", "sklearn/linear_model/tests/test_ridge.py::test_ridge_best_score[None-ridge0-make_regression]", "sklearn/linear_model/tests/test_ridge.py::test_positive_ridge_loss[0.1]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_n_features_deprecation[GradientBoostingClassifier]", "sklearn/linear_model/_glm/tests/test_glm.py::test_gamma_regression_family", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape1-csr_matrix-eigen]", "sklearn/cluster/tests/test_dbscan.py::test_dbscan_callable", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-float64-float64]", "sklearn/tree/tests/test_tree.py::test_sparse_input_reg_trees[reg_small-DecisionTreeRegressor]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[True-shape2]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_cv", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[DecisionTreeRegressor-zeros-friedman_mse]", "sklearn/feature_extraction/tests/test_text.py::test_callable_analyzer_reraise_error[CountVectorizer]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-lsqr-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_param_invalid[params2-ValueError-l1_ratio == 2, must be <= 1.0]", "sklearn/linear_model/tests/test_ridge.py::test_X_CenterStackOp[n_col2]", "sklearn/tree/tests/test_tree.py::test_sparse[check_sparse_criterion-sparse-mix-ExtraTreeClassifier]", "sklearn/preprocessing/tests/test_discretization.py::test_inverse_transform[ordinal-quantile-expected_inv2]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_log_regression[family0-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-csr_matrix-sample_weight1-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[True-0.5-True]", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_valid[True-insignificant neg float64]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params2-ValueError-min_samples_leaf == 0, must be >= 1-ExtraTreeRegressor-ExtraTreeRegressor]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_path_unknown_parameter[lasso_path]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-ridgecv-False]", "sklearn/decomposition/tests/test_pca.py::test_n_components_mle[full]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[DecisionTreeRegressor-zeros-squared_error]", "sklearn/ensemble/tests/test_weight_boosting.py::test_adaboostclassifier_without_sample_weight[SAMME]", "sklearn/tree/tests/test_tree.py::test_poisson_vs_mse", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_family_argument[gamma-instance2]", "sklearn/tree/tests/test_tree.py::test_sparse[check_sparse_criterion-sparse-mix-ExtraTreeRegressor]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-csr_matrix-sample_weight1-False]", "sklearn/decomposition/tests/test_pca.py::test_whitening[full-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[0.01-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_precompute_invalid_argument", "sklearn/cluster/tests/test_birch.py::test_birch_params_validation[params9-ValueError-n_clusters == -3, must be >= 1.]", "sklearn/tree/tests/test_tree.py::test_diabetes_overfit[friedman_mse-ExtraTreeRegressor-ExtraTreeRegressor]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[DecisionTreeRegressor-sparse-pos-poisson]", "sklearn/preprocessing/tests/test_discretization.py::test_fit_transform[kmeans-expected1]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-sparse_cg-False]", "sklearn/utils/tests/test_validation.py::test_check_array_deprecated_matrix", "sklearn/preprocessing/tests/test_discretization.py::test_kbinsdiscretizer_subsample_warn", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingClassifier-X1-y1-params16-ValueError-validation]", "sklearn/tree/tests/test_tree.py::test_prune_tree_classifier_are_subtrees[DecisionTreeClassifier-toy-gini]", "sklearn/utils/tests/test_validation.py::test_check_array_numeric_warns[X1]", "sklearn/cross_decomposition/tests/test_pls.py::test_pls_canonical_basics", "sklearn/preprocessing/tests/test_discretization.py::test_percentile_numeric_stability", "sklearn/tree/tests/test_tree.py::test_explicit_sparse_zeros[ExtraTreeClassifier]", "sklearn/tree/tests/test_tree.py::test_prune_tree_classifier_are_subtrees[ExtraTreeClassifier-toy-entropy]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params7-ValueError-min_samples_split == 1.1, must be <= 1.0-DecisionTreeRegressor-DecisionTreeRegressor]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[ExtraTreeRegressor-diabetes-friedman_mse]", "sklearn/feature_extraction/tests/test_text.py::test_count_binary_occurrences[get_feature_names]", "sklearn/cross_decomposition/tests/test_pls.py::test_scale_and_stability[X2-Y2-PLSSVD]", "sklearn/tree/tests/test_tree.py::test_n_features_deprecated[DecisionTreeRegressor]", "sklearn/feature_extraction/tests/test_text.py::test_vectorizer_string_object_as_input[TfidfVectorizer]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_positive_constraint", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_multi_ridge_diabetes]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_int_alphas", "sklearn/cluster/tests/test_spectral.py::test_n_components", "sklearn/preprocessing/tests/test_discretization.py::test_32_equal_64[ordinal-float16]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[True-shape2]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_fit_intercept_sparse_error[saga]", "sklearn/cross_decomposition/tests/test_pls.py::test_scale_and_stability[X3-Y3-PLSRegression]", "sklearn/feature_extraction/tests/test_text.py::test_tf_idf_smoothing", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-lsqr-False]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[int-long-integer]", "sklearn/utils/tests/test_validation.py::test_check_is_fitted", "sklearn/tree/tests/test_tree.py::test_diabetes_underfit[squared_error-15-mean_squared_error-60-ExtraTreeRegressor-ExtraTreeRegressor]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params16-ValueError-max_leaf_nodes == 0, must be >= 2-DecisionTreeClassifier-DecisionTreeClassifier]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[ExtraTreeRegressor-clf_small-poisson]", "sklearn/feature_extraction/tests/test_text.py::test_tfidf_vectorizer_setter", "sklearn/cluster/tests/test_dbscan.py::test_dbscan_input_not_modified[minkowski-True]", "sklearn/tree/tests/test_tree.py::test_min_weight_fraction_leaf_with_min_samples_leaf_on_dense_input[ExtraTreeRegressor]", "sklearn/tree/tests/test_tree.py::test_sparse_input[sparse-mix-DecisionTreeRegressor]", "sklearn/decomposition/tests/test_pca.py::test_assess_dimension_bad_rank", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape1-csr_matrix-svd]", "sklearn/tree/tests/test_tree.py::test_diabetes_underfit[absolute_error-20-mean_squared_error-60-ExtraTreeRegressor-ExtraTreeRegressor]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-8-csr_matrix-svd]", "sklearn/feature_extraction/tests/test_text.py::test_countvectorizer_custom_token_pattern_with_several_group", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-20-asarray-eigen]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_sample_weight_consistentcy[gamma-0.0-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[LinearRegression-params13]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_set_order_dense[F-C]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_warm_start_argument[warm_start3]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params0-ValueError-max_iter == 0, must be >= 1-PoissonRegressor]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-8-csr_matrix-eigen]", "sklearn/tree/tests/test_tree.py::test_prune_tree_classifier_are_subtrees[ExtraTreeClassifier-digits-entropy]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_consistency[True-True-0.01-True]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[DecisionTreeRegressor-sparse-neg-poisson]", "sklearn/ensemble/tests/test_weight_boosting.py::test_error", "sklearn/linear_model/tests/test_ridge.py::test_ridgeclassifier_multilabel[RidgeClassifierCV-params2]", "sklearn/feature_extraction/tests/test_text.py::test_callable_analyzer_error[file-AttributeError-'str' object has no attribute 'read'-TfidfVectorizer]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-20-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-csr_matrix-sample_weight1-True]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[array-int]", "sklearn/feature_extraction/tests/test_text.py::test_tfidf_transformer_type[float32]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params9-ValueError-tol == 0, must be > 0.0-GeneralizedLinearRegressor]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_zero_estimator_clf", "sklearn/tree/tests/test_tree.py::test_1d_input[DecisionTreeClassifier]", "sklearn/tree/tests/test_tree.py::test_min_weight_leaf_split_level[ExtraTreeRegressor]", "sklearn/feature_extraction/tests/test_text.py::test_vectorizers_invalid_ngram_range[vec1]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_models_cv_fit_with_loky[ElasticNetCV]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[ExtraTreeRegressor-reg_small-poisson]", "sklearn/decomposition/tests/test_pca.py::test_pca_svd_solver_auto[data0-0.5-full]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-array-sample_weight1-False]", "sklearn/tree/tests/test_tree.py::test_sparse_input[sparse-mix-DecisionTreeClassifier]", "sklearn/tree/tests/test_tree.py::test_prune_tree_classifier_are_subtrees[DecisionTreeClassifier-clf_small-entropy]", "sklearn/tree/tests/test_tree.py::test_diabetes_underfit[poisson-15-mean_poisson_deviance-30-DecisionTreeRegressor-DecisionTreeRegressor]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-8-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-csr_matrix-None-False]", "sklearn/tree/tests/test_tree.py::test_different_bitness_pickle", "sklearn/decomposition/tests/test_pca.py::test_pca[1-full]", "sklearn/utils/tests/test_validation.py::test_check_is_fitted_with_attributes[list]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingClassifier-X1-y1-params23-ValueError-min_sample]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_max_leaf_nodes_max_depth[GradientBoostingRegressor]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-cholesky-False]", "sklearn/feature_extraction/tests/test_text.py::test_callable_analyzer_change_behavior[filename-<lambda>0-CountVectorizer]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-ridgecv-True]", "sklearn/utils/tests/test_validation.py::test_check_scalar_invalid[5-test_name3-int-2-4-neither-err_msg5]", "sklearn/cluster/tests/test_spectral.py::test_verbose[kmeans]", "sklearn/feature_extraction/tests/test_text.py::test_callable_analyzer_change_behavior[filename-<lambda>1-CountVectorizer]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-cholesky-False]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params3-ValueError-min_samples_leaf == 0.0, must be > 0-ExtraTreeRegressor-ExtraTreeRegressor]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape1-csr_matrix-svd]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gradient_boosting_with_init[regression]", "sklearn/cluster/tests/test_spectral.py::test_spectral_params_validation[input1-params1-ValueError-n_clusters == 0, must be >= 1]", "sklearn/utils/tests/test_validation.py::test_check_non_negative[csr_matrix]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[Lasso-params0]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_loss_alpha_error[params1-alpha == 0.0, must be > 0.0]", "sklearn/feature_extraction/tests/test_text.py::test_stop_word_validation_custom_preprocessor[TfidfVectorizer]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingRegressor-X0-y0-params19-ValueError-n_iter_no_]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_regression_dataset[0.5-squared_error]", "sklearn/decomposition/tests/test_pca.py::test_mle_simple_case", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[array-dict]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_serialization", "sklearn/preprocessing/tests/test_discretization.py::test_inverse_transform[onehot-kmeans-expected_inv1]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[single-float32-floating]", "sklearn/tree/tests/test_tree.py::test_prune_tree_classifier_are_subtrees[ExtraTreeClassifier-iris-entropy]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[lbfgs-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lassoCV_does_not_set_precompute[False-False]", "sklearn/feature_extraction/tests/test_text.py::test_stop_word_validation_custom_preprocessor[CountVectorizer]", "sklearn/cluster/tests/test_birch.py::test_birch_n_clusters_long_int", "sklearn/ensemble/tests/test_weight_boosting.py::test_adaboost_params_validation[AdaBoostClassifier-X0-y0-params3-ValueError-learning_rate == -1, must be > 0.]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[ExtraTreeRegressor-multilabel-friedman_mse]", "sklearn/tree/tests/test_tree.py::test_sparse_input[clf_small-DecisionTreeClassifier]", "sklearn/utils/tests/test_validation.py::test_check_array_links_to_imputer_doc_only_for_X[asarray-y]", "sklearn/cross_decomposition/tests/test_pls.py::test_singular_value_helpers[9-100-10]", "sklearn/decomposition/tests/test_pca.py::test_infer_dim_1", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[ElasticNetCV-params2]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gradient_boosting_init_wrong_methods[estimator1-predict]", "sklearn/tree/tests/test_tree.py::test_big_input", "sklearn/tree/tests/test_tree.py::test_prune_tree_classifier_are_subtrees[ExtraTreeClassifier-digits-gini]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params10-ValueError-min_weight_fraction_leaf == 0.6, must be <= 0.5-ExtraTreeClassifier-ExtraTreeClassifier]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_1d_multioutput_lasso_and_multitask_lasso_cv", "sklearn/decomposition/tests/test_pca.py::test_infer_dim_by_explained_variance[X0-0.95-2]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingRegressor-X0-y0-params4-ValueError-Loss 'foob]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingRegressor-X0-y0-params8-ValueError-The init p]", "sklearn/utils/tests/test_validation.py::test_retrieve_samples_from_non_standard_shape", "sklearn/tree/tests/test_tree.py::test_sparse[check_sparse_criterion-sparse-pos-ExtraTreeRegressor]", "sklearn/feature_extraction/tests/test_text.py::test_count_vectorizer_pipeline_grid_selection", "sklearn/preprocessing/tests/test_discretization.py::test_32_equal_64[ordinal-float32]", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_equals[array]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_scalars[float]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-ridgecv-True]", "sklearn/cross_decomposition/tests/test_pls.py::test_singular_value_helpers[5-100-200]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-sag-False]", "sklearn/utils/tests/test_validation.py::test_memmap", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[list-int]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_warm_start_clear[GradientBoostingClassifier]", "sklearn/decomposition/tests/test_pca.py::test_whitening[auto-True]", "sklearn/tree/tests/test_tree.py::test_class_weights[ExtraTreeClassifier]", "sklearn/feature_extraction/tests/test_text.py::test_callable_analyzer_error[file-AttributeError-'str' object has no attribute 'read'-CountVectorizer]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-False-RidgeClassifierCV-params7]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-sparse_cg-False]", "sklearn/tree/tests/test_tree.py::test_public_apply_sparse_trees[ExtraTreeClassifier]", "sklearn/feature_extraction/tests/test_text.py::test_count_vectorizer_max_features[get_feature_names_out]", "sklearn/cluster/tests/test_dbscan.py::test_dbscan_badargs[args1]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[ExtraTreeRegressor-toy-absolute_error]", "sklearn/cross_decomposition/tests/test_pls.py::test_singular_value_helpers[3-100-10]", "sklearn/linear_model/_glm/tests/test_glm.py::test_warm_start[False]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_regression_dataset[1.0-squared_error]", "sklearn/tree/tests/test_tree.py::test_prune_tree_classifier_are_subtrees[DecisionTreeClassifier-sparse-mix-gini]", "sklearn/feature_extraction/tests/test_text.py::test_feature_names[get_feature_names]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_no_exception[coo]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingClassifier-X1-y1-params15-TypeError-warm_start]", "sklearn/ensemble/tests/test_weight_boosting.py::test_adaboost_params_validation[AdaBoostRegressor-X1-y1-params0-ValueError-n_estimators == -1, must be >= 1]", "sklearn/cluster/tests/test_birch.py::test_birch_predict", "sklearn/tree/tests/test_tree.py::test_min_weight_leaf_split_level[ExtraTreeClassifier]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape1-asarray-svd]", "sklearn/tree/tests/test_tree.py::test_sparse[check_sparse_criterion-sparse-pos-ExtraTreeClassifier]", "sklearn/utils/tests/test_validation.py::test_check_array_dtype_numeric_errors[X3]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[float32-double]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[uint8-int8]", "sklearn/tree/tests/test_tree.py::test_sparse[check_sparse_criterion-zeros-DecisionTreeClassifier]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[ordinal-float64-float64]", "sklearn/feature_extraction/tests/test_text.py::test_unused_parameters_warn[None-None-None-ngram_range4-None-<lambda>-'ngram_range'-'analyzer'-is callable-TfidfVectorizer]", "sklearn/cluster/tests/test_spectral.py::test_spectral_params_validation[input7-params7-ValueError-gamma == 0, must be >= 1]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_warm_start_oob_switch[GradientBoostingClassifier]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-cholesky-False]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params6-ValueError-min_samples_split == 0.0, must be > 0.0-ExtraTreeRegressor-ExtraTreeRegressor]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[ExtraTreeRegressor-sparse-mix-absolute_error]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[ordinal-float32-float32]", "sklearn/feature_extraction/tests/test_text.py::test_countvectorizer_vocab_sets_when_pickling[get_feature_names_out]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[double-float64-floating]", "sklearn/decomposition/tests/test_pca.py::test_pca_check_projection_list[auto]", "sklearn/tree/tests/test_tree.py::test_classes_shape", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.1-False-auto]", "sklearn/tree/tests/test_tree.py::test_prune_tree_classifier_are_subtrees[ExtraTreeClassifier-sparse-neg-entropy]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_valid[asarray-inf-False]", "sklearn/tree/tests/test_tree.py::test_prune_tree_classifier_are_subtrees[DecisionTreeClassifier-sparse-neg-entropy]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[ordinal-float32-float64]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_probability_log", "sklearn/utils/tests/test_validation.py::test_check_array_numeric_warns[X0]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_sample_weight_consistentcy[poisson-1.0-False]", "sklearn/feature_extraction/tests/test_text.py::test_word_analyzer_unigrams[CountVectorizer]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-8-asarray-eigen]", "sklearn/cross_decomposition/tests/test_pls.py::test_svd_flip_1d", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[float16-half-floating]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-saga-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_sparse_input_dtype_enet_and_lassocv", "sklearn/decomposition/tests/test_pca.py::test_pca_explained_variance_empirical[randomized-correlated-data]", "sklearn/preprocessing/tests/test_discretization.py::test_inverse_transform[onehot-uniform-expected_inv0]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_sample_weight_consistentcy[normal-1.0-True]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[ExtraTreeRegressor-toy-squared_error]", "sklearn/cross_decomposition/tests/test_pls.py::test_pls_feature_names_out[PLSCanonical]", "sklearn/feature_extraction/tests/test_text.py::test_tie_breaking_sample_order_invariance", "sklearn/feature_extraction/tests/test_text.py::test_countvectorizer_vocab_dicts_when_pickling[get_feature_names_out]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[DecisionTreeRegressor-iris-poisson]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params7-ValueError-min_samples_split == 1.1, must be <= 1.0-DecisionTreeClassifier-DecisionTreeClassifier]", "sklearn/tree/tests/test_tree.py::test_sparse_input[sparse-neg-ExtraTreeClassifier]", "sklearn/tree/tests/test_tree.py::test_explicit_sparse_zeros[DecisionTreeRegressor]", "sklearn/utils/tests/test_validation.py::test_check_is_fitted_with_attributes[single]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_custom_scoring[DENSE_FILTER-None]", "sklearn/ensemble/tests/test_weight_boosting.py::test_adaboost_negative_weight_error[model1-X1-y1]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_non_uniform_weights_toy_edge_case_clf", "sklearn/feature_extraction/tests/test_text.py::test_callable_analyzer_reraise_error[HashingVectorizer]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_sparse[Lasso]", "sklearn/feature_extraction/tests/test_text.py::test_vectorizer_params_validation[params2-ValueError-max_df == -2, must be >= 0.]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[int0-long-integer]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_early_stopping_n_classes", "sklearn/tree/tests/test_tree.py::test_min_weight_fraction_leaf_with_min_samples_leaf_on_sparse_input[ExtraTreeClassifier]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape0-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_best_score[None-ridge1-make_classification]", "sklearn/tree/tests/test_tree.py::test_importances_raises", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_log_regression[family3-True]", "sklearn/utils/tests/test_validation.py::test_check_non_negative[coo_matrix]", "sklearn/feature_extraction/tests/test_text.py::test_callable_analyzer_change_behavior[file-<lambda>1-HashingVectorizer]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape0-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-8-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_sparse_cg_max_iter", "sklearn/utils/tests/test_validation.py::test_check_X_y_informative_error", "sklearn/tree/tests/test_tree.py::test_sparse_input[sparse-neg-ExtraTreeRegressor]", "sklearn/feature_extraction/tests/test_text.py::test_stop_words_removal", "sklearn/linear_model/tests/test_coordinate_descent.py::test_1d_multioutput_enet_and_multitask_enet_cv", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-lsqr-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[Lars-params12]", "sklearn/tree/tests/test_tree.py::test_sparse_input[clf_small-DecisionTreeRegressor]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_alphas_conversion[RidgeClassifierCV]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-saga-False]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[DecisionTreeRegressor-sparse-pos-absolute_error]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[csr_matrix-inf--True-Input contains infinity]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-array-sample_weight1-False]", "sklearn/utils/tests/test_validation.py::test_check_sparse_pandas_sp_format[csc]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[ExtraTreeRegressor-zeros-friedman_mse]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_feature_importances[GradientBoostingClassifier-X1-y1]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-sparse_cg-True]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[tuple-dict]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object", "sklearn/cluster/tests/test_spectral.py::test_spectral_clustering_sparse[cluster_qr]", "sklearn/feature_extraction/tests/test_text.py::test_vectorizer_params_validation[params6-ValueError-max_features == -10, must be >= 0.]", "sklearn/tree/tests/test_tree.py::test_sparse_input[sparse-pos-ExtraTreeClassifier]", "sklearn/tree/tests/test_tree.py::test_sparse[check_sparse_parameters-sparse-pos-DecisionTreeClassifier]", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_raise[csc_matrix]", "sklearn/tree/tests/test_tree.py::test_explicit_sparse_zeros[DecisionTreeClassifier]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_alphas_scalar[RidgeCV]", "sklearn/tree/tests/test_tree.py::test_sparse[check_sparse_parameters-sparse-mix-DecisionTreeRegressor]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_staged_predict", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[ARDRegression-params7]", "sklearn/linear_model/_glm/tests/test_glm.py::test_normal_ridge_comparison[None-True-10-100]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[ExtraTreeRegressor-sparse-pos-absolute_error]", "sklearn/cluster/tests/test_birch.py::test_birch_fit_attributes_deprecated[partial_fit_]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape0-asarray-eigen]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_set_order_sparse[F-F]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[0.001-False]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[ExtraTreeRegressor-clf_small-squared_error]", "sklearn/utils/tests/test_validation.py::test_check_sparse_pandas_sp_format[coo]", "sklearn/feature_extraction/tests/test_text.py::test_vectorizer_params_validation[params3-ValueError-min_df == -10, must be >= 0.]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[eigen-eigen-eigen-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-ridgecv-False]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[True-X1-Input contains NaN.]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingClassifier-X1-y1-params0-ValueError-learning_r]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_multi_task_lasso_cv_dtype", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[ExtraTreeRegressor-zeros-squared_error]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[asarray-nan--1-Input contains NaN]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape0-csr_matrix-svd]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[asarray-inf--True-Input contains infinity]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[dtype0-float32-Float64]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weights", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-dense-None-float16]", "sklearn/cross_decomposition/tests/test_pls.py::test_singular_value_helpers[4-100-200]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[series-str]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_fit_intercept_sparse_error[lsqr]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape1-asarray-svd]", "sklearn/cluster/tests/test_dbscan.py::test_dbscan_params_validation[params1-ValueError-eps == 0.0, must be > 0.0.]", "sklearn/tree/tests/test_tree.py::test_prune_tree_classifier_are_subtrees[ExtraTreeClassifier-sparse-mix-gini]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_alphas_scalar[RidgeClassifierCV]", "sklearn/cross_decomposition/tests/test_pls.py::test_scale_and_stability[X1-Y1-PLSCanonical]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_does_not_overwrite_sample_weight[True]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingClassifier-X1-y1-params28-ValueError-min_sample]", "sklearn/linear_model/_glm/tests/test_glm.py::test_normal_ridge_comparison[True-False-100-10]", "sklearn/tree/tests/test_tree.py::test_public_apply_sparse_trees[DecisionTreeClassifier]", "sklearn/preprocessing/tests/test_discretization.py::test_nonuniform_strategies[kmeans-expected_2bins1-expected_3bins1-expected_5bins1]", "sklearn/feature_extraction/tests/test_text.py::test_countvectorizer_custom_vocabulary", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-ridgecv-False]", "sklearn/cluster/tests/test_spectral.py::test_spectral_params_validation[input12-params12-ValueError-degree == 0, must be >= 1]", "sklearn/cross_decomposition/tests/test_pls.py::test_singular_value_helpers[8-100-200]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-20-csr_matrix-svd]", "sklearn/tree/tests/test_tree.py::test_sparse_input[digits-DecisionTreeClassifier]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_cv_values_not_stored[ridge1-make_classification]", "sklearn/tree/tests/test_tree.py::test_apply_path_readonly_all_trees[ExtraTreeClassifier]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[ushort-uint32]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_error[1]", "sklearn/cluster/tests/test_dbscan.py::test_weighted_dbscan", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_positive_constraint", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-saga-False]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gradient_boosting_early_stopping", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-True-ElasticNet-params3]", "sklearn/tree/tests/test_tree.py::test_sparse_input_reg_trees[reg_small-ExtraTreeRegressor]", "sklearn/tree/tests/test_tree.py::test_sparse[check_sparse_parameters-sparse-neg-DecisionTreeRegressor]", "sklearn/cross_decomposition/tests/test_pls.py::test_pls_feature_names_out[CCA]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[ElasticNet-params3]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[DENSE_FILTER-None-None]", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_invalid[significant neg float32]", "sklearn/feature_extraction/tests/test_text.py::test_callable_analyzer_change_behavior[filename-<lambda>0-HashingVectorizer]", "sklearn/feature_extraction/tests/test_text.py::test_stop_word_validation_custom_preprocessor[HashingVectorizer]", "sklearn/tree/tests/test_tree.py::test_sparse_input[zeros-DecisionTreeRegressor]", "sklearn/feature_extraction/tests/test_text.py::test_unused_parameters_warn[None-None-<lambda>-ngram_range3-\\\\w+-<lambda>-'preprocessor'-'analyzer'-is callable-CountVectorizer]", "sklearn/ensemble/tests/test_weight_boosting.py::test_pickle", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape0-asarray-eigen]", "sklearn/cluster/tests/test_spectral.py::test_spectral_clustering_with_arpack_amg_solvers", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[csr_matrix-nan-X-True-Input X contains NaN]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_classification_synthetic[deviance]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-sparse_cg-False]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[DecisionTreeRegressor-multilabel-absolute_error]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_log_regression[family5-False]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[list-dict]", "sklearn/decomposition/tests/test_pca.py::test_pca_dtype_preservation[full]", "sklearn/ensemble/tests/test_weight_boosting.py::test_sample_weight_adaboost_regressor", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[sparse_cg-False]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_warm_start_equal_n_estimators[GradientBoostingRegressor]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[longfloat-longdouble-floating]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.01-False-lbfgs]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[RidgeClassifierCV-params16]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[ordinal-float32-float16]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_warm_start_zero_n_estimators[GradientBoostingRegressor]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[ExtraTreeRegressor-sparse-mix-squared_error]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_grid_search[True]", "sklearn/cluster/tests/test_birch.py::test_birch_fit_attributes_deprecated[fit_]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-cholesky-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_consistency[True-1-False]", "sklearn/utils/tests/test_validation.py::test_check_sparse_pandas_sp_format[True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-8-csr_matrix-svd]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params15-ValueError-Invalid value for max_features.-DecisionTreeClassifier-DecisionTreeClassifier]", "sklearn/decomposition/tests/test_pca.py::test_pca_dtype_preservation[arpack]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape1-csr_matrix-svd]", "sklearn/tree/tests/test_tree.py::test_check_n_classes", "sklearn/decomposition/tests/test_pca.py::test_pca_svd_solver_auto[data3-10-randomized]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[eigen-eigen-eigen-False]", "sklearn/tree/tests/test_tree.py::test_sparse_input[sparse-pos-DecisionTreeClassifier]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[ordinal-None-float16]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_warm_start_zero_n_estimators[GradientBoostingClassifier]", "sklearn/linear_model/tests/test_ridge.py::test_ridge[lsqr]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-True-LinearRegression-params5]", "sklearn/cluster/tests/test_birch.py::test_birch_params_validation[params1-ValueError-threshold == 0.0, must be > 0.0.]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[int32-long]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-array-sample_weight1-False]", "sklearn/tree/tests/test_tree.py::test_sparse_input[sparse-mix-ExtraTreeRegressor]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params5-ValueError-alpha == -1, must be >= 0.0-PoissonRegressor]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_iris[1-1.0]", "sklearn/decomposition/tests/test_pca.py::test_pca[3-arpack]", "sklearn/decomposition/tests/test_pca.py::test_infer_dim_by_explained_variance[X2-0.5-2]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[DecisionTreeRegressor-clf_small-absolute_error]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_log_regression[family3-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_sparse[LassoCV]", "sklearn/ensemble/tests/test_weight_boosting.py::test_diabetes[square]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingClassifier-X1-y1-params27-ValueError-min_sample]", "sklearn/cluster/tests/test_dbscan.py::test_dbscan_balltree", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[RidgeCV-params15]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_set_order_dense[F-F]", "sklearn/feature_extraction/tests/test_text.py::test_hashingvectorizer_nan_in_docs", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[True-X0-Input contains NaN.]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-cholesky]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-array-None-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_sample_weight_correctness[True]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[DecisionTreeRegressor-digits-friedman_mse]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[False-X3-cannot convert float NaN to integer]", "sklearn/utils/tests/test_validation.py::test_has_fit_parameter", "sklearn/ensemble/tests/test_gradient_boosting.py::test_verbose_output", "sklearn/ensemble/tests/test_gradient_boosting.py::test_regression_dataset[1.0-absolute_error]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_link_auto[poisson-LogLink]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[True-False-LinearRegression-params5]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape1-asarray-eigen]", "sklearn/preprocessing/tests/test_discretization.py::test_32_equal_64[ordinal-float64]", "sklearn/preprocessing/tests/test_discretization.py::test_kbinsdiscretizer_subsample_invalid_strategy", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params9-ValueError-tol == 0, must be > 0.0-GammaRegressor]", "sklearn/tree/tests/test_tree.py::test_class_weight_errors[DecisionTreeClassifier]", "sklearn/cross_decomposition/tests/test_pls.py::test_singular_value_helpers[0-100-10]", "sklearn/tree/tests/test_tree.py::test_xor", "sklearn/feature_extraction/tests/test_text.py::test_vectorizer_min_df", "sklearn/linear_model/tests/test_ridge.py::test_lbfgs_solver_consistency[1.0]", "sklearn/feature_extraction/tests/test_text.py::test_word_analyzer_unigrams[HashingVectorizer]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-lsqr-False]", "sklearn/tree/tests/test_tree.py::test_no_sparse_y_support[DecisionTreeClassifier]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_monitor_early_stopping[GradientBoostingClassifier]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_model_sample_weights_normalize_in_pipeline[False-False-Lasso-params0]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-cholesky-False]", "sklearn/tree/tests/test_tree.py::test_prune_tree_classifier_are_subtrees[DecisionTreeClassifier-zeros-gini]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape0-asarray-svd]", "sklearn/feature_extraction/tests/test_text.py::test_tfidf_vectorizer_with_fixed_vocabulary", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params14-ValueError-max_features == 1.1, must be <= 1.0-ExtraTreeClassifier-ExtraTreeClassifier]", "sklearn/tree/tests/test_tree.py::test_diabetes_overfit[poisson-ExtraTreeRegressor-ExtraTreeRegressor]", "sklearn/tree/tests/test_tree.py::test_prune_tree_regression_are_subtrees[ExtraTreeRegressor-sparse-pos-friedman_mse]", "sklearn/feature_extraction/tests/test_text.py::test_countvectorizer_custom_vocabulary_repeated_indices", "sklearn/cluster/tests/test_spectral.py::test_cluster_qr", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[SPARSE_FILTER-None-None]", "sklearn/tree/tests/test_tree.py::test_sparse_input[zeros-ExtraTreeRegressor]", "sklearn/linear_model/_glm/tests/test_glm.py::test_normal_ridge_comparison[None-False-100-10]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params18-ValueError-min_impurity_decrease == -1, must be >= 0.0-DecisionTreeClassifier-DecisionTreeClassifier]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_warm_start_oob_switch[GradientBoostingRegressor]", "sklearn/preprocessing/tests/test_discretization.py::test_consistent_dtype[onehot-dense-None-float64]", "sklearn/decomposition/tests/test_pca.py::test_pca_validation[arpack-2-must be strictly less than min-data1]", "sklearn/cluster/tests/test_dbscan.py::test_dbscan_core_samples_toy[kd_tree]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_raises_value_error_if_solver_not_supported", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[series-bool]", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_not_equals[array]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[DENSE_FILTER-None-accuracy]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[dtype0-float32-UInt16]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingRegressor-X0-y0-params35-ValueError-max_depth ]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingClassifier-X1-y1-params30-ValueError-min_weight]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-array-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-ridgecv-False]", "sklearn/decomposition/tests/test_pca.py::test_pca_check_projection_list[arpack]", "sklearn/cluster/tests/test_dbscan.py::test_dbscan_sparse_precomputed[False]", "sklearn/decomposition/tests/test_pca.py::test_pca[2-randomized]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_warm_start_max_depth[GradientBoostingClassifier]", "sklearn/feature_extraction/tests/test_text.py::test_vectorizer_max_features[CountVectorizer]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_alphas_conversion[RidgeCV]" ]
[ "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingRegressor-X0-y0-params1-TypeError-learning_r]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params10-TypeError-tol must be an instance of float, not str-GammaRegressor]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params1-TypeError-max_depth must be an instance of int-ExtraTreeClassifier-ExtraTreeClassifier]", "sklearn/utils/tests/test_validation.py::test_check_scalar_invalid[None-test_name1-Integral-2-4-neither-err_msg2]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params4-TypeError-max_iter must be an instance of int, not float-GeneralizedLinearRegressor]", "sklearn/ensemble/tests/test_weight_boosting.py::test_adaboost_params_validation[AdaBoostClassifier-X0-y0-params2-TypeError-n_estimators must be an instance of int, not float]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingClassifier-X1-y1-params25-TypeError-min_sample]", "sklearn/decomposition/tests/test_pca.py::test_pca_params_validation[params1-TypeError-n_oversamples must be an instance of int]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params17-TypeError-max_leaf_nodes must be an instance of int-ExtraTreeClassifier-ExtraTreeClassifier]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params14-TypeError-verbose must be an instance of int, not float-TweedieRegressor]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_params_validation[params5-TypeError-tol must be an instance of float, not str]", "sklearn/cluster/tests/test_birch.py::test_birch_params_validation[params7-TypeError-n_clusters must be an instance of int, not float.]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params6-TypeError-alpha must be an instance of float, not str-GeneralizedLinearRegressor]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params2-TypeError-max_iter must be an instance of int, not str-GeneralizedLinearRegressor]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingRegressor-X0-y0-params22-TypeError-tol must b]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params11-TypeError-min_weight_fraction_leaf must be an instance of float-DecisionTreeRegressor-DecisionTreeRegressor]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_param_invalid[params7-TypeError-max_iter must be an instance of int, not str]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params6-TypeError-alpha must be an instance of float, not str-TweedieRegressor]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingRegressor-X0-y0-params32-TypeError-min_weight]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params14-TypeError-verbose must be an instance of int, not float-PoissonRegressor]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_param_invalid[params3-TypeError-l1_ratio must be an instance of float, not str]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params14-TypeError-verbose must be an instance of int, not float-GammaRegressor]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingClassifier-X1-y1-params32-TypeError-min_weight]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params4-TypeError-min_samples_leaf must be an instance of float-DecisionTreeRegressor-DecisionTreeRegressor]", "sklearn/ensemble/tests/test_weight_boosting.py::test_adaboost_params_validation[AdaBoostRegressor-X1-y1-params2-TypeError-n_estimators must be an instance of int, not float]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params13-TypeError-verbose must be an instance of int, not str-PoissonRegressor]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingClassifier-X1-y1-params1-TypeError-learning_r]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params3-TypeError-max_iter must be an instance of int, not list-GammaRegressor]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_alphas_validation[params2-TypeError-alphas\\\\[2\\\\] must be an instance of float, not str-RidgeCV]", "sklearn/cross_decomposition/tests/test_pls.py::test_n_components_bounds[2.0-TypeError-n_components must be an instance of int-PLSCanonical]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params11-TypeError-tol must be an instance of float, not list-TweedieRegressor]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingClassifier-X1-y1-params3-TypeError-n_estimato]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingRegressor-X0-y0-params3-TypeError-n_estimato]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params13-TypeError-verbose must be an instance of int, not str-GeneralizedLinearRegressor]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_param_invalid[params5-TypeError-tol must be an instance of float, not str]", "sklearn/cross_decomposition/tests/test_pls.py::test_n_components_bounds_pls_regression[2.0-TypeError-n_components must be an instance of int]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params1-TypeError-max_depth must be an instance of int-DecisionTreeClassifier-DecisionTreeClassifier]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params2-TypeError-max_iter must be an instance of int, not str-GammaRegressor]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params10-TypeError-tol must be an instance of float, not str-GeneralizedLinearRegressor]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingClassifier-X1-y1-params34-TypeError-max_leaf_n]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params17-TypeError-max_leaf_nodes must be an instance of int-DecisionTreeRegressor-DecisionTreeRegressor]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params11-TypeError-tol must be an instance of float, not list-GammaRegressor]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params4-TypeError-min_samples_leaf must be an instance of float-DecisionTreeClassifier-DecisionTreeClassifier]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params11-TypeError-min_weight_fraction_leaf must be an instance of float-ExtraTreeClassifier-ExtraTreeClassifier]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params10-TypeError-tol must be an instance of float, not str-TweedieRegressor]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_params_validation[params1-TypeError-alpha must be an instance of float, not str]", "sklearn/cluster/tests/test_dbscan.py::test_dbscan_params_validation[params3-TypeError-min_samples must be an instance of int, not float.]", "sklearn/feature_extraction/tests/test_text.py::test_vectorizer_params_validation[params7-TypeError-max_features must be an instance of int, not float]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params17-TypeError-max_leaf_nodes must be an instance of int-DecisionTreeClassifier-DecisionTreeClassifier]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingRegressor-X0-y0-params36-TypeError-max_depth ]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params21-TypeError-ccp_alpha must be an instance of float-DecisionTreeRegressor-DecisionTreeRegressor]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params4-TypeError-max_iter must be an instance of int, not float-PoissonRegressor]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params8-TypeError-min_samples_split must be an instance of float-DecisionTreeRegressor-DecisionTreeRegressor]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_params_validation[params3-TypeError-max_iter must be an instance of int, not str]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingClassifier-X1-y1-params38-TypeError-min_impuri]", "sklearn/cluster/tests/test_dbscan.py::test_dbscan_params_validation[params6-TypeError-leaf_size must be an instance of int, not float.]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params11-TypeError-tol must be an instance of float, not list-GeneralizedLinearRegressor]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params8-TypeError-min_samples_split must be an instance of float-DecisionTreeClassifier-DecisionTreeClassifier]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params11-TypeError-min_weight_fraction_leaf must be an instance of float-ExtraTreeRegressor-ExtraTreeRegressor]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params19-TypeError-min_impurity_decrease must be an instance of float-DecisionTreeClassifier-DecisionTreeClassifier]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingClassifier-X1-y1-params40-TypeError-ccp_alpha ]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params21-TypeError-ccp_alpha must be an instance of float-ExtraTreeRegressor-ExtraTreeRegressor]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params3-TypeError-max_iter must be an instance of int, not list-TweedieRegressor]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params3-TypeError-max_iter must be an instance of int, not list-GeneralizedLinearRegressor]", "sklearn/cluster/tests/test_spectral.py::test_spectral_params_validation[input2-params2-TypeError-n_clusters must be an instance of int, not float]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params4-TypeError-max_iter must be an instance of int, not float-GammaRegressor]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params21-TypeError-ccp_alpha must be an instance of float-ExtraTreeClassifier-ExtraTreeClassifier]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params1-TypeError-max_depth must be an instance of int-ExtraTreeRegressor-ExtraTreeRegressor]", "sklearn/preprocessing/tests/test_discretization.py::test_kbinsdiscretizer_subsample_invalid_type", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params19-TypeError-min_impurity_decrease must be an instance of float-ExtraTreeRegressor-ExtraTreeRegressor]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params14-TypeError-verbose must be an instance of int, not float-GeneralizedLinearRegressor]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params19-TypeError-min_impurity_decrease must be an instance of float-ExtraTreeClassifier-ExtraTreeClassifier]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params1-TypeError-max_depth must be an instance of int-DecisionTreeRegressor-DecisionTreeRegressor]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params11-TypeError-min_weight_fraction_leaf must be an instance of float-DecisionTreeClassifier-DecisionTreeClassifier]", "sklearn/cross_decomposition/tests/test_pls.py::test_n_components_bounds[2.0-TypeError-n_components must be an instance of int-PLSSVD]", "sklearn/cluster/tests/test_spectral.py::test_spectral_params_validation[input5-params5-TypeError-n_init must be an instance of int, not float]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingRegressor-X0-y0-params29-TypeError-min_sample]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingClassifier-X1-y1-params22-TypeError-tol must b]", "sklearn/utils/tests/test_validation.py::test_check_scalar_invalid[1-test_name1-float-2-4-neither-err_msg0]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingRegressor-X0-y0-params20-TypeError-n_iter_no_]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params4-TypeError-min_samples_leaf must be an instance of float-ExtraTreeClassifier-ExtraTreeClassifier]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingRegressor-X0-y0-params18-TypeError-validation]", "sklearn/cluster/tests/test_birch.py::test_birch_params_validation[params4-TypeError-branching_factor must be an instance of int, not float.]", "sklearn/utils/tests/test_validation.py::test_check_scalar_invalid[1-test_name1-target_type3-2-4-neither-err_msg3]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params11-TypeError-tol must be an instance of float, not list-PoissonRegressor]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingClassifier-X1-y1-params18-TypeError-validation]", "sklearn/cross_decomposition/tests/test_pls.py::test_n_components_bounds[2.0-TypeError-n_components must be an instance of int-CCA]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingClassifier-X1-y1-params29-TypeError-min_sample]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingClassifier-X1-y1-params36-TypeError-max_depth ]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_alphas_validation[params2-TypeError-alphas\\\\[2\\\\] must be an instance of float, not str-RidgeClassifierCV]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingClassifier-X1-y1-params20-TypeError-n_iter_no_]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params4-TypeError-max_iter must be an instance of int, not float-TweedieRegressor]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params3-TypeError-max_iter must be an instance of int, not list-PoissonRegressor]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params19-TypeError-min_impurity_decrease must be an instance of float-DecisionTreeRegressor-DecisionTreeRegressor]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingRegressor-X0-y0-params34-TypeError-max_leaf_n]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params6-TypeError-alpha must be an instance of float, not str-GammaRegressor]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingClassifier-X1-y1-params7-TypeError-subsample ]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingRegressor-X0-y0-params7-TypeError-subsample ]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingRegressor-X0-y0-params38-TypeError-min_impuri]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingRegressor-X0-y0-params40-TypeError-ccp_alpha ]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params2-TypeError-max_iter must be an instance of int, not str-TweedieRegressor]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params13-TypeError-verbose must be an instance of int, not str-GammaRegressor]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params17-TypeError-max_leaf_nodes must be an instance of int-ExtraTreeRegressor-ExtraTreeRegressor]", "sklearn/utils/tests/test_validation.py::test_check_scalar_invalid[None-test_name1-Real-2-4-neither-err_msg1]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params2-TypeError-max_iter must be an instance of int, not str-PoissonRegressor]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params6-TypeError-alpha must be an instance of float, not str-PoissonRegressor]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params21-TypeError-ccp_alpha must be an instance of float-DecisionTreeClassifier-DecisionTreeClassifier]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params13-TypeError-verbose must be an instance of int, not str-TweedieRegressor]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params8-TypeError-min_samples_split must be an instance of float-ExtraTreeRegressor-ExtraTreeRegressor]", "sklearn/ensemble/tests/test_gradient_boosting.py::test_gbdt_parameter_checks[GradientBoostingRegressor-X0-y0-params25-TypeError-min_sample]", "sklearn/cluster/tests/test_dbscan.py::test_dbscan_params_validation[params9-TypeError-n_jobs must be an instance of int, not float.]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params8-TypeError-min_samples_split must be an instance of float-ExtraTreeClassifier-ExtraTreeClassifier]", "sklearn/tree/tests/test_tree.py::test_tree_params_validation[params4-TypeError-min_samples_leaf must be an instance of float-ExtraTreeRegressor-ExtraTreeRegressor]", "sklearn/linear_model/_glm/tests/test_glm.py::test_glm_scalar_argument[params10-TypeError-tol must be an instance of float, not str-PoissonRegressor]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 39f8e405ebf7c..2b53301c40b99 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -617,6 +617,9 @@ Changelog\n left corner of the HTML representation to show how the elements are\n clickable. :pr:`<PRID>` by `<NAME>`_.\n \n+- |Enhancement| :func:`utils.validation.check_scalar` now has better messages\n+ when displaying the type. :pr:`<PRID>` by `<NAME>`_.\n+\n - |Fix| :func:`check_scalar` raises an error when `include_boundaries={\"left\", \"right\"}`\n and the boundaries are not set.\n :pr:`<PRID>` by `Marie Lanternier <mlant>`.\n" } ]
diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index 39f8e405ebf7c..2b53301c40b99 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -617,6 +617,9 @@ Changelog left corner of the HTML representation to show how the elements are clickable. :pr:`<PRID>` by `<NAME>`_. +- |Enhancement| :func:`utils.validation.check_scalar` now has better messages + when displaying the type. :pr:`<PRID>` by `<NAME>`_. + - |Fix| :func:`check_scalar` raises an error when `include_boundaries={"left", "right"}` and the boundaries are not set. :pr:`<PRID>` by `Marie Lanternier <mlant>`.
scikit-learn/scikit-learn
scikit-learn__scikit-learn-20155
https://github.com/scikit-learn/scikit-learn/pull/20155
diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index 7255fe82ff628..525f3439860ef 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -344,6 +344,10 @@ Changelog is now faster. This is especially noticeable on large sparse input. :pr:`19734` by :user:`Fred Robinson <frrad>`. +- |Enhancement| `fit` method preserves dtype for numpy.float32 in + :class:`Lars`, :class:`LassoLars`, :class:`LassoLars`, :class:`LarsCV` and + :class:`LassoLarsCV`. :pr:`20155` by :user:`Takeshi Oura <takoika>`. + :mod:`sklearn.manifold` ....................... diff --git a/sklearn/linear_model/_least_angle.py b/sklearn/linear_model/_least_angle.py index 0932d0bd1aee3..3485344b99e02 100644 --- a/sklearn/linear_model/_least_angle.py +++ b/sklearn/linear_model/_least_angle.py @@ -476,12 +476,23 @@ def _lars_path_solver( max_features = min(max_iter, n_features) + dtypes = set(a.dtype for a in (X, y, Xy, Gram) if a is not None) + if len(dtypes) == 1: + # use the precision level of input data if it is consistent + return_dtype = next(iter(dtypes)) + else: + # fallback to double precision otherwise + return_dtype = np.float64 + if return_path: - coefs = np.zeros((max_features + 1, n_features)) - alphas = np.zeros(max_features + 1) + coefs = np.zeros((max_features + 1, n_features), dtype=return_dtype) + alphas = np.zeros(max_features + 1, dtype=return_dtype) else: - coef, prev_coef = np.zeros(n_features), np.zeros(n_features) - alpha, prev_alpha = np.array([0.]), np.array([0.]) # better ideas? + coef, prev_coef = (np.zeros(n_features, dtype=return_dtype), + np.zeros(n_features, dtype=return_dtype)) + alpha, prev_alpha = (np.array([0.], dtype=return_dtype), + np.array([0.], dtype=return_dtype)) + # above better ideas? n_iter, n_active = 0, 0 active, indices = list(), np.arange(n_features) @@ -948,7 +959,7 @@ def _fit(self, X, y, max_iter, alpha, fit_path, Xy=None): self.alphas_ = [] self.n_iter_ = [] - self.coef_ = np.empty((n_targets, n_features)) + self.coef_ = np.empty((n_targets, n_features), dtype=X.dtype) if fit_path: self.active_ = []
diff --git a/sklearn/linear_model/tests/test_least_angle.py b/sklearn/linear_model/tests/test_least_angle.py index 4321c39b45e92..656b7e3fef718 100644 --- a/sklearn/linear_model/tests/test_least_angle.py +++ b/sklearn/linear_model/tests/test_least_angle.py @@ -14,7 +14,7 @@ from sklearn import linear_model, datasets from sklearn.linear_model._least_angle import _lars_path_residues from sklearn.linear_model import LassoLarsIC, lars_path -from sklearn.linear_model import Lars, LassoLars +from sklearn.linear_model import Lars, LassoLars, LarsCV, LassoLarsCV # TODO: use another dataset that has multiple drops diabetes = datasets.load_diabetes() @@ -777,3 +777,54 @@ def test_copy_X_with_auto_gram(): linear_model.lars_path(X, y, Gram='auto', copy_X=True, method='lasso') # X did not change assert_allclose(X, X_before) + + [email protected]("LARS, has_coef_path, args", + ((Lars, True, {}), + (LassoLars, True, {}), + (LassoLarsIC, False, {}), + (LarsCV, True, {}), + # max_iter=5 is for avoiding ConvergenceWarning + (LassoLarsCV, True, {"max_iter": 5}))) [email protected]("dtype", (np.float32, np.float64)) +def test_lars_dtype_match(LARS, has_coef_path, args, dtype): + # The test ensures that the fit method preserves input dtype + rng = np.random.RandomState(0) + X = rng.rand(6, 6).astype(dtype) + y = rng.rand(6).astype(dtype) + + model = LARS(**args) + model.fit(X, y) + assert model.coef_.dtype == dtype + if has_coef_path: + assert model.coef_path_.dtype == dtype + assert model.intercept_.dtype == dtype + + [email protected]("LARS, has_coef_path, args", + ((Lars, True, {}), + (LassoLars, True, {}), + (LassoLarsIC, False, {}), + (LarsCV, True, {}), + # max_iter=5 is for avoiding ConvergenceWarning + (LassoLarsCV, True, {"max_iter": 5}))) +def test_lars_numeric_consistency(LARS, has_coef_path, args): + # The test ensures numerical consistency between trained coefficients + # of float32 and float64. + rtol = 1e-5 + atol = 1e-5 + + rng = np.random.RandomState(0) + X_64 = rng.rand(6, 6) + y_64 = rng.rand(6) + + model_64 = LARS(**args).fit(X_64, y_64) + model_32 = LARS(**args).fit(X_64.astype(np.float32), + y_64.astype(np.float32)) + + assert_allclose(model_64.coef_, model_32.coef_, rtol=rtol, atol=atol) + if has_coef_path: + assert_allclose(model_64.coef_path_, model_32.coef_path_, + rtol=rtol, atol=atol) + assert_allclose(model_64.intercept_, model_32.intercept_, + rtol=rtol, atol=atol)
[ { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 7255fe82ff628..525f3439860ef 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -344,6 +344,10 @@ Changelog\n is now faster. This is especially noticeable on large sparse input.\n :pr:`19734` by :user:`Fred Robinson <frrad>`.\n \n+- |Enhancement| `fit` method preserves dtype for numpy.float32 in\n+ :class:`Lars`, :class:`LassoLars`, :class:`LassoLars`, :class:`LarsCV` and\n+ :class:`LassoLarsCV`. :pr:`20155` by :user:`Takeshi Oura <takoika>`.\n+\n :mod:`sklearn.manifold`\n .......................\n \n" } ]
1.00
eea26e7e81bc4120ed00d8bb39f58100747cecdc
[ "sklearn/linear_model/tests/test_least_angle.py::test_collinearity", "sklearn/linear_model/tests/test_least_angle.py::test_lars_cv", "sklearn/linear_model/tests/test_least_angle.py::test_lars_numeric_consistency[LassoLarsIC-False-args2]", "sklearn/linear_model/tests/test_least_angle.py::test_lasso_lars_copyX_behaviour[True]", "sklearn/linear_model/tests/test_least_angle.py::test_no_path_precomputed", "sklearn/linear_model/tests/test_least_angle.py::test_lars_path_gram_equivalent[False-lar]", "sklearn/linear_model/tests/test_least_angle.py::test_lasso_lars_vs_R_implementation", "sklearn/linear_model/tests/test_least_angle.py::test_lars_path_positive_constraint", "sklearn/linear_model/tests/test_least_angle.py::test_lars_dtype_match[float64-LassoLarsIC-False-args2]", "sklearn/linear_model/tests/test_least_angle.py::test_lasso_lars_path_length", "sklearn/linear_model/tests/test_least_angle.py::test_lars_dtype_match[float64-LassoLars-True-args1]", "sklearn/linear_model/tests/test_least_angle.py::test_lasso_lars_vs_lasso_cd_ill_conditioned", "sklearn/linear_model/tests/test_least_angle.py::test_no_path_all_precomputed", "sklearn/linear_model/tests/test_least_angle.py::test_lars_numeric_consistency[LassoLars-True-args1]", "sklearn/linear_model/tests/test_least_angle.py::test_copy_X_with_auto_gram", "sklearn/linear_model/tests/test_least_angle.py::test_lars_dtype_match[float64-LassoLarsCV-True-args4]", "sklearn/linear_model/tests/test_least_angle.py::test_lasso_gives_lstsq_solution", "sklearn/linear_model/tests/test_least_angle.py::test_lars_path_gram_equivalent[True-lar]", "sklearn/linear_model/tests/test_least_angle.py::test_lars_cv_max_iter", "sklearn/linear_model/tests/test_least_angle.py::test_estimatorclasses_positive_constraint", "sklearn/linear_model/tests/test_least_angle.py::test_lars_numeric_consistency[LarsCV-True-args3]", "sklearn/linear_model/tests/test_least_angle.py::test_lars_dtype_match[float64-LarsCV-True-args3]", "sklearn/linear_model/tests/test_least_angle.py::test_lasso_lars_vs_lasso_cd_ill_conditioned2", "sklearn/linear_model/tests/test_least_angle.py::test_lars_numeric_consistency[LassoLarsCV-True-args4]", "sklearn/linear_model/tests/test_least_angle.py::test_lasso_lars_ic", "sklearn/linear_model/tests/test_least_angle.py::test_simple", "sklearn/linear_model/tests/test_least_angle.py::test_x_none_gram_none_raises_value_error", "sklearn/linear_model/tests/test_least_angle.py::test_lasso_lars_vs_lasso_cd_positive", "sklearn/linear_model/tests/test_least_angle.py::test_lars_n_nonzero_coefs", "sklearn/linear_model/tests/test_least_angle.py::test_all_precomputed", "sklearn/linear_model/tests/test_least_angle.py::test_lars_precompute[LassoLarsIC]", "sklearn/linear_model/tests/test_least_angle.py::test_lars_add_features", "sklearn/linear_model/tests/test_least_angle.py::test_lars_path_gram_equivalent[False-lasso]", "sklearn/linear_model/tests/test_least_angle.py::test_multitarget", "sklearn/linear_model/tests/test_least_angle.py::test_singular_matrix", "sklearn/linear_model/tests/test_least_angle.py::test_lasso_lars_fit_copyX_behaviour[False]", "sklearn/linear_model/tests/test_least_angle.py::test_rank_deficient_design", "sklearn/linear_model/tests/test_least_angle.py::test_lasso_lars_vs_lasso_cd", "sklearn/linear_model/tests/test_least_angle.py::test_lars_with_jitter[est0]", "sklearn/linear_model/tests/test_least_angle.py::test_lasso_lars_copyX_behaviour[False]", "sklearn/linear_model/tests/test_least_angle.py::test_lars_dtype_match[float64-Lars-True-args0]", "sklearn/linear_model/tests/test_least_angle.py::test_lars_numeric_consistency[Lars-True-args0]", "sklearn/linear_model/tests/test_least_angle.py::test_lasso_lars_fit_copyX_behaviour[True]", "sklearn/linear_model/tests/test_least_angle.py::test_lars_precompute[LarsCV]", "sklearn/linear_model/tests/test_least_angle.py::test_lasso_lars_vs_lasso_cd_early_stopping", "sklearn/linear_model/tests/test_least_angle.py::test_lars_path_readonly_data", "sklearn/linear_model/tests/test_least_angle.py::test_no_path", "sklearn/linear_model/tests/test_least_angle.py::test_lars_with_jitter[est1]", "sklearn/linear_model/tests/test_least_angle.py::test_lars_path_gram_equivalent[True-lasso]", "sklearn/linear_model/tests/test_least_angle.py::test_lars_lstsq", "sklearn/linear_model/tests/test_least_angle.py::test_simple_precomputed", "sklearn/linear_model/tests/test_least_angle.py::test_X_none_gram_not_none", "sklearn/linear_model/tests/test_least_angle.py::test_lars_precompute[Lars]" ]
[ "sklearn/linear_model/tests/test_least_angle.py::test_lars_dtype_match[float32-LassoLarsCV-True-args4]", "sklearn/linear_model/tests/test_least_angle.py::test_lars_dtype_match[float32-LassoLars-True-args1]", "sklearn/linear_model/tests/test_least_angle.py::test_lars_dtype_match[float32-Lars-True-args0]", "sklearn/linear_model/tests/test_least_angle.py::test_lars_dtype_match[float32-LassoLarsIC-False-args2]", "sklearn/linear_model/tests/test_least_angle.py::test_lars_dtype_match[float32-LarsCV-True-args3]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 7255fe82ff628..525f3439860ef 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -344,6 +344,10 @@ Changelog\n is now faster. This is especially noticeable on large sparse input.\n :pr:`<PRID>` by :user:`<NAME>`.\n \n+- |Enhancement| `fit` method preserves dtype for numpy.float32 in\n+ :class:`Lars`, :class:`LassoLars`, :class:`LassoLars`, :class:`LarsCV` and\n+ :class:`LassoLarsCV`. :pr:`<PRID>` by :user:`<NAME>`.\n+\n :mod:`sklearn.manifold`\n .......................\n \n" } ]
diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index 7255fe82ff628..525f3439860ef 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -344,6 +344,10 @@ Changelog is now faster. This is especially noticeable on large sparse input. :pr:`<PRID>` by :user:`<NAME>`. +- |Enhancement| `fit` method preserves dtype for numpy.float32 in + :class:`Lars`, :class:`LassoLars`, :class:`LassoLars`, :class:`LarsCV` and + :class:`LassoLarsCV`. :pr:`<PRID>` by :user:`<NAME>`. + :mod:`sklearn.manifold` .......................
scikit-learn/scikit-learn
scikit-learn__scikit-learn-19415
https://github.com/scikit-learn/scikit-learn/pull/19415
diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst index 65d555f978df0..c658bc6b12452 100644 --- a/doc/modules/classes.rst +++ b/doc/modules/classes.rst @@ -991,6 +991,7 @@ details. metrics.mean_poisson_deviance metrics.mean_gamma_deviance metrics.mean_tweedie_deviance + metrics.mean_pinball_loss Multilabel ranking metrics -------------------------- diff --git a/doc/modules/model_evaluation.rst b/doc/modules/model_evaluation.rst index 86e64f997cdd8..c807af982e277 100644 --- a/doc/modules/model_evaluation.rst +++ b/doc/modules/model_evaluation.rst @@ -416,7 +416,7 @@ defined as .. math:: - \texttt{accuracy}(y, \hat{y}) = \frac{1}{n_\text{samples}} \sum_{i=0}^{n_\text{samples}-1} 1(\hat{y}_i = y_i) + \texttt{accuracy}(y, \hat{y}) = \frac{1}{n_\text{samples}} \sum_{i=0}^{n_\text{samples}-1} 1(\hat{y}_i = y_i) where :math:`1(x)` is the `indicator function <https://en.wikipedia.org/wiki/Indicator_function>`_. @@ -1960,8 +1960,8 @@ Regression metrics The :mod:`sklearn.metrics` module implements several loss, score, and utility functions to measure regression performance. Some of those have been enhanced to handle the multioutput case: :func:`mean_squared_error`, -:func:`mean_absolute_error`, :func:`explained_variance_score` and -:func:`r2_score`. +:func:`mean_absolute_error`, :func:`explained_variance_score`, +:func:`r2_score` and :func:`mean_pinball_loss`. These functions have an ``multioutput`` keyword argument which specifies the @@ -2354,6 +2354,71 @@ the difference in errors decreases. Finally, by setting, ``power=2``:: we would get identical errors. The deviance when ``power=2`` is thus only sensitive to relative errors. +.. _pinball_loss: + +Pinball loss +------------ + +The :func:`mean_pinball_loss` function is used to evaluate the predictive +performance of quantile regression models. The `pinball loss +<https://en.wikipedia.org/wiki/Quantile_regression#Computation>`_ is equivalent +to :func:`mean_absolute_error` when the quantile parameter ``alpha`` is set to +0.5. + +.. math:: + + \text{pinball}(y, \hat{y}) = \frac{1}{n_{\text{samples}}} \sum_{i=0}^{n_{\text{samples}}-1} \alpha \max(y_i - \hat{y}_i, 0) + (1 - \alpha) \max(\hat{y}_i - y_i, 0) + +Here is a small example of usage of the :func:`mean_pinball_loss` function:: + + >>> from sklearn.metrics import mean_pinball_loss + >>> y_true = [1, 2, 3] + >>> mean_pinball_loss(y_true, [0, 2, 3], alpha=0.1) + 0.03... + >>> mean_pinball_loss(y_true, [1, 2, 4], alpha=0.1) + 0.3... + >>> mean_pinball_loss(y_true, [0, 2, 3], alpha=0.9) + 0.3... + >>> mean_pinball_loss(y_true, [1, 2, 4], alpha=0.9) + 0.03... + >>> mean_pinball_loss(y_true, y_true, alpha=0.1) + 0.0 + >>> mean_pinball_loss(y_true, y_true, alpha=0.9) + 0.0 + +It is possible to build a scorer object with a specific choice of alpha:: + + >>> from sklearn.metrics import make_scorer + >>> mean_pinball_loss_95p = make_scorer(mean_pinball_loss, alpha=0.95) + +Such a scorer can be used to evaluate the generalization performance of a +quantile regressor via cross-validation: + + >>> from sklearn.datasets import make_regression + >>> from sklearn.model_selection import cross_val_score + >>> from sklearn.ensemble import GradientBoostingRegressor + >>> + >>> X, y = make_regression(n_samples=100, random_state=0) + >>> estimator = GradientBoostingRegressor( + ... loss="quantile", + ... alpha=0.95, + ... random_state=0, + ... ) + >>> cross_val_score(estimator, X, y, cv=5, scoring=mean_pinball_loss_95p) + array([11.1..., 10.4... , 24.4..., 9.2..., 12.9...]) + +It is also possible to build scorer objects for hyper-parameter tuning. The +sign of the loss must be switched to ensure that greater means better as +explained in the example linked below. + +.. topic:: Example: + + * See :ref:`sphx_glr_auto_examples_ensemble_plot_gradient_boosting_quantile.py` + for an example of using a the pinball loss to evaluate and tune the + hyper-parameters of quantile regression models on data with non-symmetric + noise and outliers. + + .. _clustering_metrics: Clustering metrics diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index 3086d91b28f5d..582d6872f59cb 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -134,6 +134,10 @@ Changelog class methods and will be removed in 1.2. :pr:`18543` by `Guillaume Lemaitre`_. +- |Feature| :func:`metrics.mean_pinball_loss` exposes the pinball loss for + quantile regression. :pr:`19415` by :user:`Xavier Dupré <sdpython>` + and :user:`Oliver Grisel <ogrisel>`. + :mod:`sklearn.naive_bayes` .......................... diff --git a/examples/ensemble/plot_gradient_boosting_quantile.py b/examples/ensemble/plot_gradient_boosting_quantile.py index ef40a2247bcc5..f29a87fe6cff7 100644 --- a/examples/ensemble/plot_gradient_boosting_quantile.py +++ b/examples/ensemble/plot_gradient_boosting_quantile.py @@ -3,77 +3,330 @@ Prediction Intervals for Gradient Boosting Regression ===================================================== -This example shows how quantile regression can be used -to create prediction intervals. +This example shows how quantile regression can be used to create prediction +intervals. """ - +# %% +# Generate some data for a synthetic regression problem by applying the +# function f to uniformly sampled random inputs. import numpy as np -import matplotlib.pyplot as plt - -from sklearn.ensemble import GradientBoostingRegressor - -np.random.seed(1) +from sklearn.model_selection import train_test_split def f(x): """The function to predict.""" return x * np.sin(x) -#---------------------------------------------------------------------- -# First the noiseless case -X = np.atleast_2d(np.random.uniform(0, 10.0, size=100)).T -X = X.astype(np.float32) -# Observations -y = f(X).ravel() +rng = np.random.RandomState(42) +X = np.atleast_2d(rng.uniform(0, 10.0, size=1000)).T +expected_y = f(X).ravel() + +# %% +# To make the problem interesting, we generate observations of the target y as +# the sum of a deterministic term computed by the function f and a random noise +# term that follows a centered `log-normal +# <https://en.wikipedia.org/wiki/Log-normal_distribution>`_. To make this even +# more interesting we consider the case where the amplitude of the noise +# depends on the input variable x (heteroscedastic noise). +# +# The lognormal distribution is non-symmetric and long tailed: observing large +# outliers is likely but it is impossible to observe small outliers. +sigma = 0.5 + X.ravel() / 10 +noise = rng.lognormal(sigma=sigma) - np.exp(sigma ** 2 / 2) +y = expected_y + noise + +# %% +# Split into train, test datasets: +X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) + +# %% +# Fitting non-linear quantile and least squares regressors +# -------------------------------------------------------- +# +# Fit gradient boosting models trained with the quantile loss and +# alpha=0.05, 0.5, 0.95. +# +# The models obtained for alpha=0.05 and alpha=0.95 produce a 90% confidence +# interval (95% - 5% = 90%). +# +# The model trained with alpha=0.5 produces a regression of the median: on +# average, there should be the same number of target observations above and +# below the predicted values. +from sklearn.ensemble import GradientBoostingRegressor +from sklearn.metrics import mean_pinball_loss, mean_squared_error + -dy = 1.5 + 1.0 * np.random.random(y.shape) -noise = np.random.normal(0, dy) -y += noise -y = y.astype(np.float32) +all_models = {} +common_params = dict( + learning_rate=0.05, + n_estimators=250, + max_depth=2, + min_samples_leaf=9, + min_samples_split=9, +) +for alpha in [0.05, 0.5, 0.95]: + gbr = GradientBoostingRegressor(loss='quantile', alpha=alpha, + **common_params) + all_models["q %1.2f" % alpha] = gbr.fit(X_train, y_train) -# Mesh the input space for evaluations of the real function, the prediction and -# its MSE +# %% +# For the sake of comparison, also fit a baseline model trained with the usual +# least squares loss (ls), also known as the mean squared error (MSE). +gbr_ls = GradientBoostingRegressor(loss='ls', **common_params) +all_models["ls"] = gbr_ls.fit(X_train, y_train) + +# %% +# Create an evenly spaced evaluation set of input values spanning the [0, 10] +# range. xx = np.atleast_2d(np.linspace(0, 10, 1000)).T -xx = xx.astype(np.float32) -alpha = 0.95 +# %% +# Plot the true conditional mean function f, the prediction of the conditional +# mean (least squares loss), the conditional median and the conditional 90% +# interval (from 5th to 95th conditional percentiles). +import matplotlib.pyplot as plt + + +y_pred = all_models['ls'].predict(xx) +y_lower = all_models['q 0.05'].predict(xx) +y_upper = all_models['q 0.95'].predict(xx) +y_med = all_models['q 0.50'].predict(xx) + +fig = plt.figure(figsize=(10, 10)) +plt.plot(xx, f(xx), 'g:', linewidth=3, label=r'$f(x) = x\,\sin(x)$') +plt.plot(X_test, y_test, 'b.', markersize=10, label='Test observations') +plt.plot(xx, y_med, 'r-', label='Predicted median', color="orange") +plt.plot(xx, y_pred, 'r-', label='Predicted mean') +plt.plot(xx, y_upper, 'k-') +plt.plot(xx, y_lower, 'k-') +plt.fill_between(xx.ravel(), y_lower, y_upper, alpha=0.4, + label='Predicted 90% interval') +plt.xlabel('$x$') +plt.ylabel('$f(x)$') +plt.ylim(-10, 25) +plt.legend(loc='upper left') +plt.show() + +# %% +# Comparing the predicted median with the predicted mean, we note that the +# median is on average below the mean as the noise is skewed towards high +# values (large outliers). The median estimate also seems to be smoother +# because of its natural robustness to outliers. +# +# Also observe that the inductive bias of gradient boosting trees is +# unfortunately preventing our 0.05 quantile to fully capture the sinoisoidal +# shape of the signal, in particular around x=8. Tuning hyper-parameters can +# reduce this effect as shown in the last part of this notebook. +# +# Analysis of the error metrics +# ----------------------------- +# +# Measure the models with :func:`mean_squared_error` and +# :func:`mean_pinball_loss` metrics on the training dataset. +import pandas as pd + + +def highlight_min(x): + x_min = x.min() + return ['font-weight: bold' if v == x_min else '' + for v in x] + + +results = [] +for name, gbr in sorted(all_models.items()): + metrics = {'model': name} + y_pred = gbr.predict(X_train) + for alpha in [0.05, 0.5, 0.95]: + metrics["pbl=%1.2f" % alpha] = mean_pinball_loss( + y_train, y_pred, alpha=alpha) + metrics['MSE'] = mean_squared_error(y_train, y_pred) + results.append(metrics) + +pd.DataFrame(results).set_index('model').style.apply(highlight_min) + +# %% +# One column shows all models evaluated by the same metric. The minimum number +# on a column should be obtained when the model is trained and measured with +# the same metric. This should be always the case on the training set if the +# training converged. +# +# Note that because the target distribution is asymmetric, the expected +# conditional mean and conditional median are signficiantly different and +# therefore one could not use the least squares model get a good estimation of +# the conditional median nor the converse. +# +# If the target distribution were symmetric and had no outliers (e.g. with a +# Gaussian noise), then median estimator and the least squares estimator would +# have yielded similar predictions. +# +# We then do the same on the test set. +results = [] +for name, gbr in sorted(all_models.items()): + metrics = {'model': name} + y_pred = gbr.predict(X_test) + for alpha in [0.05, 0.5, 0.95]: + metrics["pbl=%1.2f" % alpha] = mean_pinball_loss( + y_test, y_pred, alpha=alpha) + metrics['MSE'] = mean_squared_error(y_test, y_pred) + results.append(metrics) -clf = GradientBoostingRegressor(loss='quantile', alpha=alpha, - n_estimators=250, max_depth=3, - learning_rate=.1, min_samples_leaf=9, - min_samples_split=9) +pd.DataFrame(results).set_index('model').style.apply(highlight_min) -clf.fit(X, y) -# Make the prediction on the meshed x-axis -y_upper = clf.predict(xx) +# %% +# Errors are higher meaning the models slightly overfitted the data. It still +# shows that the best test metric is obtained when the model is trained by +# minimizing this same metric. +# +# Note that the conditional median estimator is competitive with the least +# squares estimator in terms of MSE on the test set: this can be explained by +# the fact the least squares estimator is very sensitive to large outliers +# which can cause significant overfitting. This can be seen on the right hand +# side of the previous plot. The conditional median estimator is biased +# (underestimation for this asymetric noise) but is also naturally robust to +# outliers and overfits less. +# +# Calibration of the confidence interval +# -------------------------------------- +# +# We can also evaluate the ability of the two extreme quantile estimators at +# producing a well-calibrated conditational 90%-confidence interval. +# +# To do this we can compute the fraction of observations that fall between the +# predictions: +def coverage_fraction(y, y_low, y_high): + return np.mean(np.logical_and(y >= y_low, y <= y_high)) -clf.set_params(alpha=1.0 - alpha) -clf.fit(X, y) -# Make the prediction on the meshed x-axis -y_lower = clf.predict(xx) +coverage_fraction(y_train, + all_models['q 0.05'].predict(X_train), + all_models['q 0.95'].predict(X_train)) -clf.set_params(loss='ls') -clf.fit(X, y) +# %% +# On the training set the calibration is very close to the expected coverage +# value for a 90% confidence interval. +coverage_fraction(y_test, + all_models['q 0.05'].predict(X_test), + all_models['q 0.95'].predict(X_test)) -# Make the prediction on the meshed x-axis -y_pred = clf.predict(xx) -# Plot the function, the prediction and the 95% confidence interval based on -# the MSE -fig = plt.figure() -plt.plot(xx, f(xx), 'g:', label=r'$f(x) = x\,\sin(x)$') -plt.plot(X, y, 'b.', markersize=10, label=u'Observations') -plt.plot(xx, y_pred, 'r-', label=u'Prediction') +# %% +# On the test set, the estimated confidence interval is slightly too narrow. +# Note, however, that we would need to wrap those metrics in a cross-validation +# loop to assess their variability under data resampling. +# +# Tuning the hyper-parameters of the quantile regressors +# ------------------------------------------------------ +# +# In the plot above, we observed that the 5th percentile regressor seems to +# underfit and could not adapt to sinusoidal shape of the signal. +# +# The hyper-parameters of the model were approximately hand-tuned for the +# median regressor and there is no reason than the same hyper-parameters are +# suitable for the 5th percentile regressor. +# +# To confirm this hypothesis, we tune the hyper-parameters of a new regressor +# of the 5th percentile by selecting the best model parameters by +# cross-validation on the pinball loss with alpha=0.05: + +# %% +from sklearn.model_selection import RandomizedSearchCV +from sklearn.metrics import make_scorer +from pprint import pprint + + +param_grid = dict( + learning_rate=[0.01, 0.05, 0.1], + n_estimators=[100, 150, 200, 250, 300], + max_depth=[2, 5, 10, 15, 20], + min_samples_leaf=[1, 5, 10, 20, 30, 50], + min_samples_split=[2, 5, 10, 20, 30, 50], +) +alpha = 0.05 +neg_mean_pinball_loss_05p_scorer = make_scorer( + mean_pinball_loss, + alpha=alpha, + greater_is_better=False, # maximize the negative loss +) +gbr = GradientBoostingRegressor(loss="quantile", alpha=alpha, random_state=0) +search_05p = RandomizedSearchCV( + gbr, + param_grid, + n_iter=10, # increase this if computational budget allows + scoring=neg_mean_pinball_loss_05p_scorer, + n_jobs=2, + random_state=0, +).fit(X_train, y_train) +pprint(search_05p.best_params_) + +# %% +# We observe that the search procedure identifies that deeper trees are needed +# to get a good fit for the 5th percentile regressor. Deeper trees are more +# expressive and less likely to underfit. +# +# Let's now tune the hyper-parameters for the 95th percentile regressor. We +# need to redefine the `scoring` metric used to select the best model, along +# with adjusting the alpha parameter of the inner gradient boosting estimator +# itself: +from sklearn.base import clone + +alpha = 0.95 +neg_mean_pinball_loss_95p_scorer = make_scorer( + mean_pinball_loss, + alpha=alpha, + greater_is_better=False, # maximize the negative loss +) +search_95p = clone(search_05p).set_params( + estimator__alpha=alpha, + scoring=neg_mean_pinball_loss_95p_scorer, +) +search_95p.fit(X_train, y_train) +pprint(search_95p.best_params_) + +# %% +# This time, shallower trees are selected and lead to a more constant piecewise +# and therefore more robust estimation of the 95th percentile. This is +# beneficial as it avoids overfitting the large outliers of the log-normal +# additive noise. +# +# We can confirm this intuition by displaying the predicted 90% confidence +# interval comprised by the predictions of those two tuned quantile regressors: +# the prediction of the upper 95th percentile has a much coarser shape than the +# prediction of the lower 5th percentile: +y_lower = search_05p.predict(xx) +y_upper = search_95p.predict(xx) + +fig = plt.figure(figsize=(10, 10)) +plt.plot(xx, f(xx), 'g:', linewidth=3, label=r'$f(x) = x\,\sin(x)$') +plt.plot(X_test, y_test, 'b.', markersize=10, label='Test observations') plt.plot(xx, y_upper, 'k-') plt.plot(xx, y_lower, 'k-') -plt.fill(np.concatenate([xx, xx[::-1]]), - np.concatenate([y_upper, y_lower[::-1]]), - alpha=.5, fc='b', ec='None', label='95% prediction interval') +plt.fill_between(xx.ravel(), y_lower, y_upper, alpha=0.4, + label='Predicted 90% interval') plt.xlabel('$x$') plt.ylabel('$f(x)$') -plt.ylim(-10, 20) +plt.ylim(-10, 25) plt.legend(loc='upper left') +plt.title("Prediction with tuned hyper-parameters") plt.show() + +# %% +# The plot looks qualitatively better than for the untuned models, especially +# for the shape of the of lower quantile. +# +# We now quantitatively evaluate the joint-calibration of the pair of +# estimators: +coverage_fraction(y_train, + search_05p.predict(X_train), + search_95p.predict(X_train)) +# %% +coverage_fraction(y_test, + search_05p.predict(X_test), + search_95p.predict(X_test)) +# %% +# The calibration of the tuned pair is sadly not better on the test set: the +# width of the estimated confidence interval is still too narrow. +# +# Again, we would need to wrap this study in a cross-validation loop to +# better assess the variability of those estimates. diff --git a/sklearn/metrics/__init__.py b/sklearn/metrics/__init__.py index 84e7c98e29324..bca22e3916c61 100644 --- a/sklearn/metrics/__init__.py +++ b/sklearn/metrics/__init__.py @@ -69,6 +69,7 @@ from ._regression import mean_squared_log_error from ._regression import median_absolute_error from ._regression import mean_absolute_percentage_error +from ._regression import mean_pinball_loss from ._regression import r2_score from ._regression import mean_tweedie_deviance from ._regression import mean_poisson_deviance @@ -133,6 +134,7 @@ 'mean_absolute_error', 'mean_squared_error', 'mean_squared_log_error', + 'mean_pinball_loss', 'mean_poisson_deviance', 'mean_gamma_deviance', 'mean_tweedie_deviance', diff --git a/sklearn/metrics/_regression.py b/sklearn/metrics/_regression.py index 0d8fddd0ba24e..7edf7924e50e1 100644 --- a/sklearn/metrics/_regression.py +++ b/sklearn/metrics/_regression.py @@ -43,6 +43,7 @@ "mean_squared_log_error", "median_absolute_error", "mean_absolute_percentage_error", + "mean_pinball_loss", "r2_score", "explained_variance_score", "mean_tweedie_deviance", @@ -194,6 +195,88 @@ def mean_absolute_error(y_true, y_pred, *, return np.average(output_errors, weights=multioutput) +def mean_pinball_loss(y_true, y_pred, *, + sample_weight=None, + alpha=0.5, + multioutput='uniform_average'): + """Pinball loss for quantile regression. + + Read more in the :ref:`User Guide <pinball_loss>`. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) + Estimated target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + alpha: double, slope of the pinball loss, default=0.5, + this loss is equivalent to :ref:`mean_absolute_error` when `alpha=0.5`, + `alpha=0.95` is minimized by estimators of the 95th percentile. + + multioutput : {'raw_values', 'uniform_average'} or array-like of shape \ + (n_outputs,), default='uniform_average' + Defines aggregating of multiple output values. + Array-like value defines weights used to average errors. + + 'raw_values' : + Returns a full set of errors in case of multioutput input. + + 'uniform_average' : + Errors of all outputs are averaged with uniform weight. + Returns + ------- + loss : float or ndarray of floats + If multioutput is 'raw_values', then mean absolute error is returned + for each output separately. + If multioutput is 'uniform_average' or an ndarray of weights, then the + weighted average of all output errors is returned. + + The pinball loss output is a non-negative floating point. The best + value is 0.0. + + Examples + -------- + >>> from sklearn.metrics import mean_pinball_loss + >>> y_true = [1, 2, 3] + >>> mean_pinball_loss(y_true, [0, 2, 3], alpha=0.1) + 0.03... + >>> mean_pinball_loss(y_true, [1, 2, 4], alpha=0.1) + 0.3... + >>> mean_pinball_loss(y_true, [0, 2, 3], alpha=0.9) + 0.3... + >>> mean_pinball_loss(y_true, [1, 2, 4], alpha=0.9) + 0.03... + >>> mean_pinball_loss(y_true, y_true, alpha=0.1) + 0.0 + >>> mean_pinball_loss(y_true, y_true, alpha=0.9) + 0.0 + """ + y_type, y_true, y_pred, multioutput = _check_reg_targets( + y_true, y_pred, multioutput) + check_consistent_length(y_true, y_pred, sample_weight) + diff = y_true - y_pred + sign = (diff >= 0).astype(diff.dtype) + loss = alpha * sign * diff - (1 - alpha) * (1 - sign) * diff + output_errors = np.average(loss, weights=sample_weight, axis=0) + if isinstance(multioutput, str): + if multioutput == 'raw_values': + return output_errors + elif multioutput == 'uniform_average': + # pass None as weights to np.average: uniform mean + multioutput = None + else: + raise ValueError("multioutput is expected to be 'raw_values' " + "or 'uniform_average' but we got %r" + " instead." % multioutput) + + return np.average(output_errors, weights=multioutput) + + def mean_absolute_percentage_error(y_true, y_pred, sample_weight=None, multioutput='uniform_average'):
diff --git a/sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py b/sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py index d0300ddc371c7..4d7ea9bfe9bb3 100644 --- a/sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py +++ b/sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py @@ -8,6 +8,7 @@ from pytest import approx from sklearn.utils import check_random_state +from sklearn.metrics import mean_pinball_loss from sklearn.ensemble._gb_losses import RegressionLossFunction from sklearn.ensemble._gb_losses import LeastSquaresError from sklearn.ensemble._gb_losses import LeastAbsoluteError @@ -115,6 +116,8 @@ def test_quantile_loss_function(): y_found = QuantileLossFunction(0.9)(x, np.zeros_like(x)) y_expected = np.asarray([0.1, 0.0, 0.9]).mean() np.testing.assert_allclose(y_found, y_expected) + y_found_p = mean_pinball_loss(x, np.zeros_like(x), alpha=0.9) + np.testing.assert_allclose(y_found, y_found_p) def test_sample_weight_deviance(): @@ -293,10 +296,11 @@ def test_init_raw_predictions_values(): @pytest.mark.parametrize('seed', range(5)) -def test_lad_equals_quantile_50(seed): [email protected]('alpha', [0.4, 0.5, 0.6]) +def test_lad_equals_quantiles(seed, alpha): # Make sure quantile loss with alpha = .5 is equivalent to LAD lad = LeastAbsoluteError() - ql = QuantileLossFunction(alpha=0.5) + ql = QuantileLossFunction(alpha=alpha) n_samples = 50 rng = np.random.RandomState(seed) @@ -305,9 +309,15 @@ def test_lad_equals_quantile_50(seed): lad_loss = lad(y_true, raw_predictions) ql_loss = ql(y_true, raw_predictions) - assert lad_loss == approx(2 * ql_loss) + if alpha == 0.5: + assert lad_loss == approx(2 * ql_loss) weights = np.linspace(0, 1, n_samples) ** 2 lad_weighted_loss = lad(y_true, raw_predictions, sample_weight=weights) ql_weighted_loss = ql(y_true, raw_predictions, sample_weight=weights) - assert lad_weighted_loss == approx(2 * ql_weighted_loss) + if alpha == 0.5: + assert lad_weighted_loss == approx(2 * ql_weighted_loss) + pbl_weighted_loss = mean_pinball_loss(y_true, raw_predictions, + sample_weight=weights, + alpha=alpha) + assert pbl_weighted_loss == approx(ql_weighted_loss) diff --git a/sklearn/metrics/tests/test_common.py b/sklearn/metrics/tests/test_common.py index 181baf19de3c2..dbf1bdd458f1a 100644 --- a/sklearn/metrics/tests/test_common.py +++ b/sklearn/metrics/tests/test_common.py @@ -50,6 +50,7 @@ from sklearn.metrics import mean_gamma_deviance from sklearn.metrics import median_absolute_error from sklearn.metrics import multilabel_confusion_matrix +from sklearn.metrics import mean_pinball_loss from sklearn.metrics import precision_recall_curve from sklearn.metrics import precision_score from sklearn.metrics import r2_score @@ -101,6 +102,7 @@ "max_error": max_error, "mean_absolute_error": mean_absolute_error, "mean_squared_error": mean_squared_error, + "mean_pinball_loss": mean_pinball_loss, "median_absolute_error": median_absolute_error, "mean_absolute_percentage_error": mean_absolute_percentage_error, "explained_variance_score": explained_variance_score, @@ -437,7 +439,8 @@ def precision_recall_curve_padded_thresholds(*args, **kwargs): # Regression metrics with "multioutput-continuous" format support MULTIOUTPUT_METRICS = { "mean_absolute_error", "median_absolute_error", "mean_squared_error", - "r2_score", "explained_variance_score", "mean_absolute_percentage_error" + "r2_score", "explained_variance_score", "mean_absolute_percentage_error", + "mean_pinball_loss" } # Symmetric with respect to their input arguments y_true and y_pred @@ -460,6 +463,9 @@ def precision_recall_curve_padded_thresholds(*args, **kwargs): "matthews_corrcoef_score", "mean_absolute_error", "mean_squared_error", "median_absolute_error", "max_error", + # Pinball loss is only symmetric for alpha=0.5 which is the default. + "mean_pinball_loss", + "cohen_kappa_score", "mean_normal_deviance" } diff --git a/sklearn/metrics/tests/test_regression.py b/sklearn/metrics/tests/test_regression.py index 5b8406cf7a61f..8e935173d3319 100644 --- a/sklearn/metrics/tests/test_regression.py +++ b/sklearn/metrics/tests/test_regression.py @@ -1,5 +1,6 @@ import numpy as np +from scipy import optimize from numpy.testing import assert_allclose from itertools import product import pytest @@ -7,6 +8,8 @@ from sklearn.utils._testing import assert_almost_equal from sklearn.utils._testing import assert_array_equal from sklearn.utils._testing import assert_array_almost_equal +from sklearn.dummy import DummyRegressor +from sklearn.model_selection import GridSearchCV from sklearn.metrics import explained_variance_score from sklearn.metrics import mean_absolute_error @@ -15,23 +18,30 @@ from sklearn.metrics import median_absolute_error from sklearn.metrics import mean_absolute_percentage_error from sklearn.metrics import max_error +from sklearn.metrics import mean_pinball_loss from sklearn.metrics import r2_score from sklearn.metrics import mean_tweedie_deviance +from sklearn.metrics import make_scorer from sklearn.metrics._regression import _check_reg_targets -from ...exceptions import UndefinedMetricWarning +from sklearn.exceptions import UndefinedMetricWarning def test_regression_metrics(n_samples=50): y_true = np.arange(n_samples) y_pred = y_true + 1 + y_pred_2 = y_true - 1 assert_almost_equal(mean_squared_error(y_true, y_pred), 1.) assert_almost_equal(mean_squared_log_error(y_true, y_pred), mean_squared_error(np.log(1 + y_true), np.log(1 + y_pred))) assert_almost_equal(mean_absolute_error(y_true, y_pred), 1.) + assert_almost_equal(mean_pinball_loss(y_true, y_pred), 0.5) + assert_almost_equal(mean_pinball_loss(y_true, y_pred_2), 0.5) + assert_almost_equal(mean_pinball_loss(y_true, y_pred, alpha=0.4), 0.6) + assert_almost_equal(mean_pinball_loss(y_true, y_pred_2, alpha=0.4), 0.4) assert_almost_equal(median_absolute_error(y_true, y_pred), 1.) mape = mean_absolute_percentage_error(y_true, y_pred) assert np.isfinite(mape) @@ -90,6 +100,9 @@ def test_multioutput_regression(): error = mean_absolute_error(y_true, y_pred) assert_almost_equal(error, (1. + 2. / 3) / 4.) + error = mean_pinball_loss(y_true, y_pred) + assert_almost_equal(error, (1. + 2. / 3) / 8.) + error = np.around(mean_absolute_percentage_error(y_true, y_pred), decimals=2) assert np.isfinite(error) @@ -104,15 +117,16 @@ def test_multioutput_regression(): def test_regression_metrics_at_limits(): - assert_almost_equal(mean_squared_error([0.], [0.]), 0.00, 2) - assert_almost_equal(mean_squared_error([0.], [0.], squared=False), 0.00, 2) - assert_almost_equal(mean_squared_log_error([0.], [0.]), 0.00, 2) - assert_almost_equal(mean_absolute_error([0.], [0.]), 0.00, 2) - assert_almost_equal(mean_absolute_percentage_error([0.], [0.]), 0.00, 2) - assert_almost_equal(median_absolute_error([0.], [0.]), 0.00, 2) - assert_almost_equal(max_error([0.], [0.]), 0.00, 2) - assert_almost_equal(explained_variance_score([0.], [0.]), 1.00, 2) - assert_almost_equal(r2_score([0., 1], [0., 1]), 1.00, 2) + assert_almost_equal(mean_squared_error([0.], [0.]), 0.0) + assert_almost_equal(mean_squared_error([0.], [0.], squared=False), 0.0) + assert_almost_equal(mean_squared_log_error([0.], [0.]), 0.0) + assert_almost_equal(mean_absolute_error([0.], [0.]), 0.0) + assert_almost_equal(mean_pinball_loss([0.], [0.]), 0.0) + assert_almost_equal(mean_absolute_percentage_error([0.], [0.]), 0.0) + assert_almost_equal(median_absolute_error([0.], [0.]), 0.0) + assert_almost_equal(max_error([0.], [0.]), 0.0) + assert_almost_equal(explained_variance_score([0.], [0.]), 1.0) + assert_almost_equal(r2_score([0., 1], [0., 1]), 1.0) err_msg = ("Mean Squared Logarithmic Error cannot be used when targets " "contain negative values.") with pytest.raises(ValueError, match=err_msg): @@ -207,6 +221,11 @@ def test_regression_multioutput_array(): mse = mean_squared_error(y_true, y_pred, multioutput='raw_values') mae = mean_absolute_error(y_true, y_pred, multioutput='raw_values') + err_msg = ("multioutput is expected to be 'raw_values' " + "or 'uniform_average' but we got 'variance_weighted' instead.") + with pytest.raises(ValueError, match=err_msg): + mean_pinball_loss(y_true, y_pred, multioutput='variance_weighted') + pbl = mean_pinball_loss(y_true, y_pred, multioutput='raw_values') mape = mean_absolute_percentage_error(y_true, y_pred, multioutput='raw_values') r = r2_score(y_true, y_pred, multioutput='raw_values') @@ -214,6 +233,7 @@ def test_regression_multioutput_array(): assert_array_almost_equal(mse, [0.125, 0.5625], decimal=2) assert_array_almost_equal(mae, [0.25, 0.625], decimal=2) + assert_array_almost_equal(pbl, [0.25/2, 0.625/2], decimal=2) assert_array_almost_equal(mape, [0.0778, 0.2262], decimal=2) assert_array_almost_equal(r, [0.95, 0.93], decimal=2) assert_array_almost_equal(evs, [0.95, 0.93], decimal=2) @@ -224,9 +244,11 @@ def test_regression_multioutput_array(): y_pred = [[1, 1]]*4 mse = mean_squared_error(y_true, y_pred, multioutput='raw_values') mae = mean_absolute_error(y_true, y_pred, multioutput='raw_values') + pbl = mean_pinball_loss(y_true, y_pred, multioutput='raw_values') r = r2_score(y_true, y_pred, multioutput='raw_values') assert_array_almost_equal(mse, [1., 1.], decimal=2) assert_array_almost_equal(mae, [1., 1.], decimal=2) + assert_array_almost_equal(pbl, [0.5, 0.5], decimal=2) assert_array_almost_equal(r, [0., 0.], decimal=2) r = r2_score([[0, -1], [0, 1]], [[2, 2], [1, 1]], multioutput='raw_values') @@ -330,3 +352,87 @@ def test_mean_absolute_percentage_error(): y_true = random_number_generator.exponential(size=100) y_pred = 1.2 * y_true assert mean_absolute_percentage_error(y_true, y_pred) == pytest.approx(0.2) + + [email protected]("distribution", + ["normal", "lognormal", "exponential", "uniform"]) [email protected]("target_quantile", [0.05, 0.5, 0.75]) +def test_mean_pinball_loss_on_constant_predictions( + distribution, + target_quantile +): + if not hasattr(np, "quantile"): + pytest.skip("This test requires a more recent version of numpy " + "with support for np.quantile.") + + # Check that the pinball loss is minimized by the empirical quantile. + n_samples = 3000 + rng = np.random.RandomState(42) + data = getattr(rng, distribution)(size=n_samples) + + # Compute the best possible pinball loss for any constant predictor: + best_pred = np.quantile(data, target_quantile) + best_constant_pred = np.full(n_samples, fill_value=best_pred) + best_pbl = mean_pinball_loss(data, best_constant_pred, + alpha=target_quantile) + + # Evaluate the loss on a grid of quantiles + candidate_predictions = np.quantile(data, np.linspace(0, 1, 100)) + for pred in candidate_predictions: + # Compute the pinball loss of a constant predictor: + constant_pred = np.full(n_samples, fill_value=pred) + pbl = mean_pinball_loss(data, constant_pred, alpha=target_quantile) + + # Check that the loss of this constant predictor is greater or equal + # than the loss of using the optimal quantile (up to machine + # precision): + assert pbl >= best_pbl - np.finfo(best_pbl.dtype).eps + + # Check that the value of the pinball loss matches the analytical + # formula. + expected_pbl = ( + (pred - data[data < pred]).sum() * (1 - target_quantile) + + (data[data >= pred] - pred).sum() * target_quantile + ) + expected_pbl /= n_samples + assert_almost_equal(expected_pbl, pbl) + + # Check that we can actually recover the target_quantile by minimizing the + # pinball loss w.r.t. the constant prediction quantile. + def objective_func(x): + constant_pred = np.full(n_samples, fill_value=x) + return mean_pinball_loss(data, constant_pred, alpha=target_quantile) + + result = optimize.minimize(objective_func, data.mean(), + method="Nelder-Mead") + assert result.success + # The minimum is not unique with limited data, hence the large tolerance. + assert result.x == pytest.approx(best_pred, rel=1e-2) + assert result.fun == pytest.approx(best_pbl) + + +def test_dummy_quantile_parameter_tuning(): + # Integration test to check that it is possible to use the pinball loss to + # tune the hyperparameter of a quantile regressor. This is conceptually + # similar to the previous test but using the scikit-learn estimator and + # scoring API instead. + n_samples = 1000 + rng = np.random.RandomState(0) + X = rng.normal(size=(n_samples, 5)) # Ignored + y = rng.exponential(size=n_samples) + + all_quantiles = [0.05, 0.1, 0.25, 0.5, 0.75, 0.9, 0.95] + for alpha in all_quantiles: + neg_mean_pinball_loss = make_scorer( + mean_pinball_loss, + alpha=alpha, + greater_is_better=False, + ) + regressor = DummyRegressor(strategy="quantile", quantile=0.25) + grid_search = GridSearchCV( + regressor, + param_grid=dict(quantile=all_quantiles), + scoring=neg_mean_pinball_loss, + ).fit(X, y) + + assert grid_search.best_params_["quantile"] == pytest.approx(alpha)
[ { "path": "doc/modules/classes.rst", "old_path": "a/doc/modules/classes.rst", "new_path": "b/doc/modules/classes.rst", "metadata": "diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst\nindex 65d555f978df0..c658bc6b12452 100644\n--- a/doc/modules/classes.rst\n+++ b/doc/modules/classes.rst\n@@ -991,6 +991,7 @@ details.\n metrics.mean_poisson_deviance\n metrics.mean_gamma_deviance\n metrics.mean_tweedie_deviance\n+ metrics.mean_pinball_loss\n \n Multilabel ranking metrics\n --------------------------\n" }, { "path": "doc/modules/model_evaluation.rst", "old_path": "a/doc/modules/model_evaluation.rst", "new_path": "b/doc/modules/model_evaluation.rst", "metadata": "diff --git a/doc/modules/model_evaluation.rst b/doc/modules/model_evaluation.rst\nindex 86e64f997cdd8..c807af982e277 100644\n--- a/doc/modules/model_evaluation.rst\n+++ b/doc/modules/model_evaluation.rst\n@@ -416,7 +416,7 @@ defined as\n \n .. math::\n \n- \\texttt{accuracy}(y, \\hat{y}) = \\frac{1}{n_\\text{samples}} \\sum_{i=0}^{n_\\text{samples}-1} 1(\\hat{y}_i = y_i)\n+ \\texttt{accuracy}(y, \\hat{y}) = \\frac{1}{n_\\text{samples}} \\sum_{i=0}^{n_\\text{samples}-1} 1(\\hat{y}_i = y_i)\n \n where :math:`1(x)` is the `indicator function\n <https://en.wikipedia.org/wiki/Indicator_function>`_.\n@@ -1960,8 +1960,8 @@ Regression metrics\n The :mod:`sklearn.metrics` module implements several loss, score, and utility\n functions to measure regression performance. Some of those have been enhanced\n to handle the multioutput case: :func:`mean_squared_error`,\n-:func:`mean_absolute_error`, :func:`explained_variance_score` and\n-:func:`r2_score`.\n+:func:`mean_absolute_error`, :func:`explained_variance_score`,\n+:func:`r2_score` and :func:`mean_pinball_loss`.\n \n \n These functions have an ``multioutput`` keyword argument which specifies the\n@@ -2354,6 +2354,71 @@ the difference in errors decreases. Finally, by setting, ``power=2``::\n we would get identical errors. The deviance when ``power=2`` is thus only\n sensitive to relative errors.\n \n+.. _pinball_loss:\n+\n+Pinball loss\n+------------\n+\n+The :func:`mean_pinball_loss` function is used to evaluate the predictive\n+performance of quantile regression models. The `pinball loss\n+<https://en.wikipedia.org/wiki/Quantile_regression#Computation>`_ is equivalent\n+to :func:`mean_absolute_error` when the quantile parameter ``alpha`` is set to\n+0.5.\n+\n+.. math::\n+\n+ \\text{pinball}(y, \\hat{y}) = \\frac{1}{n_{\\text{samples}}} \\sum_{i=0}^{n_{\\text{samples}}-1} \\alpha \\max(y_i - \\hat{y}_i, 0) + (1 - \\alpha) \\max(\\hat{y}_i - y_i, 0)\n+\n+Here is a small example of usage of the :func:`mean_pinball_loss` function::\n+\n+ >>> from sklearn.metrics import mean_pinball_loss\n+ >>> y_true = [1, 2, 3]\n+ >>> mean_pinball_loss(y_true, [0, 2, 3], alpha=0.1)\n+ 0.03...\n+ >>> mean_pinball_loss(y_true, [1, 2, 4], alpha=0.1)\n+ 0.3...\n+ >>> mean_pinball_loss(y_true, [0, 2, 3], alpha=0.9)\n+ 0.3...\n+ >>> mean_pinball_loss(y_true, [1, 2, 4], alpha=0.9)\n+ 0.03...\n+ >>> mean_pinball_loss(y_true, y_true, alpha=0.1)\n+ 0.0\n+ >>> mean_pinball_loss(y_true, y_true, alpha=0.9)\n+ 0.0\n+\n+It is possible to build a scorer object with a specific choice of alpha::\n+\n+ >>> from sklearn.metrics import make_scorer\n+ >>> mean_pinball_loss_95p = make_scorer(mean_pinball_loss, alpha=0.95)\n+\n+Such a scorer can be used to evaluate the generalization performance of a\n+quantile regressor via cross-validation:\n+\n+ >>> from sklearn.datasets import make_regression\n+ >>> from sklearn.model_selection import cross_val_score\n+ >>> from sklearn.ensemble import GradientBoostingRegressor\n+ >>>\n+ >>> X, y = make_regression(n_samples=100, random_state=0)\n+ >>> estimator = GradientBoostingRegressor(\n+ ... loss=\"quantile\",\n+ ... alpha=0.95,\n+ ... random_state=0,\n+ ... )\n+ >>> cross_val_score(estimator, X, y, cv=5, scoring=mean_pinball_loss_95p)\n+ array([11.1..., 10.4... , 24.4..., 9.2..., 12.9...])\n+\n+It is also possible to build scorer objects for hyper-parameter tuning. The\n+sign of the loss must be switched to ensure that greater means better as\n+explained in the example linked below.\n+\n+.. topic:: Example:\n+\n+ * See :ref:`sphx_glr_auto_examples_ensemble_plot_gradient_boosting_quantile.py`\n+ for an example of using a the pinball loss to evaluate and tune the\n+ hyper-parameters of quantile regression models on data with non-symmetric\n+ noise and outliers.\n+\n+\n .. _clustering_metrics:\n \n Clustering metrics\n" }, { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 3086d91b28f5d..582d6872f59cb 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -134,6 +134,10 @@ Changelog\n class methods and will be removed in 1.2.\n :pr:`18543` by `Guillaume Lemaitre`_.\n \n+- |Feature| :func:`metrics.mean_pinball_loss` exposes the pinball loss for\n+ quantile regression. :pr:`19415` by :user:`Xavier Dupré <sdpython>`\n+ and :user:`Oliver Grisel <ogrisel>`.\n+\n :mod:`sklearn.naive_bayes`\n ..........................\n \n" } ]
1.00
5403e9fdaee6d4982c887ce2ae9a62ccd3955fbb
[]
[ "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric18]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[matthews_corrcoef_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_single_sample[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric21]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric37]", "sklearn/metrics/tests/test_common.py::test_single_sample[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[macro_f1_score]", "sklearn/metrics/tests/test_regression.py::test__check_reg_targets_exception", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_normal_deviance]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric41]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[micro_recall_score]", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.75-uniform]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric29]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric29]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[f2_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric10]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric15]", "sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py::test_sample_weight_init_estimators", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric35]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-explained_variance_score]", "sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py::test_mdl_exception[2]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric3]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[roc_auc_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[label_ranking_loss]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multiclass[f1_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric38]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric33]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric40]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[object-f1_score-False]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[precision_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric10]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric8]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-multilabel_confusion_matrix]", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.05-uniform]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric28]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_ovo_roc_auc]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-matthews_corrcoef]", "sklearn/metrics/tests/test_common.py::test_single_sample[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_zeroes[f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric22]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric33]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric10]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric36]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric34]", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric38]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric9]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric17]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric38]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[log_loss]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric30]", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.75-exponential]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric23]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_zeroes[f0.5_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[hinge_loss]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[brier_score_loss]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric34]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric27]", "sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py::test_lad_equals_quantiles[0.4-0]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric19]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_zeroes[recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric18]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_ones[f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-label_ranking_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric10]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-label_ranking_loss]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_absolute_error]", "sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py::test_lad_equals_quantiles[0.5-0]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[f1_score]", "sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py::test_lad_equals_quantiles[0.5-4]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[r2_score]", "sklearn/metrics/tests/test_regression.py::test_mean_squared_error_multioutput_raw_value_squared", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric16]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-hinge_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-max_error]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_normal_deviance]", "sklearn/metrics/tests/test_common.py::test_averaging_multiclass[f0.5_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-hinge_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[label_ranking_loss]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[ndcg_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric15]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric39]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric13]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric10]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric18]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[partial_roc_auc]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[samples_roc_auc]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric18]", "sklearn/metrics/tests/test_common.py::test_single_sample[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[max_error]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[partial_roc_auc]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric18]", "sklearn/metrics/tests/test_common.py::test_single_sample[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-max_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-precision_score]", "sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py::test_lad_equals_quantiles[0.6-1]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[samples_precision_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric3]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-log_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_representation_invariance", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-average_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-matthews_corrcoef]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[roc_auc_score]", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.5-exponential]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric7]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-matthews_corrcoef]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[object-jaccard_score-False]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric16]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric23]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[f0.5_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-brier_score_loss]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric41]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric25]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric31]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric40]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[hinge_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric27]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric11]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-recall_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric35]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric36]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_recall_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[log_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[r2_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric40]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[samples_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric29]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric27]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[hinge_loss]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric17]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_compound_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-ndcg_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric18]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric39]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric3]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric32]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[samples_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric12]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[r2_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric30]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-hamming_loss]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric18]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric39]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric27]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric21]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[weighted_recall_score]", "sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py::test_init_raw_predictions_shapes", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric26]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric14]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric8]", "sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py::test_binomial_deviance", "sklearn/metrics/tests/test_common.py::test_normalize_option_binary_classification[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[ovo_roc_auc]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-<lambda>]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric39]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric37]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric32]", "sklearn/metrics/tests/test_common.py::test_normalize_option_multilabel_classification[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[samples_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[log_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-coverage_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric22]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[mean_compound_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric33]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-average_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_compound_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric30]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[roc_auc_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[hinge_loss]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-max_error]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[weighted_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric11]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric40]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric20]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[samples_precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[dcg_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric19]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[f0.5_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric17]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric25]", "sklearn/metrics/tests/test_regression.py::test_regression_metrics_at_limits", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric40]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric31]", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric31]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric10]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric9]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_compound_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric13]", "sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py::test_multinomial_deviance[3-100]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[matthews_corrcoef]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric24]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[coverage_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric7]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[weighted_roc_auc]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[samples_recall_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[average_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-jaccard_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric20]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_roc_auc]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric34]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric24]", "sklearn/metrics/tests/test_common.py::test_averaging_multiclass[recall_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[label_ranking_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric2]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric28]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[weighted_ovo_roc_auc]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_normalize_option_multiclass_classification[top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric15]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric35]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric20]", "sklearn/metrics/tests/test_common.py::test_single_sample[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric23]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-average_precision_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[unnormalized_log_loss]", "sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py::test_multinomial_deviance[7-13]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-coverage_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-hinge_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric16]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric19]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-dcg_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_normal_deviance]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric30]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[str-f1_score-False]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric31]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[dcg_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample[matthews_corrcoef_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-label_ranking_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric18]", "sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py::test_multinomial_deviance[5-57]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric31]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric12]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-label_ranking_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric8]", "sklearn/metrics/tests/test_common.py::test_single_sample[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric16]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric30]", "sklearn/metrics/tests/test_common.py::test_single_sample[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric22]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric30]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric33]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric2]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_roc_auc]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[coverage_error]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric3]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[str-jaccard_score-False]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-precision_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric14]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-hinge_loss]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[macro_f1_score]", "sklearn/metrics/tests/test_regression.py::test__check_reg_targets", "sklearn/metrics/tests/test_common.py::test_single_sample[r2_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric18]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[samples_recall_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric30]", "sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py::test_mdl_computation_weighted", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric23]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[samples_precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[micro_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric35]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric22]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[average_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-<lambda>]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[log_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric21]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-ndcg_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric32]", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.5-normal]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_f2_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[average_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-ndcg_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric19]", "sklearn/metrics/tests/test_common.py::test_single_sample[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[samples_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[object-average_precision_score-True]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-<lambda>]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric9]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric2]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_symmetry_consistency", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric24]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric25]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric12]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric16]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multiclass[f2_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-dcg_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric28]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric36]", "sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py::test_init_raw_predictions_values", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-dcg_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-label_ranking_loss]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_ones[precision_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[label_ranking_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[micro_average_precision_score]", "sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py::test_lad_equals_quantiles[0.5-3]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[samples_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric10]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric31]", "sklearn/metrics/tests/test_common.py::test_normalize_option_multiclass_classification[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[samples_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[str-precision_score-False]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[r2_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric7]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric34]", "sklearn/metrics/tests/test_common.py::test_single_sample[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric19]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric10]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[str-brier_score_loss-True]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric36]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric9]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-precision_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[hinge_loss]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric3]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[samples_roc_auc]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[log_loss]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_compound_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_f1_score]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[object-precision_recall_curve-True]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric30]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric39]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric28]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric23]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[roc_curve]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric41]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric3]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-roc_auc_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-<lambda>]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric39]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-label_ranking_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric26]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[samples_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[precision_recall_curve]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[weighted_ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric31]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric20]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-multilabel_confusion_matrix]", "sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py::test_lad_equals_quantiles[0.5-1]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric38]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric13]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric40]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric22]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric18]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[weighted_roc_auc]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric14]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[f0.5_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_ovo_roc_auc]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[log_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-recall_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[micro_roc_auc]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_ones[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[log_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric28]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[det_curve]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[samples_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric11]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric3]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[samples_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric2]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_single_sample[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_roc_auc]", "sklearn/metrics/tests/test_common.py::test_averaging_multiclass[precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric31]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric34]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric16]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-accuracy_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[r2_score]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[f1_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_ones[f2_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[macro_jaccard_score]", "sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py::test_sample_weight_deviance", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric25]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-dcg_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric15]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric32]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric16]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-hamming_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric7]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[unnormalized_multilabel_confusion_matrix]", "sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py::test_lad_equals_quantiles[0.6-0]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric31]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_single_sample[normalized_confusion_matrix]", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.05-normal]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[micro_jaccard_score]", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.5-uniform]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric7]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[weighted_ovo_roc_auc]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric22]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[label_ranking_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_normalize_option_multilabel_classification[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[precision_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[f0.5_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric37]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[object-brier_score_loss-True]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[object-metric3-False]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric28]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric37]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-label_ranking_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[log_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric37]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric21]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[matthews_corrcoef_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric21]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_absolute_error]", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.05-exponential]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric17]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[recall_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric3]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[partial_roc_auc]", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.75-normal]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-hinge_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-dcg_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[samples_f2_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-max_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-roc_auc_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric26]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[micro_roc_auc]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[samples_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_zeroes[f2_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[label_ranking_loss]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[samples_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-brier_score_loss]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric16]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[f2_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-coverage_error]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[samples_recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[str-average_precision_score-True]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric37]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric20]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric32]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-log_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-precision_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric31]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-label_ranking_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric29]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_pinball_loss]", "sklearn/metrics/tests/test_regression.py::test_regression_custom_weights", "sklearn/metrics/tests/test_common.py::test_single_sample[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric18]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-hamming_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric24]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric34]", "sklearn/metrics/tests/test_regression.py::test_regression_metrics", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[weighted_ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric27]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric33]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[matthews_corrcoef_score]", "sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py::test_lad_equals_quantiles[0.6-3]", "sklearn/metrics/tests/test_common.py::test_single_sample[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[samples_f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-recall_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[matthews_corrcoef_score]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[str-recall_score-False]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[partial_roc_auc]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[samples_f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric14]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric24]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[samples_f1_score]", "sklearn/metrics/tests/test_common.py::test_averaging_binary_multilabel_all_zeroes", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric31]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric36]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-hamming_loss]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[hinge_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric34]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric28]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[ndcg_score]", "sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py::test_sample_weight_smoke", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric3]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-brier_score_loss]", "sklearn/metrics/tests/test_regression.py::test_regression_multioutput_array", "sklearn/metrics/tests/test_common.py::test_normalize_option_binary_classification[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-coverage_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric32]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-hamming_loss]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[brier_score_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-log_loss]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[roc_auc_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[coverage_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric2]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric23]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_regression.py::test_tweedie_deviance_continuity", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[r2_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-matthews_corrcoef]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-coverage_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-label_ranking_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-precision_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[precision_recall_curve]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-ndcg_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric16]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric34]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric41]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-roc_auc_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric30]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[ovo_roc_auc]", "sklearn/metrics/tests/test_common.py::test_averaging_multiclass[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric34]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-ndcg_score]", "sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py::test_lad_equals_quantiles[0.4-1]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[recall_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric7]", "sklearn/metrics/tests/test_common.py::test_single_sample[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[det_curve]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric30]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric34]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric7]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric21]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric3]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_normalize_option_binary_classification[top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[average_precision_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[hinge_loss]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[object-recall_score-False]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric25]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric35]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric3]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[samples_f2_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[roc_auc_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric7]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-average_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric40]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[samples_recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric25]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric18]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric26]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric27]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_zeroes[precision_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[samples_roc_auc]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[object-precision_score-False]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-matthews_corrcoef]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric24]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[hamming_loss]", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.75-lognormal]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric8]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_normal_deviance]", "sklearn/metrics/tests/test_common.py::test_single_sample[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric12]", "sklearn/metrics/tests/test_common.py::test_single_sample[max_error]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[average_precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[ovo_roc_auc]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[max_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric7]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric29]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[samples_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric35]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-average_precision_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[ovo_roc_auc]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric23]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric22]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric11]", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.5-lognormal]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric10]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-<lambda>]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[partial_roc_auc]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric36]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric10]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-brier_score_loss]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[<lambda>]", "sklearn/metrics/tests/test_common.py::test_single_sample[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[str-roc_curve-True]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric2]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric7]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[samples_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_ones[f0.5_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-f1_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric9]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-hamming_loss]", "sklearn/metrics/tests/test_regression.py::test_mean_absolute_percentage_error", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[matthews_corrcoef_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric41]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric29]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[str-metric3-False]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric25]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[matthews_corrcoef_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric30]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[ndcg_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric33]", "sklearn/metrics/tests/test_common.py::test_normalize_option_multiclass_classification[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric19]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric7]", "sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py::test_lad_equals_quantiles[0.5-2]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric16]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric24]", "sklearn/metrics/tests/test_common.py::test_single_sample[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[r2_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric41]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric32]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[mean_normal_deviance]", "sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py::test_lad_equals_quantiles[0.6-4]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-roc_auc_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[f1_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric26]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric2]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric38]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[roc_curve]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric16]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric15]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric38]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[weighted_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric29]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-jaccard_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[unnormalized_multilabel_confusion_matrix_sample]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric16]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-label_ranking_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-matthews_corrcoef]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric30]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric37]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[f1_score]", "sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py::test_mdl_exception[0]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric39]", "sklearn/metrics/tests/test_regression.py::test_dummy_quantile_parameter_tuning", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric34]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric31]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[samples_f1_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[dcg_score]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[r2_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-log_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[samples_f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric26]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric41]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric19]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric20]", "sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py::test_mdl_exception[1]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-max_error]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[recall_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[matthews_corrcoef_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[weighted_f1_score]", "sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py::test_lad_equals_quantiles[0.4-2]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric8]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric3]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric20]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[samples_f0.5_score]", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.05-lognormal]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-roc_auc_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric15]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[r2_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric11]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric27]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric14]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_ones[recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric12]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[max_error]", "sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py::test_lad_equals_quantiles[0.4-4]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric26]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric36]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance_multilabel_and_multioutput", "sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py::test_quantile_loss_function", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_no_averaging_labels", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_roc_auc]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_zeroes[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[log_loss]", "sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py::test_lad_equals_quantiles[0.4-3]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_roc_auc]", "sklearn/metrics/tests/test_regression.py::test_regression_single_sample[r2_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[str-precision_recall_curve-True]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric21]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric34]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric38]", "sklearn/metrics/tests/test_common.py::test_single_sample[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-<lambda>]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[object-roc_curve-True]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric10]", "sklearn/metrics/tests/test_regression.py::test_multioutput_regression", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-brier_score_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric17]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[hamming_loss]", "sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py::test_lad_equals_quantiles[0.6-2]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric13]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric15]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric7]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric10]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric33]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-log_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric35]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric13]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/modules/classes.rst", "old_path": "a/doc/modules/classes.rst", "new_path": "b/doc/modules/classes.rst", "metadata": "diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst\nindex 65d555f978df0..c658bc6b12452 100644\n--- a/doc/modules/classes.rst\n+++ b/doc/modules/classes.rst\n@@ -991,6 +991,7 @@ details.\n metrics.mean_poisson_deviance\n metrics.mean_gamma_deviance\n metrics.mean_tweedie_deviance\n+ metrics.mean_pinball_loss\n \n Multilabel ranking metrics\n --------------------------\n" }, { "path": "doc/modules/model_evaluation.rst", "old_path": "a/doc/modules/model_evaluation.rst", "new_path": "b/doc/modules/model_evaluation.rst", "metadata": "diff --git a/doc/modules/model_evaluation.rst b/doc/modules/model_evaluation.rst\nindex 86e64f997cdd8..c807af982e277 100644\n--- a/doc/modules/model_evaluation.rst\n+++ b/doc/modules/model_evaluation.rst\n@@ -416,7 +416,7 @@ defined as\n \n .. math::\n \n- \\texttt{accuracy}(y, \\hat{y}) = \\frac{1}{n_\\text{samples}} \\sum_{i=0}^{n_\\text{samples}-1} 1(\\hat{y}_i = y_i)\n+ \\texttt{accuracy}(y, \\hat{y}) = \\frac{1}{n_\\text{samples}} \\sum_{i=0}^{n_\\text{samples}-1} 1(\\hat{y}_i = y_i)\n \n where :math:`1(x)` is the `indicator function\n <https://en.wikipedia.org/wiki/Indicator_function>`_.\n@@ -1960,8 +1960,8 @@ Regression metrics\n The :mod:`sklearn.metrics` module implements several loss, score, and utility\n functions to measure regression performance. Some of those have been enhanced\n to handle the multioutput case: :func:`mean_squared_error`,\n-:func:`mean_absolute_error`, :func:`explained_variance_score` and\n-:func:`r2_score`.\n+:func:`mean_absolute_error`, :func:`explained_variance_score`,\n+:func:`r2_score` and :func:`mean_pinball_loss`.\n \n \n These functions have an ``multioutput`` keyword argument which specifies the\n@@ -2354,6 +2354,71 @@ the difference in errors decreases. Finally, by setting, ``power=2``::\n we would get identical errors. The deviance when ``power=2`` is thus only\n sensitive to relative errors.\n \n+.. _pinball_loss:\n+\n+Pinball loss\n+------------\n+\n+The :func:`mean_pinball_loss` function is used to evaluate the predictive\n+performance of quantile regression models. The `pinball loss\n+<https://en.wikipedia.org/wiki/Quantile_regression#Computation>`_ is equivalent\n+to :func:`mean_absolute_error` when the quantile parameter ``alpha`` is set to\n+0.5.\n+\n+.. math::\n+\n+ \\text{pinball}(y, \\hat{y}) = \\frac{1}{n_{\\text{samples}}} \\sum_{i=0}^{n_{\\text{samples}}-1} \\alpha \\max(y_i - \\hat{y}_i, 0) + (1 - \\alpha) \\max(\\hat{y}_i - y_i, 0)\n+\n+Here is a small example of usage of the :func:`mean_pinball_loss` function::\n+\n+ >>> from sklearn.metrics import mean_pinball_loss\n+ >>> y_true = [1, 2, 3]\n+ >>> mean_pinball_loss(y_true, [0, 2, 3], alpha=0.1)\n+ 0.03...\n+ >>> mean_pinball_loss(y_true, [1, 2, 4], alpha=0.1)\n+ 0.3...\n+ >>> mean_pinball_loss(y_true, [0, 2, 3], alpha=0.9)\n+ 0.3...\n+ >>> mean_pinball_loss(y_true, [1, 2, 4], alpha=0.9)\n+ 0.03...\n+ >>> mean_pinball_loss(y_true, y_true, alpha=0.1)\n+ 0.0\n+ >>> mean_pinball_loss(y_true, y_true, alpha=0.9)\n+ 0.0\n+\n+It is possible to build a scorer object with a specific choice of alpha::\n+\n+ >>> from sklearn.metrics import make_scorer\n+ >>> mean_pinball_loss_95p = make_scorer(mean_pinball_loss, alpha=0.95)\n+\n+Such a scorer can be used to evaluate the generalization performance of a\n+quantile regressor via cross-validation:\n+\n+ >>> from sklearn.datasets import make_regression\n+ >>> from sklearn.model_selection import cross_val_score\n+ >>> from sklearn.ensemble import GradientBoostingRegressor\n+ >>>\n+ >>> X, y = make_regression(n_samples=100, random_state=0)\n+ >>> estimator = GradientBoostingRegressor(\n+ ... loss=\"quantile\",\n+ ... alpha=0.95,\n+ ... random_state=0,\n+ ... )\n+ >>> cross_val_score(estimator, X, y, cv=5, scoring=mean_pinball_loss_95p)\n+ array([11.1..., 10.4... , 24.4..., 9.2..., 12.9...])\n+\n+It is also possible to build scorer objects for hyper-parameter tuning. The\n+sign of the loss must be switched to ensure that greater means better as\n+explained in the example linked below.\n+\n+.. topic:: Example:\n+\n+ * See :ref:`sphx_glr_auto_examples_ensemble_plot_gradient_boosting_quantile.py`\n+ for an example of using a the pinball loss to evaluate and tune the\n+ hyper-parameters of quantile regression models on data with non-symmetric\n+ noise and outliers.\n+\n+\n .. _clustering_metrics:\n \n Clustering metrics\n" }, { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 3086d91b28f5d..582d6872f59cb 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -134,6 +134,10 @@ Changelog\n class methods and will be removed in 1.2.\n :pr:`<PRID>` by `<NAME>`_.\n \n+- |Feature| :func:`metrics.mean_pinball_loss` exposes the pinball loss for\n+ quantile regression. :pr:`<PRID>` by :user:`<NAME>`\n+ and :user:`<NAME>`.\n+\n :mod:`sklearn.naive_bayes`\n ..........................\n \n" } ]
diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst index 65d555f978df0..c658bc6b12452 100644 --- a/doc/modules/classes.rst +++ b/doc/modules/classes.rst @@ -991,6 +991,7 @@ details. metrics.mean_poisson_deviance metrics.mean_gamma_deviance metrics.mean_tweedie_deviance + metrics.mean_pinball_loss Multilabel ranking metrics -------------------------- diff --git a/doc/modules/model_evaluation.rst b/doc/modules/model_evaluation.rst index 86e64f997cdd8..c807af982e277 100644 --- a/doc/modules/model_evaluation.rst +++ b/doc/modules/model_evaluation.rst @@ -416,7 +416,7 @@ defined as .. math:: - \texttt{accuracy}(y, \hat{y}) = \frac{1}{n_\text{samples}} \sum_{i=0}^{n_\text{samples}-1} 1(\hat{y}_i = y_i) + \texttt{accuracy}(y, \hat{y}) = \frac{1}{n_\text{samples}} \sum_{i=0}^{n_\text{samples}-1} 1(\hat{y}_i = y_i) where :math:`1(x)` is the `indicator function <https://en.wikipedia.org/wiki/Indicator_function>`_. @@ -1960,8 +1960,8 @@ Regression metrics The :mod:`sklearn.metrics` module implements several loss, score, and utility functions to measure regression performance. Some of those have been enhanced to handle the multioutput case: :func:`mean_squared_error`, -:func:`mean_absolute_error`, :func:`explained_variance_score` and -:func:`r2_score`. +:func:`mean_absolute_error`, :func:`explained_variance_score`, +:func:`r2_score` and :func:`mean_pinball_loss`. These functions have an ``multioutput`` keyword argument which specifies the @@ -2354,6 +2354,71 @@ the difference in errors decreases. Finally, by setting, ``power=2``:: we would get identical errors. The deviance when ``power=2`` is thus only sensitive to relative errors. +.. _pinball_loss: + +Pinball loss +------------ + +The :func:`mean_pinball_loss` function is used to evaluate the predictive +performance of quantile regression models. The `pinball loss +<https://en.wikipedia.org/wiki/Quantile_regression#Computation>`_ is equivalent +to :func:`mean_absolute_error` when the quantile parameter ``alpha`` is set to +0.5. + +.. math:: + + \text{pinball}(y, \hat{y}) = \frac{1}{n_{\text{samples}}} \sum_{i=0}^{n_{\text{samples}}-1} \alpha \max(y_i - \hat{y}_i, 0) + (1 - \alpha) \max(\hat{y}_i - y_i, 0) + +Here is a small example of usage of the :func:`mean_pinball_loss` function:: + + >>> from sklearn.metrics import mean_pinball_loss + >>> y_true = [1, 2, 3] + >>> mean_pinball_loss(y_true, [0, 2, 3], alpha=0.1) + 0.03... + >>> mean_pinball_loss(y_true, [1, 2, 4], alpha=0.1) + 0.3... + >>> mean_pinball_loss(y_true, [0, 2, 3], alpha=0.9) + 0.3... + >>> mean_pinball_loss(y_true, [1, 2, 4], alpha=0.9) + 0.03... + >>> mean_pinball_loss(y_true, y_true, alpha=0.1) + 0.0 + >>> mean_pinball_loss(y_true, y_true, alpha=0.9) + 0.0 + +It is possible to build a scorer object with a specific choice of alpha:: + + >>> from sklearn.metrics import make_scorer + >>> mean_pinball_loss_95p = make_scorer(mean_pinball_loss, alpha=0.95) + +Such a scorer can be used to evaluate the generalization performance of a +quantile regressor via cross-validation: + + >>> from sklearn.datasets import make_regression + >>> from sklearn.model_selection import cross_val_score + >>> from sklearn.ensemble import GradientBoostingRegressor + >>> + >>> X, y = make_regression(n_samples=100, random_state=0) + >>> estimator = GradientBoostingRegressor( + ... loss="quantile", + ... alpha=0.95, + ... random_state=0, + ... ) + >>> cross_val_score(estimator, X, y, cv=5, scoring=mean_pinball_loss_95p) + array([11.1..., 10.4... , 24.4..., 9.2..., 12.9...]) + +It is also possible to build scorer objects for hyper-parameter tuning. The +sign of the loss must be switched to ensure that greater means better as +explained in the example linked below. + +.. topic:: Example: + + * See :ref:`sphx_glr_auto_examples_ensemble_plot_gradient_boosting_quantile.py` + for an example of using a the pinball loss to evaluate and tune the + hyper-parameters of quantile regression models on data with non-symmetric + noise and outliers. + + .. _clustering_metrics: Clustering metrics diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index 3086d91b28f5d..582d6872f59cb 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -134,6 +134,10 @@ Changelog class methods and will be removed in 1.2. :pr:`<PRID>` by `<NAME>`_. +- |Feature| :func:`metrics.mean_pinball_loss` exposes the pinball loss for + quantile regression. :pr:`<PRID>` by :user:`<NAME>` + and :user:`<NAME>`. + :mod:`sklearn.naive_bayes` ..........................
scikit-learn/scikit-learn
scikit-learn__scikit-learn-20231
https://github.com/scikit-learn/scikit-learn/pull/20231
diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index 9689cd8789a7a..4f952758691f7 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -405,6 +405,12 @@ Changelog :user:`Oliver Grisel <ogrisel>` and :user:`Christian Lorentzen <lorentzenchr>`. +- |Feature| Added new solver `lbfgs` (available with `solver="lbfgs") + and `positive` argument to class:`linear_model.Ridge`. + When `positive` is set to True, forces the coefficients to be positive + (only supported by `lbfgs`). + :pr:`20231` by :user:`Toshihiro Nakae <tnakae>`. + :mod:`sklearn.manifold` ....................... diff --git a/sklearn/linear_model/_ridge.py b/sklearn/linear_model/_ridge.py index b47276d7787e7..18cdead844f43 100644 --- a/sklearn/linear_model/_ridge.py +++ b/sklearn/linear_model/_ridge.py @@ -15,6 +15,7 @@ import numpy as np from scipy import linalg from scipy import sparse +from scipy import optimize from scipy.sparse import linalg as sp_linalg from ._base import LinearClassifierMixin, LinearModel @@ -235,6 +236,64 @@ def _solve_svd(X, y, alpha): return np.dot(Vt.T, d_UT_y).T +def _solve_lbfgs( + X, y, alpha, positive=True, max_iter=None, tol=1e-3, X_offset=None, X_scale=None +): + """Solve ridge regression with LBFGS. + + The main purpose is fitting with forcing coefficients to be positive. + For unconstrained ridge regression, there are faster dedicated solver methods. + Note that with positive bounds on the coefficients, LBFGS seems faster + than scipy.optimize.lsq_linear. + """ + n_samples, n_features = X.shape + + options = {} + if max_iter is not None: + options["maxiter"] = max_iter + config = { + "method": "L-BFGS-B", + "tol": tol, + "jac": True, + "options": options, + } + if positive: + config["bounds"] = [(0, np.inf)] * n_features + + if X_offset is not None and X_scale is not None: + X_offset_scale = X_offset / X_scale + else: + X_offset_scale = None + + coefs = np.empty((y.shape[1], n_features), dtype=X.dtype) + + for i in range(y.shape[1]): + x0 = np.zeros((n_features,)) + y_column = y[:, i] + + def func(w): + residual = X.dot(w) - y_column + if X_offset_scale is not None: + residual -= w.dot(X_offset_scale) + f = 0.5 * residual.dot(residual) + 0.5 * alpha[i] * w.dot(w) + grad = X.T @ residual + alpha[i] * w + if X_offset_scale is not None: + grad -= X_offset_scale * np.sum(residual) + + return f, grad + + result = optimize.minimize(func, x0, **config) + if not result["success"]: + warnings.warn( + "The lbfgs solver did not converge. Try increasing max_iter " + f"or tol. Currently: max_iter={max_iter} and tol={tol}", + ConvergenceWarning, + ) + coefs[i] = result["x"] + + return coefs + + def _get_valid_accept_sparse(is_X_sparse, solver): if is_X_sparse and solver in ["auto", "sag", "saga"]: return "csr" @@ -252,6 +311,7 @@ def ridge_regression( max_iter=None, tol=1e-3, verbose=0, + positive=False, random_state=None, return_n_iter=False, return_intercept=False, @@ -287,8 +347,8 @@ def ridge_regression( .. versionadded:: 0.17 - solver : {'auto', 'svd', 'cholesky', 'lsqr', 'sparse_cg', 'sag', 'saga'}, \ - default='auto' + solver : {'auto', 'svd', 'cholesky', 'lsqr', 'sparse_cg', \ + 'sag', 'saga', 'lbfgs'}, default='auto' Solver to use in the computational routines: - 'auto' chooses the solver automatically based on the type of data. @@ -317,10 +377,13 @@ def ridge_regression( approximately the same scale. You can preprocess the data with a scaler from sklearn.preprocessing. + - 'lbfgs' uses L-BFGS-B algorithm implemented in + `scipy.optimize.minimize`. It can be used only when `positive` + is True. - All last five solvers support both dense and sparse data. However, only - 'sag' and 'sparse_cg' supports sparse input when `fit_intercept` is - True. + All last six solvers support both dense and sparse data. However, only + 'sag', 'sparse_cg', and 'lbfgs' support sparse input when `fit_intercept` + is True. .. versionadded:: 0.17 Stochastic Average Gradient descent solver. @@ -331,7 +394,7 @@ def ridge_regression( Maximum number of iterations for conjugate gradient solver. For the 'sparse_cg' and 'lsqr' solvers, the default value is determined by scipy.sparse.linalg. For 'sag' and saga solver, the default value is - 1000. + 1000. For 'lbfgs' solver, the default value is 15000. tol : float, default=1e-3 Precision of the solution. @@ -340,6 +403,10 @@ def ridge_regression( Verbosity level. Setting verbose > 0 will display additional information depending on the solver used. + positive : bool, default=False + When set to ``True``, forces the coefficients to be positive. + Only 'lbfgs' solver is supported in this case. + random_state : int, RandomState instance, default=None Used when ``solver`` == 'sag' or 'saga' to shuffle the data. See :term:`Glossary <random_state>` for details. @@ -389,6 +456,7 @@ def ridge_regression( max_iter=max_iter, tol=tol, verbose=verbose, + positive=positive, random_state=random_state, return_n_iter=return_n_iter, return_intercept=return_intercept, @@ -407,6 +475,7 @@ def _ridge_regression( max_iter=None, tol=1e-3, verbose=0, + positive=False, random_state=None, return_n_iter=False, return_intercept=False, @@ -418,18 +487,33 @@ def _ridge_regression( has_sw = sample_weight is not None if solver == "auto": - if return_intercept: - # only sag supports fitting intercept directly + if positive: + solver = "lbfgs" + elif return_intercept: + # sag supports fitting intercept directly solver = "sag" elif not sparse.issparse(X): solver = "cholesky" else: solver = "sparse_cg" - if solver not in ("sparse_cg", "cholesky", "svd", "lsqr", "sag", "saga"): + if solver not in ("sparse_cg", "cholesky", "svd", "lsqr", "sag", "saga", "lbfgs"): raise ValueError( "Known solvers are 'sparse_cg', 'cholesky', 'svd'" - " 'lsqr', 'sag' or 'saga'. Got %s." % solver + " 'lsqr', 'sag', 'saga' or 'lbfgs'. Got %s." % solver + ) + + if positive and solver != "lbfgs": + raise ValueError( + "When positive=True, only 'lbfgs' solver can be used. " + f"Please change solver {solver} to 'lbfgs' " + "or set positive=False." + ) + + if solver == "lbfgs" and not positive: + raise ValueError( + "'lbfgs' solver can be used only when positive=True. " + "Please use another solver." ) if return_intercept and solver != "sag": @@ -554,6 +638,18 @@ def _ridge_regression( intercept = intercept[0] coef = np.asarray(coef) + elif solver == "lbfgs": + coef = _solve_lbfgs( + X, + y, + alpha, + positive=positive, + tol=tol, + max_iter=max_iter, + X_offset=X_offset, + X_scale=X_scale, + ) + if solver == "svd": if sparse.issparse(X): raise TypeError("SVD solver does not support sparse inputs currently") @@ -585,6 +681,7 @@ def __init__( max_iter=None, tol=1e-3, solver="auto", + positive=False, random_state=None, ): self.alpha = alpha @@ -594,6 +691,7 @@ def __init__( self.max_iter = max_iter self.tol = tol self.solver = solver + self.positive = positive self.random_state = random_state def fit(self, X, y, sample_weight=None): @@ -612,16 +710,31 @@ def fit(self, X, y, sample_weight=None): multi_output=True, y_numeric=True, ) - if sparse.issparse(X) and self.fit_intercept: - if self.solver not in ["auto", "sparse_cg", "sag"]: + if self.solver == "lbfgs" and not self.positive: + raise ValueError( + "'lbfgs' solver can be used only when positive=True. " + "Please use another solver." + ) + + if self.positive: + if self.solver not in ["auto", "lbfgs"]: + raise ValueError( + f"solver='{self.solver}' does not support positive fitting. Please" + " set the solver to 'auto' or 'lbfgs', or set `positive=False`" + ) + else: + solver = self.solver + elif sparse.issparse(X) and self.fit_intercept: + if self.solver not in ["auto", "sparse_cg", "sag", "lbfgs"]: raise ValueError( "solver='{}' does not support fitting the intercept " "on sparse data. Please set the solver to 'auto' or " - "'sparse_cg', 'sag', or set `fit_intercept=False`".format( - self.solver - ) + "'sparse_cg', 'sag', 'lbfgs' " + "or set `fit_intercept=False`".format(self.solver) ) - if self.solver == "sag" and self.max_iter is None and self.tol > 1e-4: + if self.solver == "lbfgs": + solver = "lbfgs" + elif self.solver == "sag" and self.max_iter is None and self.tol > 1e-4: warnings.warn( '"sag" solver requires many iterations to fit ' "an intercept with sparse inputs. Either set the " @@ -658,6 +771,7 @@ def fit(self, X, y, sample_weight=None): max_iter=self.max_iter, tol=self.tol, solver="sag", + positive=self.positive, random_state=self.random_state, return_n_iter=True, return_intercept=True, @@ -682,6 +796,7 @@ def fit(self, X, y, sample_weight=None): max_iter=self.max_iter, tol=self.tol, solver=solver, + positive=self.positive, random_state=self.random_state, return_n_iter=True, return_intercept=False, @@ -744,12 +859,13 @@ class Ridge(MultiOutputMixin, RegressorMixin, _BaseRidge): Maximum number of iterations for conjugate gradient solver. For 'sparse_cg' and 'lsqr' solvers, the default value is determined by scipy.sparse.linalg. For 'sag' solver, the default value is 1000. + For 'lbfgs' solver, the default value is 15000. tol : float, default=1e-3 Precision of the solution. - solver : {'auto', 'svd', 'cholesky', 'lsqr', 'sparse_cg', 'sag', 'saga'}, \ - default='auto' + solver : {'auto', 'svd', 'cholesky', 'lsqr', 'sparse_cg', \ + 'sag', 'saga', 'lbfgs'}, default='auto' Solver to use in the computational routines: - 'auto' chooses the solver automatically based on the type of data. @@ -777,15 +893,23 @@ class Ridge(MultiOutputMixin, RegressorMixin, _BaseRidge): approximately the same scale. You can preprocess the data with a scaler from sklearn.preprocessing. - All last five solvers support both dense and sparse data. However, only - 'sag' and 'sparse_cg' supports sparse input when `fit_intercept` is - True. + - 'lbfgs' uses L-BFGS-B algorithm implemented in + `scipy.optimize.minimize`. It can be used only when `positive` + is True. + + All last six solvers support both dense and sparse data. However, only + 'sag', 'sparse_cg', and 'lbfgs' support sparse input when `fit_intercept` + is True. .. versionadded:: 0.17 Stochastic Average Gradient descent solver. .. versionadded:: 0.19 SAGA solver. + positive : bool, default=False + When set to ``True``, forces the coefficients to be positive. + Only 'lbfgs' solver is supported in this case. + random_state : int, RandomState instance, default=None Used when ``solver`` == 'sag' or 'saga' to shuffle the data. See :term:`Glossary <random_state>` for details. @@ -843,6 +967,7 @@ def __init__( max_iter=None, tol=1e-3, solver="auto", + positive=False, random_state=None, ): super().__init__( @@ -853,6 +978,7 @@ def __init__( max_iter=max_iter, tol=tol, solver=solver, + positive=positive, random_state=random_state, ) @@ -932,8 +1058,8 @@ class RidgeClassifier(LinearClassifierMixin, _BaseRidge): weights inversely proportional to class frequencies in the input data as ``n_samples / (n_classes * np.bincount(y))``. - solver : {'auto', 'svd', 'cholesky', 'lsqr', 'sparse_cg', 'sag', 'saga'}, \ - default='auto' + solver : {'auto', 'svd', 'cholesky', 'lsqr', 'sparse_cg', \ + 'sag', 'saga', 'lbfgs'}, default='auto' Solver to use in the computational routines: - 'auto' chooses the solver automatically based on the type of data. @@ -966,6 +1092,14 @@ class RidgeClassifier(LinearClassifierMixin, _BaseRidge): .. versionadded:: 0.19 SAGA solver. + - 'lbfgs' uses L-BFGS-B algorithm implemented in + `scipy.optimize.minimize`. It can be used only when `positive` + is True. + + positive : bool, default=False + When set to ``True``, forces the coefficients to be positive. + Only 'lbfgs' solver is supported in this case. + random_state : int, RandomState instance, default=None Used when ``solver`` == 'sag' or 'saga' to shuffle the data. See :term:`Glossary <random_state>` for details. @@ -1025,6 +1159,7 @@ def __init__( tol=1e-3, class_weight=None, solver="auto", + positive=False, random_state=None, ): super().__init__( @@ -1035,6 +1170,7 @@ def __init__( max_iter=max_iter, tol=tol, solver=solver, + positive=positive, random_state=random_state, ) self.class_weight = class_weight
diff --git a/sklearn/linear_model/tests/test_ridge.py b/sklearn/linear_model/tests/test_ridge.py index b933cf54964c9..bfc6722737bd8 100644 --- a/sklearn/linear_model/tests/test_ridge.py +++ b/sklearn/linear_model/tests/test_ridge.py @@ -29,6 +29,8 @@ from sklearn.linear_model import RidgeClassifierCV from sklearn.linear_model._ridge import _solve_cholesky from sklearn.linear_model._ridge import _solve_cholesky_kernel +from sklearn.linear_model._ridge import _solve_svd +from sklearn.linear_model._ridge import _solve_lbfgs from sklearn.linear_model._ridge import _check_gcv_mode from sklearn.linear_model._ridge import _X_CenterStackOp from sklearn.datasets import make_regression @@ -189,7 +191,7 @@ def test_ridge_sample_weights(): for (alpha, intercept, solver) in param_grid: # Ridge with explicit sample_weight - est = Ridge(alpha=alpha, fit_intercept=intercept, solver=solver, tol=1e-6) + est = Ridge(alpha=alpha, fit_intercept=intercept, solver=solver, tol=1e-12) est.fit(X, y, sample_weight=sample_weight) coefs = est.coef_ inter = est.intercept_ @@ -321,7 +323,7 @@ def test_ridge_individual_penalties(): ) coefs_indiv_pen = [ - Ridge(alpha=penalties, solver=solver, tol=1e-8).fit(X, y).coef_ + Ridge(alpha=penalties, solver=solver, tol=1e-12).fit(X, y).coef_ for solver in ["svd", "sparse_cg", "lsqr", "cholesky", "sag", "saga"] ] for coef_indiv_pen in coefs_indiv_pen: @@ -398,6 +400,7 @@ def _make_sparse_offset_regression( noise=30.0, shuffle=True, coef=False, + positive=False, random_state=None, ): X, y, c = make_regression( @@ -421,6 +424,9 @@ def _make_sparse_offset_regression( X[~mask] = 0.0 removed_X[mask] = 0.0 y -= removed_X.dot(c) + if positive: + y += X.dot(np.abs(c) + 1 - c) + c = np.abs(c) + 1 if n_features == 1: c = c[0] if coef: @@ -435,7 +441,8 @@ def _make_sparse_offset_regression( ( (solver, sparse_X) for (solver, sparse_X) in product( - ["cholesky", "sag", "sparse_cg", "lsqr", "saga", "ridgecv"], [False, True] + ["cholesky", "sag", "sparse_cg", "lsqr", "saga", "ridgecv"], + [False, True], ) if not (sparse_X and solver not in ["sparse_cg", "ridgecv"]) ), @@ -1267,13 +1274,16 @@ def test_n_iter(): assert reg.n_iter_ is None [email protected]("solver", ["sparse_cg", "auto"]) [email protected]("solver", ["sparse_cg", "lbfgs", "auto"]) def test_ridge_fit_intercept_sparse(solver): - X, y = _make_sparse_offset_regression(n_features=20, random_state=0) + positive = solver == "lbfgs" + X, y = _make_sparse_offset_regression( + n_features=20, random_state=0, positive=positive + ) X_csr = sp.csr_matrix(X) - # for now only sparse_cg can correctly fit an intercept with sparse X with - # default tol and max_iter. + # for now only sparse_cg and lbfgs can correctly fit an intercept + # with sparse X with default tol and max_iter. # sag is tested separately in test_ridge_fit_intercept_sparse_sag # because it requires more iterations and should raise a warning if default # max_iter is used. @@ -1284,8 +1294,8 @@ def test_ridge_fit_intercept_sparse(solver): # so the reference we use for both ("auto" and "sparse_cg") is # Ridge(solver="sparse_cg"), fitted using the dense representation (note # that "sparse_cg" can fit sparse or dense data) - dense_ridge = Ridge(solver="sparse_cg") - sparse_ridge = Ridge(solver=solver) + dense_ridge = Ridge(solver="sparse_cg", tol=1e-12) + sparse_ridge = Ridge(solver=solver, tol=1e-12, positive=positive) dense_ridge.fit(X, y) with pytest.warns(None) as record: sparse_ridge.fit(X_csr, y) @@ -1329,7 +1339,7 @@ def test_ridge_fit_intercept_sparse_sag(): @pytest.mark.parametrize("sample_weight", [None, np.ones(1000)]) @pytest.mark.parametrize("arr_type", [np.array, sp.csr_matrix]) @pytest.mark.parametrize( - "solver", ["auto", "sparse_cg", "cholesky", "lsqr", "sag", "saga"] + "solver", ["auto", "sparse_cg", "cholesky", "lsqr", "sag", "saga", "lbfgs"] ) def test_ridge_regression_check_arguments_validity( return_intercept, sample_weight, arr_type, solver @@ -1351,6 +1361,8 @@ def test_ridge_regression_check_arguments_validity( alpha, tol = 1e-3, 1e-6 atol = 1e-3 if _IS_32BIT else 1e-4 + positive = solver == "lbfgs" + if solver not in ["sag", "auto"] and return_intercept: with pytest.raises(ValueError, match="In Ridge, only 'sag' solver"): ridge_regression( @@ -1360,6 +1372,7 @@ def test_ridge_regression_check_arguments_validity( solver=solver, sample_weight=sample_weight, return_intercept=return_intercept, + positive=positive, tol=tol, ) return @@ -1370,6 +1383,7 @@ def test_ridge_regression_check_arguments_validity( alpha=alpha, solver=solver, sample_weight=sample_weight, + positive=positive, return_intercept=return_intercept, tol=tol, ) @@ -1389,11 +1403,12 @@ def test_ridge_classifier_no_support_multilabel(): @pytest.mark.parametrize( - "solver", ["svd", "sparse_cg", "cholesky", "lsqr", "sag", "saga"] + "solver", ["svd", "sparse_cg", "cholesky", "lsqr", "sag", "saga", "lbfgs"] ) def test_dtype_match(solver): rng = np.random.RandomState(0) alpha = 1.0 + positive = solver == "lbfgs" n_samples, n_features = 6, 5 X_64 = rng.randn(n_samples, n_features) @@ -1403,12 +1418,16 @@ def test_dtype_match(solver): tol = 2 * np.finfo(np.float32).resolution # Check type consistency 32bits - ridge_32 = Ridge(alpha=alpha, solver=solver, max_iter=500, tol=tol) + ridge_32 = Ridge( + alpha=alpha, solver=solver, max_iter=500, tol=tol, positive=positive + ) ridge_32.fit(X_32, y_32) coef_32 = ridge_32.coef_ # Check type consistency 64 bits - ridge_64 = Ridge(alpha=alpha, solver=solver, max_iter=500, tol=tol) + ridge_64 = Ridge( + alpha=alpha, solver=solver, max_iter=500, tol=tol, positive=positive + ) ridge_64.fit(X_64, y_64) coef_64 = ridge_64.coef_ @@ -1451,7 +1470,7 @@ def test_dtype_match_cholesky(): @pytest.mark.parametrize( - "solver", ["svd", "cholesky", "lsqr", "sparse_cg", "sag", "saga"] + "solver", ["svd", "cholesky", "lsqr", "sparse_cg", "sag", "saga", "lbfgs"] ) @pytest.mark.parametrize("seed", range(1)) def test_ridge_regression_dtype_stability(solver, seed): @@ -1461,6 +1480,7 @@ def test_ridge_regression_dtype_stability(solver, seed): coef = random_state.randn(n_features) y = np.dot(X, coef) + 0.01 * random_state.randn(n_samples) alpha = 1.0 + positive = solver == "lbfgs" results = dict() # XXX: Sparse CG seems to be far less numerically stable than the # others, maybe we should not enable float32 for this one. @@ -1473,6 +1493,7 @@ def test_ridge_regression_dtype_stability(solver, seed): solver=solver, random_state=random_state, sample_weight=None, + positive=positive, max_iter=500, tol=1e-10, return_n_iter=False, @@ -1494,11 +1515,150 @@ def test_ridge_sag_with_X_fortran(): Ridge(solver="sag").fit(X, y) [email protected]("solver", ["auto", "lbfgs"]) [email protected]("fit_intercept", [True, False]) [email protected]("alpha", [1e-3, 1e-2, 0.1, 1.0]) +def test_ridge_positive_regression_test(solver, fit_intercept, alpha): + """Test that positive Ridge finds true positive coefficients.""" + X = np.array([[1, 2], [3, 4], [5, 6], [7, 8]]) + coef = np.array([1, -10]) + if fit_intercept: + intercept = 20 + y = X.dot(coef) + intercept + else: + y = X.dot(coef) + + model = Ridge( + alpha=alpha, positive=True, solver=solver, fit_intercept=fit_intercept + ) + model.fit(X, y) + assert np.all(model.coef_ >= 0) + + [email protected]("fit_intercept", [True, False]) [email protected]("alpha", [1e-3, 1e-2, 0.1, 1.0]) +def test_ridge_ground_truth_positive_test(fit_intercept, alpha): + """Test that Ridge w/wo positive converges to the same solution. + + Ridge with positive=True and positive=False must give the same + when the ground truth coefs are all positive. + """ + rng = np.random.RandomState(42) + X = rng.randn(300, 100) + coef = rng.uniform(0.1, 1.0, size=X.shape[1]) + if fit_intercept: + intercept = 1 + y = X @ coef + intercept + else: + y = X @ coef + y += rng.normal(size=X.shape[0]) * 0.01 + + results = [] + for positive in [True, False]: + model = Ridge( + alpha=alpha, positive=positive, fit_intercept=fit_intercept, tol=1e-10 + ) + results.append(model.fit(X, y).coef_) + assert_allclose(*results, atol=1e-6, rtol=0) + + [email protected]( + "solver", ["svd", "cholesky", "lsqr", "sparse_cg", "sag", "saga"] +) +def test_ridge_positive_error_test(solver): + """Test input validation for positive argument in Ridge.""" + alpha = 0.1 + X = np.array([[1, 2], [3, 4]]) + coef = np.array([1, -1]) + y = X @ coef + + model = Ridge(alpha=alpha, positive=True, solver=solver, fit_intercept=False) + with pytest.raises(ValueError, match="does not support positive"): + model.fit(X, y) + + with pytest.raises(ValueError, match="only 'lbfgs' solver can be used"): + _, _ = ridge_regression( + X, y, alpha, positive=True, solver=solver, return_intercept=False + ) + + [email protected]("alpha", [1e-3, 1e-2, 0.1, 1.0]) +def test_positive_ridge_loss(alpha): + """Check ridge loss consistency when positive argument is enabled.""" + X, y = make_regression(n_samples=300, n_features=300, random_state=42) + alpha = 0.10 + n_checks = 100 + + def ridge_loss(model, random_state=None, noise_scale=1e-8): + intercept = model.intercept_ + if random_state is not None: + rng = np.random.RandomState(random_state) + coef = model.coef_ + rng.uniform(0, noise_scale, size=model.coef_.shape) + else: + coef = model.coef_ + + return 0.5 * np.sum((y - X @ coef - intercept) ** 2) + 0.5 * alpha * np.sum( + coef ** 2 + ) + + model = Ridge(alpha=alpha).fit(X, y) + model_positive = Ridge(alpha=alpha, positive=True).fit(X, y) + + # Check 1: + # Loss for solution found by Ridge(positive=False) + # is lower than that for solution found by Ridge(positive=True) + loss = ridge_loss(model) + loss_positive = ridge_loss(model_positive) + assert loss <= loss_positive + + # Check 2: + # Loss for solution found by Ridge(positive=True) + # is lower than that for small random positive perturbation + # of the positive solution. + for random_state in range(n_checks): + loss_perturbed = ridge_loss(model_positive, random_state=random_state) + assert loss_positive <= loss_perturbed + + [email protected]("alpha", [1e-3, 1e-2, 0.1, 1.0]) +def test_lbfgs_solver_consistency(alpha): + """Test that LBGFS gets almost the same coef of svd when positive=False.""" + X, y = make_regression(n_samples=300, n_features=300, random_state=42) + y = np.expand_dims(y, 1) + alpha = np.asarray([alpha]) + config = { + "positive": False, + "tol": 1e-16, + "max_iter": 500000, + } + + coef_lbfgs = _solve_lbfgs(X, y, alpha, **config) + coef_cholesky = _solve_svd(X, y, alpha) + assert_allclose(coef_lbfgs, coef_cholesky, atol=1e-4, rtol=0) + + +def test_lbfgs_solver_error(): + """Test that LBFGS solver raises ConvergenceWarning.""" + X = np.array([[1, -1], [1, 1]]) + y = np.array([-1e10, 1e10]) + + model = Ridge( + alpha=0.01, + solver="lbfgs", + fit_intercept=False, + tol=1e-12, + positive=True, + max_iter=1, + ) + with pytest.warns(ConvergenceWarning, match="lbfgs solver did not converge"): + model.fit(X, y) + + # FIXME: 'normalize' to be removed in 1.2 @pytest.mark.filterwarnings("ignore:'normalize' was deprecated") @pytest.mark.parametrize("normalize", [True, False]) @pytest.mark.parametrize( - "solver", ["cholesky", "lsqr", "sparse_cg", "svd", "sag", "saga"] + "solver", ["cholesky", "lsqr", "sparse_cg", "svd", "sag", "saga", "lbfgs"] ) def test_ridge_sample_weight_invariance(normalize, solver): """Test that Ridge fulfils sample weight invariance. @@ -1511,6 +1671,7 @@ def test_ridge_sample_weight_invariance(normalize, solver): normalize=normalize, solver=solver, tol=1e-12, + positive=(solver == "lbfgs"), ) reg = Ridge(**params) name = reg.__class__.__name__
[ { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 9689cd8789a7a..4f952758691f7 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -405,6 +405,12 @@ Changelog\n :user:`Oliver Grisel <ogrisel>` and\n :user:`Christian Lorentzen <lorentzenchr>`.\n \n+- |Feature| Added new solver `lbfgs` (available with `solver=\"lbfgs\")\n+ and `positive` argument to class:`linear_model.Ridge`.\n+ When `positive` is set to True, forces the coefficients to be positive\n+ (only supported by `lbfgs`).\n+ :pr:`20231` by :user:`Toshihiro Nakae <tnakae>`.\n+\n :mod:`sklearn.manifold`\n .......................\n \n" } ]
1.00
e4ef854d031854932b7165d55bfd04a400af6b85
[]
[ "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[1.0-True-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape0-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_class_weights", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[cholesky-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape0-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[lbfgs-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-csr_matrix-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape0-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape1-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge[svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-csr_matrix-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge[sparse_cg]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-cholesky]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape1-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape0-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_error[gcv]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-csr_matrix-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[0.1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-array-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape0-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-8-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-csr_matrix-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-csr_matrix-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape1-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[1.0-False-auto]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[True-shape2]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[SPARSE_FILTER-None-None]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-20-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_lbfgs_solver_error", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-20-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_tolerance]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_no_support_multilabel", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape1-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-array-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_error_test[cholesky]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-array-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[False-shape0]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape1-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[DENSE_FILTER-None-None]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_raises_value_error_if_sample_weights_greater_than_1d", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape1-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape0-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[False-shape4]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_sample_weight", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape1-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape0-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_class_weight_vs_sample_weight[RidgeClassifierCV]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-8-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_multi_ridge_diabetes]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-8-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-8-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape1-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_shapes", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[1.0-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape1-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_error[5]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[eigen-eigen-eigen-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape1-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-csr_matrix-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_lbfgs_solver_consistency[1.0]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-array-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_error_test[sag]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-array-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-20-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-array-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[svd-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_X_CenterStackOp[n_col0]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-csr_matrix-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[True-shape1]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[False-shape0]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[SPARSE_FILTER-cv1-_accuracy_callable]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[False-shape1]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[None-svd-eigen-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape1-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-20-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape1-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-8-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_X_CenterStackOp[n_col2]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-sparse_cg]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-csr_matrix-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-csr_matrix-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-20-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_error[1]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape1-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-array-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape1-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_lbfgs_solver_consistency[0.001]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-8-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_vs_lstsq", "sklearn/linear_model/tests/test_ridge.py::test_X_CenterStackOp[n_col1]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.001-True-auto]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_error_test[lsqr]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-array-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_sparse_design_with_sample_weights", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_raises_value_error_if_solver_not_supported", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[1.0-False-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape0-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-array-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape0-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-array-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-8-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_toy_ridge_object", "sklearn/linear_model/tests/test_ridge.py::test_ridge_fit_intercept_sparse_error[cholesky]", "sklearn/linear_model/tests/test_ridge.py::test_primal_dual_relationship", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape1-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-array-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_custom_scoring[SPARSE_FILTER-None]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-csr_matrix-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.001-False-auto]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_store_cv_values[None]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[DENSE_FILTER-None-_accuracy_callable]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_custom_scoring[DENSE_FILTER-cv1]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[False-shape2]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_store_cv_values[neg_mean_squared_error]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[True-shape0]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape1-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-20-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-8-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape0-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_singular", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[saga]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[auto-svd-eigen-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[0.01-True]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[sag]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-array-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_cv_values_not_stored[ridge0-make_regression]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-csr_matrix-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[True-shape4]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_cv_store_cv_values[_accuracy_callable]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-csr_matrix-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weights", "sklearn/linear_model/tests/test_ridge.py::test_positive_ridge_loss[0.01]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[SPARSE_FILTER-cv1-accuracy]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_best_score[3-ridge1-make_classification]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape0-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_ridge_loo]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[SPARSE_FILTER-cv1-None]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape1-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[lbfgs-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[0.1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-8-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-csr_matrix-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge[cholesky]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[True-shape0]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-20-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_n_iter", "sklearn/linear_model/tests/test_ridge.py::test_ridge_fit_intercept_sparse_error[svd]", "sklearn/linear_model/tests/test_ridge.py::test_lbfgs_solver_consistency[0.01]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape1-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-csr_matrix-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_negative_alphas", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-array-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape0-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-array-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_cv_values_not_stored[ridge1-make_classification]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-array-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_ridge_classifiers]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[False-shape3]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-8-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[None-svd-eigen-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.1-True-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[False-shape1]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_individual_penalties", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_sparse_cg_max_iter", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-csr_matrix-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_error_test[sparse_cg]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[0.001-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.1-False-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-20-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-20-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_positive_ridge_loss[0.001]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[1.0-True-auto]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sparse_svd", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.01-False-auto]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[True-shape3]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-array-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[0.001-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-array-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.001-True-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_custom_scoring[SPARSE_FILTER-cv1]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_cv_store_cv_values[None]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape0-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.01-False-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_intercept", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape0-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[True-shape3]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_class_weights_cv", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[lsqr-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-8-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[DENSE_FILTER-None-accuracy]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_error_test[saga]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-20-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.001-False-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[0.01-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-20-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[False-shape4]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-8-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-csr_matrix-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_positive_ridge_loss[1.0]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape0-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-csr_matrix-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.1-True-auto]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-sag]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_fit_intercept_sparse_error[lsqr]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[True-shape2]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_best_score[None-ridge1-make_classification]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[DENSE_FILTER-cv1-_accuracy_callable]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-csr_matrix-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape0-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape0-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape1-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-array-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-20-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[svd-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.1-False-auto]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sag_with_X_fortran", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-20-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-csr_matrix-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-array-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape0-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[sparse_cg]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_best_score[None-ridge0-make_regression]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-csr_matrix-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-saga]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_error[bad]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_positive_ridge_loss[0.1]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_loo_cv_asym_scoring", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape0-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-csr_matrix-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.01-True-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape0-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[SPARSE_FILTER-None-accuracy]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-csr_matrix-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-20-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_lbfgs_solver_consistency[0.1]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[eigen-eigen-eigen-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-array-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-csr_matrix-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[DENSE_FILTER-cv1-accuracy]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-20-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape1-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-array-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[True-shape4]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_int_alphas", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_best_score[3-ridge0-make_regression]", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_ridge_cv_normalize]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-8-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-csr_matrix-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_convergence_fail", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape1-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.01-True-auto]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-array-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[cholesky]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[False-shape2]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[svd-svd-svd-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[SPARSE_FILTER-None-_accuracy_callable]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[True-shape1]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-20-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-array-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_error[True]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[svd-svd-svd-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-csr_matrix-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-lsqr]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape1-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-array-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[auto-svd-eigen-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape0-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_store_cv_values[_mean_squared_error_callable]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-array-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape1-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-8-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match_cholesky", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-array-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_error_test[svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-array-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-csr_matrix-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_cv_individual_penalties", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[False-shape3]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-array-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_ridge_diabetes]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_sample_weights", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_ridge_cv]", "sklearn/linear_model/tests/test_ridge.py::test_ridge[lsqr]", "sklearn/linear_model/tests/test_ridge.py::test_class_weight_vs_sample_weight[RidgeClassifier]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-8-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-csr_matrix-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_fit_intercept_sparse_error[saga]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape0-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape0-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[1.0-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_cv_store_cv_values[accuracy]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape1-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_custom_scoring[DENSE_FILTER-None]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape0-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[DENSE_FILTER-cv1-None]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-8-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[lsqr]", "sklearn/linear_model/tests/test_ridge.py::test_ridge[sag]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-csr_matrix-None-False]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 9689cd8789a7a..4f952758691f7 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -405,6 +405,12 @@ Changelog\n :user:`<NAME>` and\n :user:`<NAME>`.\n \n+- |Feature| Added new solver `lbfgs` (available with `solver=\"lbfgs\")\n+ and `positive` argument to class:`linear_model.Ridge`.\n+ When `positive` is set to True, forces the coefficients to be positive\n+ (only supported by `lbfgs`).\n+ :pr:`<PRID>` by :user:`<NAME>`.\n+\n :mod:`sklearn.manifold`\n .......................\n \n" } ]
diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index 9689cd8789a7a..4f952758691f7 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -405,6 +405,12 @@ Changelog :user:`<NAME>` and :user:`<NAME>`. +- |Feature| Added new solver `lbfgs` (available with `solver="lbfgs") + and `positive` argument to class:`linear_model.Ridge`. + When `positive` is set to True, forces the coefficients to be positive + (only supported by `lbfgs`). + :pr:`<PRID>` by :user:`<NAME>`. + :mod:`sklearn.manifold` .......................
scikit-learn/scikit-learn
scikit-learn__scikit-learn-19643
https://github.com/scikit-learn/scikit-learn/pull/19643
diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index 3e36438dda095..06764d2be6003 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -165,6 +165,11 @@ Changelog class methods and will be removed in 1.2. :pr:`18543` by `Guillaume Lemaitre`_. +- |Enhancement| A fix to raise an error in :func:`metrics.hinge_loss` when + ``pred_decision`` is 1d whereas it is a multiclass classification or when + ``pred_decision`` parameter is not consistent with the ``labels`` parameter. + :pr:`19643` by :user:`Pierre Attard <PierreAttard>`. + - |Feature| :func:`metrics.mean_pinball_loss` exposes the pinball loss for quantile regression. :pr:`19415` by :user:`Xavier Dupré <sdpython>` and :user:`Oliver Grisel <ogrisel>`. diff --git a/sklearn/metrics/_classification.py b/sklearn/metrics/_classification.py index 708bde662e765..97ee5a2e01340 100644 --- a/sklearn/metrics/_classification.py +++ b/sklearn/metrics/_classification.py @@ -2370,11 +2370,29 @@ def hinge_loss(y_true, pred_decision, *, labels=None, sample_weight=None): pred_decision = check_array(pred_decision, ensure_2d=False) y_true = column_or_1d(y_true) y_true_unique = np.unique(labels if labels is not None else y_true) + if y_true_unique.size > 2: - if (labels is None and pred_decision.ndim > 1 and - (np.size(y_true_unique) != pred_decision.shape[1])): - raise ValueError("Please include all labels in y_true " - "or pass labels as third argument") + + if pred_decision.ndim <= 1: + raise ValueError("The shape of pred_decision cannot be 1d array" + "with a multiclass target. pred_decision shape " + "must be (n_samples, n_classes), that is " + f"({y_true.shape[0]}, {y_true_unique.size})." + f" Got: {pred_decision.shape}") + + # pred_decision.ndim > 1 is true + if y_true_unique.size != pred_decision.shape[1]: + if labels is None: + raise ValueError("Please include all labels in y_true " + "or pass labels as third argument") + else: + raise ValueError("The shape of pred_decision is not " + "consistent with the number of classes. " + "With a multiclass target, pred_decision " + "shape must be " + "(n_samples, n_classes), that is " + f"({y_true.shape[0]}, {y_true_unique.size}). " + f"Got: {pred_decision.shape}") if labels is None: labels = y_true_unique le = LabelEncoder()
diff --git a/sklearn/metrics/tests/test_classification.py b/sklearn/metrics/tests/test_classification.py index c32e9c89ada47..7b634e88f2275 100644 --- a/sklearn/metrics/tests/test_classification.py +++ b/sklearn/metrics/tests/test_classification.py @@ -4,6 +4,7 @@ from itertools import chain from itertools import permutations import warnings +import re import numpy as np from scipy import linalg @@ -2135,6 +2136,31 @@ def test_hinge_loss_multiclass_missing_labels_with_labels_none(): hinge_loss(y_true, pred_decision) +def test_hinge_loss_multiclass_no_consistent_pred_decision_shape(): + # test for inconsistency between multiclass problem and pred_decision + # argument + y_true = np.array([2, 1, 0, 1, 0, 1, 1]) + pred_decision = np.array([0, 1, 2, 1, 0, 2, 1]) + error_message = ("The shape of pred_decision cannot be 1d array" + "with a multiclass target. pred_decision shape " + "must be (n_samples, n_classes), that is " + "(7, 3). Got: (7,)") + with pytest.raises(ValueError, match=re.escape(error_message)): + hinge_loss(y_true=y_true, pred_decision=pred_decision) + + # test for inconsistency between pred_decision shape and labels number + pred_decision = np.array([[0, 1], [0, 1], [0, 1], [0, 1], + [2, 0], [0, 1], [1, 0]]) + labels = [0, 1, 2] + error_message = ("The shape of pred_decision is not " + "consistent with the number of classes. " + "With a multiclass target, pred_decision " + "shape must be (n_samples, n_classes), that is " + "(7, 3). Got: (7, 2)") + with pytest.raises(ValueError, match=re.escape(error_message)): + hinge_loss(y_true=y_true, pred_decision=pred_decision, labels=labels) + + def test_hinge_loss_multiclass_with_missing_labels(): pred_decision = np.array([ [+0.36, -0.17, -0.58, -0.99],
[ { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 3e36438dda095..06764d2be6003 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -165,6 +165,11 @@ Changelog\n class methods and will be removed in 1.2.\n :pr:`18543` by `Guillaume Lemaitre`_.\n \n+- |Enhancement| A fix to raise an error in :func:`metrics.hinge_loss` when\n+ ``pred_decision`` is 1d whereas it is a multiclass classification or when\n+ ``pred_decision`` parameter is not consistent with the ``labels`` parameter.\n+ :pr:`19643` by :user:`Pierre Attard <PierreAttard>`.\n+\n - |Feature| :func:`metrics.mean_pinball_loss` exposes the pinball loss for\n quantile regression. :pr:`19415` by :user:`Xavier Dupré <sdpython>`\n and :user:`Oliver Grisel <ogrisel>`.\n" } ]
1.00
42e90e9ba28fb37c2c9bd3e8aed1ac2387f1d5d5
[ "sklearn/metrics/tests/test_classification.py::test_classification_report_multiclass_balanced", "sklearn/metrics/tests/test_classification.py::test_fscore_warnings[1]", "sklearn/metrics/tests/test_classification.py::test_matthews_corrcoef_overflow[10000]", "sklearn/metrics/tests/test_classification.py::test_multiclass_jaccard_score", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f_binary_single_class", "sklearn/metrics/tests/test_classification.py::test_average_precision_score_tied_values", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_no_labels[1-weighted-1]", "sklearn/metrics/tests/test_classification.py::test_log_loss", "sklearn/metrics/tests/test_classification.py::test_classification_report_multiclass_with_digits", "sklearn/metrics/tests/test_classification.py::test_fscore_warnings[0]", "sklearn/metrics/tests/test_classification.py::test_log_loss_pandas_input", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_score_with_an_empty_prediction[0]", "sklearn/metrics/tests/test_classification.py::test_precision_recall_fscore_support_errors", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_no_labels[1-samples-1]", "sklearn/metrics/tests/test_classification.py::test_classification_report_output_dict_empty_input", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f_unused_pos_label", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_no_labels[0-samples-1]", "sklearn/metrics/tests/test_classification.py::test_multilabel_confusion_matrix_binary", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_no_labels_average_none[1]", "sklearn/metrics/tests/test_classification.py::test_multilabel_confusion_matrix_multilabel", "sklearn/metrics/tests/test_classification.py::test_zero_precision_recall", "sklearn/metrics/tests/test_classification.py::test_classification_report_labels_target_names_unequal_length", "sklearn/metrics/tests/test_classification.py::test_jaccard_score_validation", "sklearn/metrics/tests/test_classification.py::test_hinge_loss_multiclass_missing_labels_only_two_unq_in_y_true", "sklearn/metrics/tests/test_classification.py::test_balanced_accuracy_score[y_true0-y_pred0]", "sklearn/metrics/tests/test_classification.py::test_classification_report_zero_division_warning[warn]", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_no_labels_average_none[0]", "sklearn/metrics/tests/test_classification.py::test_precision_warnings[1]", "sklearn/metrics/tests/test_classification.py::test_recall_warnings[1]", "sklearn/metrics/tests/test_classification.py::test_prf_average_binary_data_non_binary", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_score_binary", "sklearn/metrics/tests/test_classification.py::test_precision_refcall_f1_score_multilabel_unordered_labels[None]", "sklearn/metrics/tests/test_classification.py::test_average_binary_jaccard_score", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_no_labels_check_warnings[macro]", "sklearn/metrics/tests/test_classification.py::test_hinge_loss_binary", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_score_with_an_empty_prediction[warn]", "sklearn/metrics/tests/test_classification.py::test_prf_no_warnings_if_zero_division_set[1]", "sklearn/metrics/tests/test_classification.py::test_precision_refcall_f1_score_multilabel_unordered_labels[micro]", "sklearn/metrics/tests/test_classification.py::test_confusion_matrix_normalize[all-f-0.1111111111]", "sklearn/metrics/tests/test_classification.py::test__check_targets", "sklearn/metrics/tests/test_classification.py::test_multilabel_hamming_loss", "sklearn/metrics/tests/test_classification.py::test_balanced_accuracy_score[y_true2-y_pred2]", "sklearn/metrics/tests/test_classification.py::test_prf_warnings", "sklearn/metrics/tests/test_classification.py::test_confusion_matrix_normalize[None-i-2]", "sklearn/metrics/tests/test_classification.py::test_classification_report_dictionary_output", "sklearn/metrics/tests/test_classification.py::test_multilabel_classification_report", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_no_labels_check_warnings[weighted]", "sklearn/metrics/tests/test_classification.py::test_jaccard_score_zero_division_warning", "sklearn/metrics/tests/test_classification.py::test__check_targets_multiclass_with_both_y_true_and_y_pred_binary", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_score_multilabel_1", "sklearn/metrics/tests/test_classification.py::test_confusion_matrix_error[empty list]", "sklearn/metrics/tests/test_classification.py::test_recall_warnings[0]", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f_ignored_labels", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_no_labels_check_warnings[micro]", "sklearn/metrics/tests/test_classification.py::test_hinge_loss_multiclass", "sklearn/metrics/tests/test_classification.py::test_confusion_matrix_normalize[true-f-0.333333333]", "sklearn/metrics/tests/test_classification.py::test_brier_score_loss", "sklearn/metrics/tests/test_classification.py::test_multilabel_jaccard_score", "sklearn/metrics/tests/test_classification.py::test_confusion_matrix_on_zero_length_input[None]", "sklearn/metrics/tests/test_classification.py::test_confusion_matrix_binary", "sklearn/metrics/tests/test_classification.py::test_precision_warnings[0]", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_score_with_an_empty_prediction[1]", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f_extra_labels", "sklearn/metrics/tests/test_classification.py::test_confusion_matrix_on_zero_length_input[binary]", "sklearn/metrics/tests/test_classification.py::test_matthews_corrcoef_against_jurman", "sklearn/metrics/tests/test_classification.py::test_classification_report_multiclass", "sklearn/metrics/tests/test_classification.py::test_confusion_matrix_normalize_wrong_option", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_no_labels[0-macro-1]", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_no_labels_average_none_warn", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_no_labels[1-macro-1]", "sklearn/metrics/tests/test_classification.py::test_precision_warnings[warn]", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_no_labels[0-weighted-1]", "sklearn/metrics/tests/test_classification.py::test_fscore_warnings[warn]", "sklearn/metrics/tests/test_classification.py::test_prf_no_warnings_if_zero_division_set[0]", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_score_binary_averaged", "sklearn/metrics/tests/test_classification.py::test_classification_report_no_labels_target_names_unequal_length", "sklearn/metrics/tests/test_classification.py::test_balanced_accuracy_score_unseen", "sklearn/metrics/tests/test_classification.py::test_confusion_matrix_error[unknown labels]", "sklearn/metrics/tests/test_classification.py::test_matthews_corrcoef", "sklearn/metrics/tests/test_classification.py::test_matthews_corrcoef_multiclass", "sklearn/metrics/tests/test_classification.py::test_recall_warnings[warn]", "sklearn/metrics/tests/test_classification.py::test_confusion_matrix_multiclass_subset_labels", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_score_multiclass", "sklearn/metrics/tests/test_classification.py::test_confusion_matrix_dtype", "sklearn/metrics/tests/test_classification.py::test_cohen_kappa", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_no_labels_check_warnings[samples]", "sklearn/metrics/tests/test_classification.py::test_precision_refcall_f1_score_multilabel_unordered_labels[weighted]", "sklearn/metrics/tests/test_classification.py::test_hinge_loss_multiclass_with_missing_labels", "sklearn/metrics/tests/test_classification.py::test_matthews_corrcoef_overflow[100]", "sklearn/metrics/tests/test_classification.py::test_average_precision_score_duplicate_values", "sklearn/metrics/tests/test_classification.py::test_precision_refcall_f1_score_multilabel_unordered_labels[samples]", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_score_multilabel_2", "sklearn/metrics/tests/test_classification.py::test_classification_report_zero_division_warning[1]", "sklearn/metrics/tests/test_classification.py::test_classification_report_multiclass_with_long_string_label", "sklearn/metrics/tests/test_classification.py::test_balanced_accuracy_score[y_true1-y_pred1]", "sklearn/metrics/tests/test_classification.py::test_multilabel_confusion_matrix_errors", "sklearn/metrics/tests/test_classification.py::test_matthews_corrcoef_nan", "sklearn/metrics/tests/test_classification.py::test_multilabel_confusion_matrix_multiclass", "sklearn/metrics/tests/test_classification.py::test_classification_report_multiclass_with_string_label", "sklearn/metrics/tests/test_classification.py::test_classification_report_multiclass_with_unicode_label", "sklearn/metrics/tests/test_classification.py::test_matthews_corrcoef_against_numpy_corrcoef", "sklearn/metrics/tests/test_classification.py::test_average_precision_score_score_non_binary_class", "sklearn/metrics/tests/test_classification.py::test_hinge_loss_multiclass_invariance_lists", "sklearn/metrics/tests/test_classification.py::test_confusion_matrix_normalize[pred-f-0.333333333]", "sklearn/metrics/tests/test_classification.py::test_classification_report_multiclass_with_label_detection", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_no_labels[1-micro-1]", "sklearn/metrics/tests/test_classification.py::test_multilabel_zero_one_loss_subset", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_no_labels[0-micro-1]", "sklearn/metrics/tests/test_classification.py::test_multilabel_accuracy_score_subset_accuracy", "sklearn/metrics/tests/test_classification.py::test_precision_refcall_f1_score_multilabel_unordered_labels[macro]", "sklearn/metrics/tests/test_classification.py::test_classification_report_zero_division_warning[0]", "sklearn/metrics/tests/test_classification.py::test_confusion_matrix_on_zero_length_input[multiclass]", "sklearn/metrics/tests/test_classification.py::test_hinge_loss_multiclass_missing_labels_with_labels_none" ]
[ "sklearn/metrics/tests/test_classification.py::test_hinge_loss_multiclass_no_consistent_pred_decision_shape" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 3e36438dda095..06764d2be6003 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -165,6 +165,11 @@ Changelog\n class methods and will be removed in 1.2.\n :pr:`<PRID>` by `<NAME>`_.\n \n+- |Enhancement| A fix to raise an error in :func:`metrics.hinge_loss` when\n+ ``pred_decision`` is 1d whereas it is a multiclass classification or when\n+ ``pred_decision`` parameter is not consistent with the ``labels`` parameter.\n+ :pr:`<PRID>` by :user:`<NAME>`.\n+\n - |Feature| :func:`metrics.mean_pinball_loss` exposes the pinball loss for\n quantile regression. :pr:`<PRID>` by :user:`<NAME>`\n and :user:`<NAME>`.\n" } ]
diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index 3e36438dda095..06764d2be6003 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -165,6 +165,11 @@ Changelog class methods and will be removed in 1.2. :pr:`<PRID>` by `<NAME>`_. +- |Enhancement| A fix to raise an error in :func:`metrics.hinge_loss` when + ``pred_decision`` is 1d whereas it is a multiclass classification or when + ``pred_decision`` parameter is not consistent with the ``labels`` parameter. + :pr:`<PRID>` by :user:`<NAME>`. + - |Feature| :func:`metrics.mean_pinball_loss` exposes the pinball loss for quantile regression. :pr:`<PRID>` by :user:`<NAME>` and :user:`<NAME>`.
scikit-learn/scikit-learn
scikit-learn__scikit-learn-17036
https://github.com/scikit-learn/scikit-learn/pull/17036
diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst index 3edd8adee8191..d56c7b5d8eafe 100644 --- a/doc/modules/classes.rst +++ b/doc/modules/classes.rst @@ -994,6 +994,7 @@ details. metrics.mean_poisson_deviance metrics.mean_gamma_deviance metrics.mean_tweedie_deviance + metrics.d2_tweedie_score metrics.mean_pinball_loss Multilabel ranking metrics diff --git a/doc/modules/model_evaluation.rst b/doc/modules/model_evaluation.rst index b1ef50dafbaa9..f5f447e118a8e 100644 --- a/doc/modules/model_evaluation.rst +++ b/doc/modules/model_evaluation.rst @@ -2354,6 +2354,34 @@ the difference in errors decreases. Finally, by setting, ``power=2``:: we would get identical errors. The deviance when ``power=2`` is thus only sensitive to relative errors. +.. _d2_tweedie_score: + +D² score, the coefficient of determination +------------------------------------------- + +The :func:`d2_tweedie_score` function computes the percentage of deviance +explained. It is a generalization of R², where the squared error is replaced by +the Tweedie deviance. D², also known as McFadden's likelihood ratio index, is +calculated as + +.. math:: + + D^2(y, \hat{y}) = 1 - \frac{\text{D}(y, \hat{y})}{\text{D}(y, \bar{y})} \,. + +The argument ``power`` defines the Tweedie power as for +:func:`mean_tweedie_deviance`. Note that for `power=0`, +:func:`d2_tweedie_score` equals :func:`r2_score` (for single targets). + +Like R², the best possible score is 1.0 and it can be negative (because the +model can be arbitrarily worse). A constant model that always predicts the +expected value of y, disregarding the input features, would get a D² score +of 0.0. + +A scorer object with a specific choice of ``power`` can be built by:: + + >>> from sklearn.metrics import d2_tweedie_score, make_scorer + >>> d2_tweedie_score_15 = make_scorer(d2_tweedie_score, pwoer=1.5) + .. _pinball_loss: Pinball loss @@ -2386,7 +2414,7 @@ Here is a small example of usage of the :func:`mean_pinball_loss` function:: >>> mean_pinball_loss(y_true, y_true, alpha=0.9) 0.0 -It is possible to build a scorer object with a specific choice of alpha:: +It is possible to build a scorer object with a specific choice of ``alpha``:: >>> from sklearn.metrics import make_scorer >>> mean_pinball_loss_95p = make_scorer(mean_pinball_loss, alpha=0.95) diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index 7d8175a3b5046..205eacdc91443 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -602,6 +602,12 @@ Changelog quantile regression. :pr:`19415` by :user:`Xavier Dupré <sdpython>` and :user:`Oliver Grisel <ogrisel>`. +- |Feature| :func:`metrics.d2_tweedie_score` calculates the D^2 regression + score for Tweedie deviances with power parameter ``power``. This is a + generalization of the `r2_score` and can be interpreted as percentage of + Tweedie deviance explained. + :pr:`17036` by :user:`Christian Lorentzen <lorentzenchr>`. + - |Feature| :func:`metrics.mean_squared_log_error` now supports `squared=False`. :pr:`20326` by :user:`Uttam kumar <helper-uttam>`. @@ -683,7 +689,7 @@ Changelog ............................. - |Fix| :class:`neural_network.MLPClassifier` and - :class:`neural_network.MLPRegressor` now correct supports continued training + :class:`neural_network.MLPRegressor` now correctly support continued training when loading from a pickled file. :pr:`19631` by `Thomas Fan`_. :mod:`sklearn.pipeline` diff --git a/sklearn/metrics/__init__.py b/sklearn/metrics/__init__.py index a0b06a02ad6d1..46958ea4ef7f8 100644 --- a/sklearn/metrics/__init__.py +++ b/sklearn/metrics/__init__.py @@ -74,6 +74,7 @@ from ._regression import mean_tweedie_deviance from ._regression import mean_poisson_deviance from ._regression import mean_gamma_deviance +from ._regression import d2_tweedie_score from ._scorer import check_scoring @@ -109,6 +110,7 @@ "confusion_matrix", "consensus_score", "coverage_error", + "d2_tweedie_score", "dcg_score", "davies_bouldin_score", "DetCurveDisplay", diff --git a/sklearn/metrics/_regression.py b/sklearn/metrics/_regression.py index 525837aefc2dc..ed9da69b1261c 100644 --- a/sklearn/metrics/_regression.py +++ b/sklearn/metrics/_regression.py @@ -24,15 +24,16 @@ # Uttam kumar <[email protected]> # License: BSD 3 clause -import numpy as np import warnings +import numpy as np + from .._loss.glm_distribution import TweedieDistribution +from ..exceptions import UndefinedMetricWarning from ..utils.validation import check_array, check_consistent_length, _num_samples from ..utils.validation import column_or_1d from ..utils.validation import _check_sample_weight from ..utils.stats import _weighted_percentile -from ..exceptions import UndefinedMetricWarning __ALL__ = [ @@ -986,3 +987,107 @@ def mean_gamma_deviance(y_true, y_pred, *, sample_weight=None): 1.0568... """ return mean_tweedie_deviance(y_true, y_pred, sample_weight=sample_weight, power=2) + + +def d2_tweedie_score(y_true, y_pred, *, sample_weight=None, power=0): + """D^2 regression score function, percentage of Tweedie deviance explained. + + Best possible score is 1.0 and it can be negative (because the model can be + arbitrarily worse). A model that always uses the empirical mean of `y_true` as + constant prediction, disregarding the input features, gets a D^2 score of 0.0. + + Read more in the :ref:`User Guide <d2_tweedie_score>`. + + .. versionadded:: 1.0 + + Parameters + ---------- + y_true : array-like of shape (n_samples,) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) + Estimated target values. + + sample_weight : array-like of shape (n_samples,), optional + Sample weights. + + power : float, default=0 + Tweedie power parameter. Either power <= 0 or power >= 1. + + The higher `p` the less weight is given to extreme + deviations between true and predicted targets. + + - power < 0: Extreme stable distribution. Requires: y_pred > 0. + - power = 0 : Normal distribution, output corresponds to r2_score. + y_true and y_pred can be any real numbers. + - power = 1 : Poisson distribution. Requires: y_true >= 0 and + y_pred > 0. + - 1 < p < 2 : Compound Poisson distribution. Requires: y_true >= 0 + and y_pred > 0. + - power = 2 : Gamma distribution. Requires: y_true > 0 and y_pred > 0. + - power = 3 : Inverse Gaussian distribution. Requires: y_true > 0 + and y_pred > 0. + - otherwise : Positive stable distribution. Requires: y_true > 0 + and y_pred > 0. + + Returns + ------- + z : float or ndarray of floats + The D^2 score. + + Notes + ----- + This is not a symmetric function. + + Like R^2, D^2 score may be negative (it need not actually be the square of + a quantity D). + + This metric is not well-defined for single samples and will return a NaN + value if n_samples is less than two. + + References + ---------- + .. [1] Eq. (3.11) of Hastie, Trevor J., Robert Tibshirani and Martin J. + Wainwright. "Statistical Learning with Sparsity: The Lasso and + Generalizations." (2015). https://trevorhastie.github.io + + Examples + -------- + >>> from sklearn.metrics import d2_tweedie_score + >>> y_true = [0.5, 1, 2.5, 7] + >>> y_pred = [1, 1, 5, 3.5] + >>> d2_tweedie_score(y_true, y_pred) + 0.285... + >>> d2_tweedie_score(y_true, y_pred, power=1) + 0.487... + >>> d2_tweedie_score(y_true, y_pred, power=2) + 0.630... + >>> d2_tweedie_score(y_true, y_true, power=2) + 1.0 + """ + y_type, y_true, y_pred, _ = _check_reg_targets( + y_true, y_pred, None, dtype=[np.float64, np.float32] + ) + if y_type == "continuous-multioutput": + raise ValueError("Multioutput not supported in d2_tweedie_score") + check_consistent_length(y_true, y_pred, sample_weight) + + if _num_samples(y_pred) < 2: + msg = "D^2 score is not well-defined with less than two samples." + warnings.warn(msg, UndefinedMetricWarning) + return float("nan") + + if sample_weight is not None: + sample_weight = column_or_1d(sample_weight) + sample_weight = sample_weight[:, np.newaxis] + + dist = TweedieDistribution(power=power) + + dev = dist.unit_deviance(y_true, y_pred, check_input=True) + numerator = np.average(dev, weights=sample_weight) + + y_avg = np.average(y_true, weights=sample_weight) + dev = dist.unit_deviance(y_true, y_avg, check_input=True) + denominator = np.average(dev, weights=sample_weight) + + return 1 - numerator / denominator
diff --git a/sklearn/metrics/tests/test_common.py b/sklearn/metrics/tests/test_common.py index 939371b01fc27..47e6bec38388f 100644 --- a/sklearn/metrics/tests/test_common.py +++ b/sklearn/metrics/tests/test_common.py @@ -29,6 +29,7 @@ from sklearn.metrics import cohen_kappa_score from sklearn.metrics import confusion_matrix from sklearn.metrics import coverage_error +from sklearn.metrics import d2_tweedie_score from sklearn.metrics import det_curve from sklearn.metrics import explained_variance_score from sklearn.metrics import f1_score @@ -110,6 +111,7 @@ "mean_poisson_deviance": mean_poisson_deviance, "mean_gamma_deviance": mean_gamma_deviance, "mean_compound_poisson_deviance": partial(mean_tweedie_deviance, power=1.4), + "d2_tweedie_score": partial(d2_tweedie_score, power=1.4), } CLASSIFICATION_METRICS = { @@ -510,6 +512,7 @@ def precision_recall_curve_padded_thresholds(*args, **kwargs): "mean_gamma_deviance", "mean_poisson_deviance", "mean_compound_poisson_deviance", + "d2_tweedie_score", "mean_absolute_percentage_error", } @@ -526,6 +529,7 @@ def precision_recall_curve_padded_thresholds(*args, **kwargs): "mean_poisson_deviance", "mean_gamma_deviance", "mean_compound_poisson_deviance", + "d2_tweedie_score", } diff --git a/sklearn/metrics/tests/test_regression.py b/sklearn/metrics/tests/test_regression.py index ed655a9fead3a..b66ce18ec8da4 100644 --- a/sklearn/metrics/tests/test_regression.py +++ b/sklearn/metrics/tests/test_regression.py @@ -1,6 +1,7 @@ import numpy as np from scipy import optimize from numpy.testing import assert_allclose +from scipy.special import factorial, xlogy from itertools import product import pytest @@ -20,6 +21,7 @@ from sklearn.metrics import mean_pinball_loss from sklearn.metrics import r2_score from sklearn.metrics import mean_tweedie_deviance +from sklearn.metrics import d2_tweedie_score from sklearn.metrics import make_scorer from sklearn.metrics._regression import _check_reg_targets @@ -53,6 +55,9 @@ def test_regression_metrics(n_samples=50): mean_tweedie_deviance(y_true, y_pred, power=0), mean_squared_error(y_true, y_pred), ) + assert_almost_equal( + d2_tweedie_score(y_true, y_pred, power=0), r2_score(y_true, y_pred) + ) # Tweedie deviance needs positive y_pred, except for p=0, # p>=2 needs positive y_true @@ -78,6 +83,17 @@ def test_regression_metrics(n_samples=50): mean_tweedie_deviance(y_true, y_pred, power=3), np.sum(1 / y_true) / (4 * n) ) + dev_mean = 2 * np.mean(xlogy(y_true, 2 * y_true / (n + 1))) + assert_almost_equal( + d2_tweedie_score(y_true, y_pred, power=1), + 1 - (n + 1) * (1 - np.log(2)) / dev_mean, + ) + + dev_mean = 2 * np.log((n + 1) / 2) - 2 / n * np.log(factorial(n)) + assert_almost_equal( + d2_tweedie_score(y_true, y_pred, power=2), 1 - (2 * np.log(2) - 1) / dev_mean + ) + def test_mean_squared_error_multioutput_raw_value_squared(): # non-regression test for @@ -131,23 +147,23 @@ def test_regression_metrics_at_limits(): assert_almost_equal(max_error([0.0], [0.0]), 0.0) assert_almost_equal(explained_variance_score([0.0], [0.0]), 1.0) assert_almost_equal(r2_score([0.0, 1], [0.0, 1]), 1.0) - err_msg = ( + msg = ( "Mean Squared Logarithmic Error cannot be used when targets " "contain negative values." ) - with pytest.raises(ValueError, match=err_msg): + with pytest.raises(ValueError, match=msg): mean_squared_log_error([-1.0], [-1.0]) - err_msg = ( + msg = ( "Mean Squared Logarithmic Error cannot be used when targets " "contain negative values." ) - with pytest.raises(ValueError, match=err_msg): + with pytest.raises(ValueError, match=msg): mean_squared_log_error([1.0, 2.0, 3.0], [1.0, -2.0, 3.0]) - err_msg = ( + msg = ( "Mean Squared Logarithmic Error cannot be used when targets " "contain negative values." ) - with pytest.raises(ValueError, match=err_msg): + with pytest.raises(ValueError, match=msg): mean_squared_log_error([1.0, -2.0, 3.0], [1.0, 2.0, 3.0]) # Tweedie deviance error @@ -155,35 +171,50 @@ def test_regression_metrics_at_limits(): assert_allclose( mean_tweedie_deviance([0], [1.0], power=power), 2 / (2 - power), rtol=1e-3 ) - with pytest.raises( - ValueError, match="can only be used on strictly positive y_pred." - ): + msg = "can only be used on strictly positive y_pred." + with pytest.raises(ValueError, match=msg): mean_tweedie_deviance([0.0], [0.0], power=power) - assert_almost_equal(mean_tweedie_deviance([0.0], [0.0], power=0), 0.00, 2) + with pytest.raises(ValueError, match=msg): + d2_tweedie_score([0.0] * 2, [0.0] * 2, power=power) + assert_almost_equal(mean_tweedie_deviance([0.0], [0.0], power=0), 0.0, 2) + + power = 1.0 msg = "only be used on non-negative y and strictly positive y_pred." with pytest.raises(ValueError, match=msg): - mean_tweedie_deviance([0.0], [0.0], power=1.0) + mean_tweedie_deviance([0.0], [0.0], power=power) + with pytest.raises(ValueError, match=msg): + d2_tweedie_score([0.0] * 2, [0.0] * 2, power=power) power = 1.5 assert_allclose(mean_tweedie_deviance([0.0], [1.0], power=power), 2 / (2 - power)) msg = "only be used on non-negative y and strictly positive y_pred." with pytest.raises(ValueError, match=msg): mean_tweedie_deviance([0.0], [0.0], power=power) + with pytest.raises(ValueError, match=msg): + d2_tweedie_score([0.0] * 2, [0.0] * 2, power=power) + power = 2.0 assert_allclose(mean_tweedie_deviance([1.0], [1.0], power=power), 0.00, atol=1e-8) msg = "can only be used on strictly positive y and y_pred." with pytest.raises(ValueError, match=msg): mean_tweedie_deviance([0.0], [0.0], power=power) + with pytest.raises(ValueError, match=msg): + d2_tweedie_score([0.0] * 2, [0.0] * 2, power=power) + power = 3.0 assert_allclose(mean_tweedie_deviance([1.0], [1.0], power=power), 0.00, atol=1e-8) - msg = "can only be used on strictly positive y and y_pred." with pytest.raises(ValueError, match=msg): mean_tweedie_deviance([0.0], [0.0], power=power) + with pytest.raises(ValueError, match=msg): + d2_tweedie_score([0.0] * 2, [0.0] * 2, power=power) + power = 0.5 + with pytest.raises(ValueError, match="is only defined for power<=0 and power>=1"): + mean_tweedie_deviance([0.0], [0.0], power=power) with pytest.raises(ValueError, match="is only defined for power<=0 and power>=1"): - mean_tweedie_deviance([0.0], [0.0], power=0.5) + d2_tweedie_score([0.0] * 2, [0.0] * 2, power=power) def test__check_reg_targets(): @@ -319,7 +350,7 @@ def test_regression_custom_weights(): assert_almost_equal(msle, msle2, decimal=2) [email protected]("metric", [r2_score]) [email protected]("metric", [r2_score, d2_tweedie_score]) def test_regression_single_sample(metric): y_true = [0] y_pred = [1]
[ { "path": "doc/modules/classes.rst", "old_path": "a/doc/modules/classes.rst", "new_path": "b/doc/modules/classes.rst", "metadata": "diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst\nindex 3edd8adee8191..d56c7b5d8eafe 100644\n--- a/doc/modules/classes.rst\n+++ b/doc/modules/classes.rst\n@@ -994,6 +994,7 @@ details.\n metrics.mean_poisson_deviance\n metrics.mean_gamma_deviance\n metrics.mean_tweedie_deviance\n+ metrics.d2_tweedie_score\n metrics.mean_pinball_loss\n \n Multilabel ranking metrics\n" }, { "path": "doc/modules/model_evaluation.rst", "old_path": "a/doc/modules/model_evaluation.rst", "new_path": "b/doc/modules/model_evaluation.rst", "metadata": "diff --git a/doc/modules/model_evaluation.rst b/doc/modules/model_evaluation.rst\nindex b1ef50dafbaa9..f5f447e118a8e 100644\n--- a/doc/modules/model_evaluation.rst\n+++ b/doc/modules/model_evaluation.rst\n@@ -2354,6 +2354,34 @@ the difference in errors decreases. Finally, by setting, ``power=2``::\n we would get identical errors. The deviance when ``power=2`` is thus only\n sensitive to relative errors.\n \n+.. _d2_tweedie_score:\n+\n+D² score, the coefficient of determination\n+-------------------------------------------\n+\n+The :func:`d2_tweedie_score` function computes the percentage of deviance\n+explained. It is a generalization of R², where the squared error is replaced by\n+the Tweedie deviance. D², also known as McFadden's likelihood ratio index, is\n+calculated as\n+\n+.. math::\n+\n+ D^2(y, \\hat{y}) = 1 - \\frac{\\text{D}(y, \\hat{y})}{\\text{D}(y, \\bar{y})} \\,.\n+\n+The argument ``power`` defines the Tweedie power as for\n+:func:`mean_tweedie_deviance`. Note that for `power=0`,\n+:func:`d2_tweedie_score` equals :func:`r2_score` (for single targets).\n+\n+Like R², the best possible score is 1.0 and it can be negative (because the\n+model can be arbitrarily worse). A constant model that always predicts the\n+expected value of y, disregarding the input features, would get a D² score\n+of 0.0.\n+\n+A scorer object with a specific choice of ``power`` can be built by::\n+\n+ >>> from sklearn.metrics import d2_tweedie_score, make_scorer\n+ >>> d2_tweedie_score_15 = make_scorer(d2_tweedie_score, pwoer=1.5)\n+\n .. _pinball_loss:\n \n Pinball loss\n@@ -2386,7 +2414,7 @@ Here is a small example of usage of the :func:`mean_pinball_loss` function::\n >>> mean_pinball_loss(y_true, y_true, alpha=0.9)\n 0.0\n \n-It is possible to build a scorer object with a specific choice of alpha::\n+It is possible to build a scorer object with a specific choice of ``alpha``::\n \n >>> from sklearn.metrics import make_scorer\n >>> mean_pinball_loss_95p = make_scorer(mean_pinball_loss, alpha=0.95)\n" }, { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 7d8175a3b5046..205eacdc91443 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -602,6 +602,12 @@ Changelog\n quantile regression. :pr:`19415` by :user:`Xavier Dupré <sdpython>`\n and :user:`Oliver Grisel <ogrisel>`.\n \n+- |Feature| :func:`metrics.d2_tweedie_score` calculates the D^2 regression\n+ score for Tweedie deviances with power parameter ``power``. This is a\n+ generalization of the `r2_score` and can be interpreted as percentage of\n+ Tweedie deviance explained.\n+ :pr:`17036` by :user:`Christian Lorentzen <lorentzenchr>`.\n+\n - |Feature| :func:`metrics.mean_squared_log_error` now supports\n `squared=False`.\n :pr:`20326` by :user:`Uttam kumar <helper-uttam>`.\n@@ -683,7 +689,7 @@ Changelog\n .............................\n \n - |Fix| :class:`neural_network.MLPClassifier` and\n- :class:`neural_network.MLPRegressor` now correct supports continued training\n+ :class:`neural_network.MLPRegressor` now correctly support continued training\n when loading from a pickled file. :pr:`19631` by `Thomas Fan`_.\n \n :mod:`sklearn.pipeline`\n" } ]
1.00
03245ee3afe5ee9e2ff626e2290f02748d95e497
[]
[ "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric18]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[matthews_corrcoef_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_single_sample[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric21]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric37]", "sklearn/metrics/tests/test_common.py::test_single_sample[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[macro_f1_score]", "sklearn/metrics/tests/test_regression.py::test__check_reg_targets_exception", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_normal_deviance]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric41]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[micro_recall_score]", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.75-uniform]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric29]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric29]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[f2_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric10]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric15]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric35]", "sklearn/metrics/tests/test_common.py::test_single_sample[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_precision_score]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[str-metric3-False]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric3]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[roc_auc_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[label_ranking_loss]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multiclass[f1_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric38]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric33]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric40]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[object-f1_score-False]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[precision_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric10]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric8]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-multilabel_confusion_matrix]", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.05-uniform]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric28]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_ovo_roc_auc]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-matthews_corrcoef]", "sklearn/metrics/tests/test_common.py::test_single_sample[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_zeroes[f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric22]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric33]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric10]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric36]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric34]", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric38]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric9]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric17]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric38]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[log_loss]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric30]", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.75-exponential]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric23]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_zeroes[f0.5_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[hinge_loss]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[brier_score_loss]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric34]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric27]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_zeroes[recall_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric19]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric18]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_ones[f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-label_ranking_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric10]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-label_ranking_loss]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[r2_score]", "sklearn/metrics/tests/test_regression.py::test_mean_squared_error_multioutput_raw_value_squared", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric16]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-hinge_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-max_error]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_normal_deviance]", "sklearn/metrics/tests/test_common.py::test_averaging_multiclass[f0.5_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-hinge_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[label_ranking_loss]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[ndcg_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric15]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric39]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric13]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric10]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric18]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[partial_roc_auc]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[samples_roc_auc]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric18]", "sklearn/metrics/tests/test_common.py::test_single_sample[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[max_error]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[partial_roc_auc]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric18]", "sklearn/metrics/tests/test_common.py::test_single_sample[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-max_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-precision_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[samples_precision_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric3]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-log_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_representation_invariance", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-average_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-matthews_corrcoef]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[roc_auc_score]", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.5-exponential]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric7]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-matthews_corrcoef]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[object-jaccard_score-False]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric16]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric23]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[f0.5_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-brier_score_loss]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric41]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric25]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric31]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric40]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[hinge_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric27]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric11]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-recall_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric35]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric36]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_recall_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[log_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[r2_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric40]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[samples_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric29]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric27]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[hinge_loss]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric17]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_compound_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-ndcg_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric18]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric39]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric3]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric32]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[samples_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric12]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[r2_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric30]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-hamming_loss]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric18]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[d2_tweedie_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric27]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric39]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric21]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric26]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric14]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric8]", "sklearn/metrics/tests/test_common.py::test_normalize_option_binary_classification[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[ovo_roc_auc]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-<lambda>]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric39]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric37]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric32]", "sklearn/metrics/tests/test_common.py::test_normalize_option_multilabel_classification[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[samples_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[log_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-coverage_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric22]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[mean_compound_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric33]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-average_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_compound_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric30]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[roc_auc_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[d2_tweedie_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[hinge_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-max_error]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[weighted_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric11]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric40]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric20]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[samples_precision_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric19]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[dcg_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[f0.5_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric17]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric25]", "sklearn/metrics/tests/test_regression.py::test_regression_metrics_at_limits", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric40]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric31]", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric31]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric10]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric9]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_compound_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric13]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[matthews_corrcoef]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric24]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[coverage_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric7]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[weighted_roc_auc]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[samples_recall_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[average_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-jaccard_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric20]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_roc_auc]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric34]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric24]", "sklearn/metrics/tests/test_common.py::test_averaging_multiclass[recall_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[label_ranking_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric2]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric28]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[weighted_ovo_roc_auc]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_normalize_option_multiclass_classification[top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric15]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric35]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric20]", "sklearn/metrics/tests/test_common.py::test_single_sample[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric23]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-average_precision_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-coverage_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-hinge_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric16]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric35]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric19]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-dcg_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_normal_deviance]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric30]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[str-f1_score-False]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric35]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric31]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[dcg_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample[matthews_corrcoef_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-label_ranking_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric18]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric31]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric12]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-label_ranking_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric8]", "sklearn/metrics/tests/test_common.py::test_single_sample[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric16]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric30]", "sklearn/metrics/tests/test_common.py::test_single_sample[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric22]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric30]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric33]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric2]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_roc_auc]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[coverage_error]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric3]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[str-jaccard_score-False]", "sklearn/metrics/tests/test_regression.py::test_regression_single_sample[d2_tweedie_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-precision_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric14]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-hinge_loss]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[macro_f1_score]", "sklearn/metrics/tests/test_regression.py::test__check_reg_targets", "sklearn/metrics/tests/test_common.py::test_single_sample[r2_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric18]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric35]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[samples_recall_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric30]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric23]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[samples_precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[micro_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric35]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric22]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[average_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-<lambda>]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[log_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric21]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-ndcg_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric32]", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.5-normal]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_f2_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[average_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-ndcg_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric19]", "sklearn/metrics/tests/test_common.py::test_single_sample[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[samples_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[object-average_precision_score-True]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-<lambda>]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric9]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric2]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_symmetry_consistency", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric24]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric25]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric12]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric16]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multiclass[f2_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-dcg_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric28]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric35]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric36]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-dcg_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-label_ranking_loss]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_ones[precision_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[label_ranking_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[micro_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[samples_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric10]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric31]", "sklearn/metrics/tests/test_common.py::test_normalize_option_multiclass_classification[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[samples_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[str-precision_score-False]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[r2_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric7]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric34]", "sklearn/metrics/tests/test_common.py::test_single_sample[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric19]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric10]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[str-brier_score_loss-True]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric36]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric9]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-precision_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[hinge_loss]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric3]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[samples_roc_auc]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[log_loss]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_compound_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_f1_score]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[object-precision_recall_curve-True]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric30]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric39]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric28]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric23]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[roc_curve]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric41]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric3]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-roc_auc_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-<lambda>]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric39]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-label_ranking_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric26]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[samples_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[precision_recall_curve]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[weighted_ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric31]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric20]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[d2_tweedie_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric38]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric13]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric40]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric22]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric18]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[weighted_roc_auc]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric14]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[f0.5_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_ovo_roc_auc]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[log_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-recall_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[micro_roc_auc]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_ones[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[log_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric28]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[det_curve]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[samples_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric11]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric3]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[samples_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric2]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_single_sample[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_roc_auc]", "sklearn/metrics/tests/test_common.py::test_averaging_multiclass[precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric31]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric34]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric16]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-accuracy_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[r2_score]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[f1_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_ones[f2_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric25]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-dcg_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric15]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric32]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric16]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-hamming_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric7]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric31]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_single_sample[normalized_confusion_matrix]", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.05-normal]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[micro_jaccard_score]", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.5-uniform]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric7]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[weighted_ovo_roc_auc]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric22]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[label_ranking_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_normalize_option_multilabel_classification[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[precision_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[f0.5_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric37]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[object-brier_score_loss-True]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[object-metric3-False]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric28]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric35]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric37]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-label_ranking_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[log_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric37]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric21]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[matthews_corrcoef_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric21]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_absolute_error]", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.05-exponential]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric17]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[recall_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric3]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[partial_roc_auc]", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.75-normal]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-hinge_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-dcg_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[samples_f2_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-max_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-roc_auc_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric26]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[micro_roc_auc]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[samples_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_zeroes[f2_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[label_ranking_loss]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[samples_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-brier_score_loss]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric16]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[f2_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-coverage_error]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[samples_recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[str-average_precision_score-True]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric37]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric20]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric32]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-log_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-precision_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric31]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-label_ranking_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric29]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_pinball_loss]", "sklearn/metrics/tests/test_regression.py::test_regression_custom_weights", "sklearn/metrics/tests/test_common.py::test_single_sample[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric18]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-hamming_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric24]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric34]", "sklearn/metrics/tests/test_regression.py::test_regression_metrics", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[weighted_ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric27]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric33]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[matthews_corrcoef_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[samples_f2_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-recall_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[matthews_corrcoef_score]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[str-recall_score-False]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[partial_roc_auc]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[samples_f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric14]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric24]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[d2_tweedie_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[samples_f1_score]", "sklearn/metrics/tests/test_common.py::test_averaging_binary_multilabel_all_zeroes", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric31]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric36]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-hamming_loss]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[hinge_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric34]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric28]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[ndcg_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric3]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-brier_score_loss]", "sklearn/metrics/tests/test_regression.py::test_regression_multioutput_array", "sklearn/metrics/tests/test_common.py::test_normalize_option_binary_classification[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-coverage_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric32]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-hamming_loss]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[brier_score_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-log_loss]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[roc_auc_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[coverage_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric2]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric23]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_regression.py::test_tweedie_deviance_continuity", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[r2_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-matthews_corrcoef]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-coverage_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-label_ranking_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-precision_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[precision_recall_curve]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-ndcg_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric16]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric34]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric41]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-roc_auc_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric30]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[ovo_roc_auc]", "sklearn/metrics/tests/test_common.py::test_averaging_multiclass[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric34]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-ndcg_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[recall_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric7]", "sklearn/metrics/tests/test_common.py::test_single_sample[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[det_curve]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric30]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric34]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric7]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric21]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric3]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_normalize_option_binary_classification[top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[average_precision_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[hinge_loss]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[object-recall_score-False]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric25]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric35]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric3]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[samples_f2_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[roc_auc_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric7]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-average_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric40]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[samples_recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric25]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric18]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric26]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric27]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_zeroes[precision_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[samples_roc_auc]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[object-precision_score-False]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-matthews_corrcoef]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric24]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[hamming_loss]", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.75-lognormal]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric8]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_normal_deviance]", "sklearn/metrics/tests/test_common.py::test_single_sample[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric12]", "sklearn/metrics/tests/test_common.py::test_single_sample[max_error]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[average_precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[ovo_roc_auc]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[max_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric7]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric29]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[samples_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric35]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-average_precision_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[ovo_roc_auc]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric23]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric22]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric11]", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.5-lognormal]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric10]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-<lambda>]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[partial_roc_auc]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric36]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric10]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-brier_score_loss]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[<lambda>]", "sklearn/metrics/tests/test_common.py::test_single_sample[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[str-roc_curve-True]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric2]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric7]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[samples_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_ones[f0.5_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-f1_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-metric9]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-hamming_loss]", "sklearn/metrics/tests/test_regression.py::test_mean_absolute_percentage_error", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[matthews_corrcoef_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric41]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric29]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric25]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[matthews_corrcoef_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric30]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[ndcg_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric33]", "sklearn/metrics/tests/test_common.py::test_normalize_option_multiclass_classification[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric19]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric7]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric16]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric24]", "sklearn/metrics/tests/test_common.py::test_single_sample[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[r2_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric41]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric32]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[mean_normal_deviance]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-roc_auc_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[f1_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric26]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric2]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric38]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[roc_curve]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric16]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-metric15]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-metric38]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[weighted_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric29]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-jaccard_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[unnormalized_multilabel_confusion_matrix_sample]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric16]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-label_ranking_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-matthews_corrcoef]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric30]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric37]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric39]", "sklearn/metrics/tests/test_regression.py::test_dummy_quantile_parameter_tuning", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_pinball_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true5-y_score5-f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric34]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric31]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[samples_f1_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[dcg_score]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[r2_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-log_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[samples_f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric26]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric41]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric19]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric20]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-max_error]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[recall_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[matthews_corrcoef_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric8]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric3]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric20]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[samples_f0.5_score]", "sklearn/metrics/tests/test_regression.py::test_mean_pinball_loss_on_constant_predictions[0.05-lognormal]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-roc_auc_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true4-y_score4-metric15]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[r2_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric11]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric27]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric14]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_ones[recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric12]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[max_error]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric26]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[recall_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[d2_tweedie_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric36]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance_multilabel_and_multioutput", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_no_averaging_labels", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_roc_auc]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_zeroes[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[log_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_roc_auc]", "sklearn/metrics/tests/test_regression.py::test_regression_single_sample[r2_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-accuracy_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[str-precision_recall_curve-True]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric21]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric34]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true0-y_score0-metric38]", "sklearn/metrics/tests/test_common.py::test_single_sample[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-<lambda>]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[object-roc_curve-True]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true3-y_score3-metric10]", "sklearn/metrics/tests/test_regression.py::test_multioutput_regression", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-brier_score_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric17]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true1-y_score1-metric13]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true1-y_score1-metric15]", "sklearn/metrics/tests/test_common.py::test_classification_binary_continuous_input[metric7]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true0-y_score0-metric10]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric33]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true4-y_score4-log_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true2-y_score2-metric35]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[y_true3-y_score3-cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[y_true2-y_score2-metric13]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/modules/classes.rst", "old_path": "a/doc/modules/classes.rst", "new_path": "b/doc/modules/classes.rst", "metadata": "diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst\nindex 3edd8adee8191..d56c7b5d8eafe 100644\n--- a/doc/modules/classes.rst\n+++ b/doc/modules/classes.rst\n@@ -994,6 +994,7 @@ details.\n metrics.mean_poisson_deviance\n metrics.mean_gamma_deviance\n metrics.mean_tweedie_deviance\n+ metrics.d2_tweedie_score\n metrics.mean_pinball_loss\n \n Multilabel ranking metrics\n" }, { "path": "doc/modules/model_evaluation.rst", "old_path": "a/doc/modules/model_evaluation.rst", "new_path": "b/doc/modules/model_evaluation.rst", "metadata": "diff --git a/doc/modules/model_evaluation.rst b/doc/modules/model_evaluation.rst\nindex b1ef50dafbaa9..f5f447e118a8e 100644\n--- a/doc/modules/model_evaluation.rst\n+++ b/doc/modules/model_evaluation.rst\n@@ -2354,6 +2354,34 @@ the difference in errors decreases. Finally, by setting, ``power=2``::\n we would get identical errors. The deviance when ``power=2`` is thus only\n sensitive to relative errors.\n \n+.. _d2_tweedie_score:\n+\n+D² score, the coefficient of determination\n+-------------------------------------------\n+\n+The :func:`d2_tweedie_score` function computes the percentage of deviance\n+explained. It is a generalization of R², where the squared error is replaced by\n+the Tweedie deviance. D², also known as McFadden's likelihood ratio index, is\n+calculated as\n+\n+.. math::\n+\n+ D^2(y, \\hat{y}) = 1 - \\frac{\\text{D}(y, \\hat{y})}{\\text{D}(y, \\bar{y})} \\,.\n+\n+The argument ``power`` defines the Tweedie power as for\n+:func:`mean_tweedie_deviance`. Note that for `power=0`,\n+:func:`d2_tweedie_score` equals :func:`r2_score` (for single targets).\n+\n+Like R², the best possible score is 1.0 and it can be negative (because the\n+model can be arbitrarily worse). A constant model that always predicts the\n+expected value of y, disregarding the input features, would get a D² score\n+of 0.0.\n+\n+A scorer object with a specific choice of ``power`` can be built by::\n+\n+ >>> from sklearn.metrics import d2_tweedie_score, make_scorer\n+ >>> d2_tweedie_score_15 = make_scorer(d2_tweedie_score, pwoer=1.5)\n+\n .. _pinball_loss:\n \n Pinball loss\n@@ -2386,7 +2414,7 @@ Here is a small example of usage of the :func:`mean_pinball_loss` function::\n >>> mean_pinball_loss(y_true, y_true, alpha=0.9)\n 0.0\n \n-It is possible to build a scorer object with a specific choice of alpha::\n+It is possible to build a scorer object with a specific choice of ``alpha``::\n \n >>> from sklearn.metrics import make_scorer\n >>> mean_pinball_loss_95p = make_scorer(mean_pinball_loss, alpha=0.95)\n" }, { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 7d8175a3b5046..205eacdc91443 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -602,6 +602,12 @@ Changelog\n quantile regression. :pr:`<PRID>` by :user:`<NAME>`\n and :user:`<NAME>`.\n \n+- |Feature| :func:`metrics.d2_tweedie_score` calculates the D^2 regression\n+ score for Tweedie deviances with power parameter ``power``. This is a\n+ generalization of the `r2_score` and can be interpreted as percentage of\n+ Tweedie deviance explained.\n+ :pr:`<PRID>` by :user:`<NAME>`.\n+\n - |Feature| :func:`metrics.mean_squared_log_error` now supports\n `squared=False`.\n :pr:`<PRID>` by :user:`<NAME>`.\n@@ -683,7 +689,7 @@ Changelog\n .............................\n \n - |Fix| :class:`neural_network.MLPClassifier` and\n- :class:`neural_network.MLPRegressor` now correct supports continued training\n+ :class:`neural_network.MLPRegressor` now correctly support continued training\n when loading from a pickled file. :pr:`<PRID>` by `<NAME>`_.\n \n :mod:`sklearn.pipeline`\n" } ]
diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst index 3edd8adee8191..d56c7b5d8eafe 100644 --- a/doc/modules/classes.rst +++ b/doc/modules/classes.rst @@ -994,6 +994,7 @@ details. metrics.mean_poisson_deviance metrics.mean_gamma_deviance metrics.mean_tweedie_deviance + metrics.d2_tweedie_score metrics.mean_pinball_loss Multilabel ranking metrics diff --git a/doc/modules/model_evaluation.rst b/doc/modules/model_evaluation.rst index b1ef50dafbaa9..f5f447e118a8e 100644 --- a/doc/modules/model_evaluation.rst +++ b/doc/modules/model_evaluation.rst @@ -2354,6 +2354,34 @@ the difference in errors decreases. Finally, by setting, ``power=2``:: we would get identical errors. The deviance when ``power=2`` is thus only sensitive to relative errors. +.. _d2_tweedie_score: + +D² score, the coefficient of determination +------------------------------------------- + +The :func:`d2_tweedie_score` function computes the percentage of deviance +explained. It is a generalization of R², where the squared error is replaced by +the Tweedie deviance. D², also known as McFadden's likelihood ratio index, is +calculated as + +.. math:: + + D^2(y, \hat{y}) = 1 - \frac{\text{D}(y, \hat{y})}{\text{D}(y, \bar{y})} \,. + +The argument ``power`` defines the Tweedie power as for +:func:`mean_tweedie_deviance`. Note that for `power=0`, +:func:`d2_tweedie_score` equals :func:`r2_score` (for single targets). + +Like R², the best possible score is 1.0 and it can be negative (because the +model can be arbitrarily worse). A constant model that always predicts the +expected value of y, disregarding the input features, would get a D² score +of 0.0. + +A scorer object with a specific choice of ``power`` can be built by:: + + >>> from sklearn.metrics import d2_tweedie_score, make_scorer + >>> d2_tweedie_score_15 = make_scorer(d2_tweedie_score, pwoer=1.5) + .. _pinball_loss: Pinball loss @@ -2386,7 +2414,7 @@ Here is a small example of usage of the :func:`mean_pinball_loss` function:: >>> mean_pinball_loss(y_true, y_true, alpha=0.9) 0.0 -It is possible to build a scorer object with a specific choice of alpha:: +It is possible to build a scorer object with a specific choice of ``alpha``:: >>> from sklearn.metrics import make_scorer >>> mean_pinball_loss_95p = make_scorer(mean_pinball_loss, alpha=0.95) diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index 7d8175a3b5046..205eacdc91443 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -602,6 +602,12 @@ Changelog quantile regression. :pr:`<PRID>` by :user:`<NAME>` and :user:`<NAME>`. +- |Feature| :func:`metrics.d2_tweedie_score` calculates the D^2 regression + score for Tweedie deviances with power parameter ``power``. This is a + generalization of the `r2_score` and can be interpreted as percentage of + Tweedie deviance explained. + :pr:`<PRID>` by :user:`<NAME>`. + - |Feature| :func:`metrics.mean_squared_log_error` now supports `squared=False`. :pr:`<PRID>` by :user:`<NAME>`. @@ -683,7 +689,7 @@ Changelog ............................. - |Fix| :class:`neural_network.MLPClassifier` and - :class:`neural_network.MLPRegressor` now correct supports continued training + :class:`neural_network.MLPRegressor` now correctly support continued training when loading from a pickled file. :pr:`<PRID>` by `<NAME>`_. :mod:`sklearn.pipeline`
scikit-learn/scikit-learn
scikit-learn__scikit-learn-18649
https://github.com/scikit-learn/scikit-learn/pull/18649
diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst index c658bc6b12452..d019af3cfb1ff 100644 --- a/doc/modules/classes.rst +++ b/doc/modules/classes.rst @@ -1176,6 +1176,7 @@ Splitter Classes model_selection.ShuffleSplit model_selection.StratifiedKFold model_selection.StratifiedShuffleSplit + model_selection.StratifiedGroupKFold model_selection.TimeSeriesSplit Splitter Functions diff --git a/doc/modules/cross_validation.rst b/doc/modules/cross_validation.rst index ae3d38f168f3f..0b090fd7385b6 100644 --- a/doc/modules/cross_validation.rst +++ b/doc/modules/cross_validation.rst @@ -353,7 +353,7 @@ Example of 2-fold cross-validation on a dataset with 4 samples:: Here is a visualization of the cross-validation behavior. Note that :class:`KFold` is not affected by classes or groups. -.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_004.png +.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_006.png :target: ../auto_examples/model_selection/plot_cv_indices.html :align: center :scale: 75% @@ -509,7 +509,7 @@ Here is a usage example:: Here is a visualization of the cross-validation behavior. Note that :class:`ShuffleSplit` is not affected by classes or groups. -.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_006.png +.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_008.png :target: ../auto_examples/model_selection/plot_cv_indices.html :align: center :scale: 75% @@ -566,7 +566,7 @@ We can see that :class:`StratifiedKFold` preserves the class ratios Here is a visualization of the cross-validation behavior. -.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_007.png +.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_009.png :target: ../auto_examples/model_selection/plot_cv_indices.html :align: center :scale: 75% @@ -585,7 +585,7 @@ percentage for each target class as in the complete set. Here is a visualization of the cross-validation behavior. -.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_009.png +.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_012.png :target: ../auto_examples/model_selection/plot_cv_indices.html :align: center :scale: 75% @@ -645,6 +645,58 @@ size due to the imbalance in the data. Here is a visualization of the cross-validation behavior. +.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_007.png + :target: ../auto_examples/model_selection/plot_cv_indices.html + :align: center + :scale: 75% + +.. _stratified_group_k_fold: + +StratifiedGroupKFold +^^^^^^^^^^^^^^^^^^^^ + +:class:`StratifiedGroupKFold` is a cross-validation scheme that combines both +:class:`StratifiedKFold` and :class:`GroupKFold`. The idea is to try to +preserve the distribution of classes in each split while keeping each group +within a single split. That might be useful when you have an unbalanced +dataset so that using just :class:`GroupKFold` might produce skewed splits. + +Example:: + + >>> from sklearn.model_selection import StratifiedGroupKFold + >>> X = list(range(18)) + >>> y = [1] * 6 + [0] * 12 + >>> groups = [1, 2, 3, 3, 4, 4, 1, 1, 2, 2, 3, 4, 5, 5, 5, 6, 6, 6] + >>> sgkf = StratifiedGroupKFold(n_splits=3) + >>> for train, test in sgkf.split(X, y, groups=groups): + ... print("%s %s" % (train, test)) + [ 0 2 3 4 5 6 7 10 11 15 16 17] [ 1 8 9 12 13 14] + [ 0 1 4 5 6 7 8 9 11 12 13 14] [ 2 3 10 15 16 17] + [ 1 2 3 8 9 10 12 13 14 15 16 17] [ 0 4 5 6 7 11] + +Implementation notes: + +- With the current implementation full shuffle is not possible in most + scenarios. When shuffle=True, the following happens: + + 1. All groups a shuffled. + 2. Groups are sorted by standard deviation of classes using stable sort. + 3. Sorted groups are iterated over and assigned to folds. + + That means that only groups with the same standard deviation of class + distribution will be shuffled, which might be useful when each group has only + a single class. +- The algorithm greedily assigns each group to one of n_splits test sets, + choosing the test set that minimises the variance in class distribution + across test sets. Group assignment proceeds from groups with highest to + lowest variance in class frequency, i.e. large groups peaked on one or few + classes are assigned first. +- This split is suboptimal in a sense that it might produce imbalanced splits + even if perfect stratification is possible. If you have relatively close + distribution of classes in each group, using :class:`GroupKFold` is better. + +Here is a visualization of cross-validation behavior for uneven groups: + .. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_005.png :target: ../auto_examples/model_selection/plot_cv_indices.html :align: center @@ -733,7 +785,7 @@ Here is a usage example:: Here is a visualization of the cross-validation behavior. -.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_008.png +.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_011.png :target: ../auto_examples/model_selection/plot_cv_indices.html :align: center :scale: 75% @@ -835,7 +887,7 @@ Example of 3-split time series cross-validation on a dataset with 6 samples:: Here is a visualization of the cross-validation behavior. -.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_010.png +.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_013.png :target: ../auto_examples/model_selection/plot_cv_indices.html :align: center :scale: 75% diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index 34f39ca48f20a..985fe57164824 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -183,6 +183,16 @@ Changelog are integral. :pr:`9843` by :user:`Jon Crall <Erotemic>`. +:mod:`sklearn.model_selection` +.............................. + +- |Feature| added :class:`model_selection.StratifiedGroupKFold`, that combines + :class:`model_selection.StratifiedKFold` and `model_selection.GroupKFold`, + providing an ability to split data preserving the distribution of classes in + each split while keeping each group within a single split. + :pr:`18649` by `Leandro Hermida <hermidalc>` and + `Rodion Martynov <marrodion>`. + :mod:`sklearn.naive_bayes` .......................... diff --git a/examples/model_selection/plot_cv_indices.py b/examples/model_selection/plot_cv_indices.py index 91f71b0451cb2..f07fa1595e860 100644 --- a/examples/model_selection/plot_cv_indices.py +++ b/examples/model_selection/plot_cv_indices.py @@ -13,7 +13,8 @@ from sklearn.model_selection import (TimeSeriesSplit, KFold, ShuffleSplit, StratifiedKFold, GroupShuffleSplit, - GroupKFold, StratifiedShuffleSplit) + GroupKFold, StratifiedShuffleSplit, + StratifiedGroupKFold) import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Patch @@ -113,16 +114,32 @@ def plot_cv_indices(cv, X, y, group, ax, n_splits, lw=10): # %% # As you can see, by default the KFold cross-validation iterator does not # take either datapoint class or group into consideration. We can change this -# by using the ``StratifiedKFold`` like so. +# by using either: +# +# - ``StratifiedKFold`` to preserve the percentage of samples for each class. +# - ``GroupKFold`` to ensure that the same group will not appear in two +# different folds. +# - ``StratifiedGroupKFold`` to keep the constraint of ``GroupKFold`` while +# attempting to return stratified folds. -fig, ax = plt.subplots() -cv = StratifiedKFold(n_splits) -plot_cv_indices(cv, X, y, groups, ax, n_splits) +# To better demonstrate the difference, we will assign samples to groups +# unevenly: + +uneven_groups = np.sort(np.random.randint(0, 10, n_points)) + +cvs = [StratifiedKFold, GroupKFold, StratifiedGroupKFold] + +for cv in cvs: + fig, ax = plt.subplots(figsize=(6, 3)) + plot_cv_indices(cv(n_splits), X, y, uneven_groups, ax, n_splits) + ax.legend([Patch(color=cmap_cv(.8)), Patch(color=cmap_cv(.02))], + ['Testing set', 'Training set'], loc=(1.02, .8)) + # Make the legend fit + plt.tight_layout() + fig.subplots_adjust(right=.7) # %% -# In this case, the cross-validation retained the same ratio of classes across -# each CV split. Next we'll visualize this behavior for a number of CV -# iterators. +# Next we'll visualize this behavior for a number of CV iterators. # # Visualize cross-validation indices for many CV objects # ------------------------------------------------------ @@ -133,7 +150,7 @@ def plot_cv_indices(cv, X, y, group, ax, n_splits, lw=10): # # Note how some use the group/class information while others do not. -cvs = [KFold, GroupKFold, ShuffleSplit, StratifiedKFold, +cvs = [KFold, GroupKFold, ShuffleSplit, StratifiedKFold, StratifiedGroupKFold, GroupShuffleSplit, StratifiedShuffleSplit, TimeSeriesSplit] diff --git a/sklearn/model_selection/__init__.py b/sklearn/model_selection/__init__.py index 897183414b5a6..f79db2a5acc17 100644 --- a/sklearn/model_selection/__init__.py +++ b/sklearn/model_selection/__init__.py @@ -14,6 +14,7 @@ from ._split import ShuffleSplit from ._split import GroupShuffleSplit from ._split import StratifiedShuffleSplit +from ._split import StratifiedGroupKFold from ._split import PredefinedSplit from ._split import train_test_split from ._split import check_cv @@ -57,6 +58,7 @@ 'RandomizedSearchCV', 'ShuffleSplit', 'StratifiedKFold', + 'StratifiedGroupKFold', 'StratifiedShuffleSplit', 'check_cv', 'cross_val_predict', diff --git a/sklearn/model_selection/_split.py b/sklearn/model_selection/_split.py index 244b2b63af449..13edbeef071f5 100644 --- a/sklearn/model_selection/_split.py +++ b/sklearn/model_selection/_split.py @@ -3,13 +3,16 @@ functions to split the data based on a preset strategy. """ -# Author: Alexandre Gramfort <[email protected]>, -# Gael Varoquaux <[email protected]>, +# Author: Alexandre Gramfort <[email protected]> +# Gael Varoquaux <[email protected]> # Olivier Grisel <[email protected]> # Raghav RV <[email protected]> +# Leandro Hermida <[email protected]> +# Rodion Martynov <[email protected]> # License: BSD 3 clause from collections.abc import Iterable +from collections import defaultdict import warnings from itertools import chain, combinations from math import ceil, floor @@ -40,6 +43,7 @@ 'ShuffleSplit', 'GroupShuffleSplit', 'StratifiedKFold', + 'StratifiedGroupKFold', 'StratifiedShuffleSplit', 'PredefinedSplit', 'train_test_split', @@ -732,6 +736,190 @@ def split(self, X, y, groups=None): return super().split(X, y, groups) +class StratifiedGroupKFold(_BaseKFold): + """Stratified K-Folds iterator variant with non-overlapping groups. + + This cross-validation object is a variation of StratifiedKFold attempts to + return stratified folds with non-overlapping groups. The folds are made by + preserving the percentage of samples for each class. + + The same group will not appear in two different folds (the number of + distinct groups has to be at least equal to the number of folds). + + The difference between GroupKFold and StratifiedGroupKFold is that + the former attempts to create balanced folds such that the number of + distinct groups is approximately the same in each fold, whereas + StratifiedGroupKFold attempts to create folds which preserve the + percentage of samples for each class as much as possible given the + constraint of non-overlapping groups between splits. + + Read more in the :ref:`User Guide <cross_validation>`. + + Parameters + ---------- + n_splits : int, default=5 + Number of folds. Must be at least 2. + + shuffle : bool, default=False + Whether to shuffle each class's samples before splitting into batches. + Note that the samples within each split will not be shuffled. + This implementation can only shuffle groups that have approximately the + same y distribution, no global shuffle will be performed. + + random_state : int or RandomState instance, default=None + When `shuffle` is True, `random_state` affects the ordering of the + indices, which controls the randomness of each fold for each class. + Otherwise, leave `random_state` as `None`. + Pass an int for reproducible output across multiple function calls. + See :term:`Glossary <random_state>`. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.model_selection import StratifiedGroupKFold + >>> X = np.ones((17, 2)) + >>> y = np.array([0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]) + >>> groups = np.array([1, 1, 2, 2, 3, 3, 3, 4, 5, 5, 5, 5, 6, 6, 7, 8, 8]) + >>> cv = StratifiedGroupKFold(n_splits=3) + >>> for train_idxs, test_idxs in cv.split(X, y, groups): + ... print("TRAIN:", groups[train_idxs]) + ... print(" ", y[train_idxs]) + ... print(" TEST:", groups[test_idxs]) + ... print(" ", y[test_idxs]) + TRAIN: [1 1 2 2 4 5 5 5 5 8 8] + [0 0 1 1 1 0 0 0 0 0 0] + TEST: [3 3 3 6 6 7] + [1 1 1 0 0 0] + TRAIN: [3 3 3 4 5 5 5 5 6 6 7] + [1 1 1 1 0 0 0 0 0 0 0] + TEST: [1 1 2 2 8 8] + [0 0 1 1 0 0] + TRAIN: [1 1 2 2 3 3 3 6 6 7 8 8] + [0 0 1 1 1 1 1 0 0 0 0 0] + TEST: [4 5 5 5 5] + [1 0 0 0 0] + + Notes + ----- + The implementation is designed to: + + * Mimic the behavior of StratifiedKFold as much as possible for trivial + groups (e.g. when each group contains only one sample). + * Be invariant to class label: relabelling ``y = ["Happy", "Sad"]`` to + ``y = [1, 0]`` should not change the indices generated. + * Stratify based on samples as much as possible while keeping + non-overlapping groups constraint. That means that in some cases when + there is a small number of groups containing a large number of samples + the stratification will not be possible and the behavior will be close + to GroupKFold. + + See also + -------- + StratifiedKFold: Takes class information into account to build folds which + retain class distributions (for binary or multiclass classification + tasks). + + GroupKFold: K-fold iterator variant with non-overlapping groups. + """ + + def __init__(self, n_splits=5, shuffle=False, random_state=None): + super().__init__(n_splits=n_splits, shuffle=shuffle, + random_state=random_state) + + def _iter_test_indices(self, X, y, groups): + # Implementation is based on this kaggle kernel: + # https://www.kaggle.com/jakubwasikowski/stratified-group-k-fold-cross-validation + # and is a subject to Apache 2.0 License. You may obtain a copy of the + # License at http://www.apache.org/licenses/LICENSE-2.0 + # Changelist: + # - Refactored function to a class following scikit-learn KFold + # interface. + # - Added heuristic for assigning group to the least populated fold in + # cases when all other criteria are equal + # - Swtch from using python ``Counter`` to ``np.unique`` to get class + # distribution + # - Added scikit-learn checks for input: checking that target is binary + # or multiclass, checking passed random state, checking that number + # of splits is less than number of members in each class, checking + # that least populated class has more members than there are splits. + rng = check_random_state(self.random_state) + y = np.asarray(y) + type_of_target_y = type_of_target(y) + allowed_target_types = ('binary', 'multiclass') + if type_of_target_y not in allowed_target_types: + raise ValueError( + 'Supported target types are: {}. Got {!r} instead.'.format( + allowed_target_types, type_of_target_y)) + + y = column_or_1d(y) + _, y_inv, y_cnt = np.unique(y, return_inverse=True, return_counts=True) + if np.all(self.n_splits > y_cnt): + raise ValueError("n_splits=%d cannot be greater than the" + " number of members in each class." + % (self.n_splits)) + n_smallest_class = np.min(y_cnt) + if self.n_splits > n_smallest_class: + warnings.warn(("The least populated class in y has only %d" + " members, which is less than n_splits=%d." + % (n_smallest_class, self.n_splits)), UserWarning) + n_classes = len(y_cnt) + + _, groups_inv, groups_cnt = np.unique( + groups, return_inverse=True, return_counts=True) + y_counts_per_group = np.zeros((len(groups_cnt), n_classes)) + for class_idx, group_idx in zip(y_inv, groups_inv): + y_counts_per_group[group_idx, class_idx] += 1 + + y_counts_per_fold = np.zeros((self.n_splits, n_classes)) + groups_per_fold = defaultdict(set) + + if self.shuffle: + rng.shuffle(y_counts_per_group) + + # Stable sort to keep shuffled order for groups with the same + # class distribution variance + sorted_groups_idx = np.argsort(-np.std(y_counts_per_group, axis=1), + kind='mergesort') + + for group_idx in sorted_groups_idx: + group_y_counts = y_counts_per_group[group_idx] + best_fold = self._find_best_fold( + y_counts_per_fold=y_counts_per_fold, y_cnt=y_cnt, + group_y_counts=group_y_counts) + y_counts_per_fold[best_fold] += group_y_counts + groups_per_fold[best_fold].add(group_idx) + + for i in range(self.n_splits): + test_indices = [idx for idx, group_idx in enumerate(groups_inv) + if group_idx in groups_per_fold[i]] + yield test_indices + + def _find_best_fold( + self, y_counts_per_fold, y_cnt, group_y_counts): + best_fold = None + min_eval = np.inf + min_samples_in_fold = np.inf + for i in range(self.n_splits): + y_counts_per_fold[i] += group_y_counts + # Summarise the distribution over classes in each proposed fold + std_per_class = np.std( + y_counts_per_fold / y_cnt.reshape(1, -1), + axis=0) + y_counts_per_fold[i] -= group_y_counts + fold_eval = np.mean(std_per_class) + samples_in_fold = np.sum(y_counts_per_fold[i]) + is_current_fold_better = ( + fold_eval < min_eval or + np.isclose(fold_eval, min_eval) + and samples_in_fold < min_samples_in_fold + ) + if is_current_fold_better: + min_eval = fold_eval + min_samples_in_fold = samples_in_fold + best_fold = i + return best_fold + + class TimeSeriesSplit(_BaseKFold): """Time Series cross-validator
diff --git a/sklearn/model_selection/tests/test_split.py b/sklearn/model_selection/tests/test_split.py index 80c19c7f2e08c..c66d8e1836ac9 100644 --- a/sklearn/model_selection/tests/test_split.py +++ b/sklearn/model_selection/tests/test_split.py @@ -35,6 +35,7 @@ from sklearn.model_selection import GridSearchCV from sklearn.model_selection import RepeatedKFold from sklearn.model_selection import RepeatedStratifiedKFold +from sklearn.model_selection import StratifiedGroupKFold from sklearn.linear_model import Ridge @@ -80,6 +81,7 @@ def test_cross_validator_with_default_params(): lopo = LeavePGroupsOut(p) ss = ShuffleSplit(random_state=0) ps = PredefinedSplit([1, 1, 2, 2]) # n_splits = np of unique folds = 2 + sgkf = StratifiedGroupKFold(n_splits) loo_repr = "LeaveOneOut()" lpo_repr = "LeavePOut(p=2)" @@ -90,15 +92,17 @@ def test_cross_validator_with_default_params(): ss_repr = ("ShuffleSplit(n_splits=10, random_state=0, " "test_size=None, train_size=None)") ps_repr = "PredefinedSplit(test_fold=array([1, 1, 2, 2]))" + sgkf_repr = ("StratifiedGroupKFold(n_splits=2, random_state=None, " + "shuffle=False)") n_splits_expected = [n_samples, comb(n_samples, p), n_splits, n_splits, n_unique_groups, comb(n_unique_groups, p), - n_shuffle_splits, 2] + n_shuffle_splits, 2, n_splits] for i, (cv, cv_repr) in enumerate(zip( - [loo, lpo, kf, skf, lolo, lopo, ss, ps], + [loo, lpo, kf, skf, lolo, lopo, ss, ps, sgkf], [loo_repr, lpo_repr, kf_repr, skf_repr, lolo_repr, lopo_repr, - ss_repr, ps_repr])): + ss_repr, ps_repr, sgkf_repr])): # Test if get_n_splits works correctly assert n_splits_expected[i] == cv.get_n_splits(X, y, groups) @@ -133,10 +137,11 @@ def test_2d_y(): groups = rng.randint(0, 3, size=(n_samples,)) splitters = [LeaveOneOut(), LeavePOut(p=2), KFold(), StratifiedKFold(), RepeatedKFold(), RepeatedStratifiedKFold(), - ShuffleSplit(), StratifiedShuffleSplit(test_size=.5), - GroupShuffleSplit(), LeaveOneGroupOut(), - LeavePGroupsOut(n_groups=2), GroupKFold(n_splits=3), - TimeSeriesSplit(), PredefinedSplit(test_fold=groups)] + StratifiedGroupKFold(), ShuffleSplit(), + StratifiedShuffleSplit(test_size=.5), GroupShuffleSplit(), + LeaveOneGroupOut(), LeavePGroupsOut(n_groups=2), + GroupKFold(n_splits=3), TimeSeriesSplit(), + PredefinedSplit(test_fold=groups)] for splitter in splitters: list(splitter.split(X, y, groups)) list(splitter.split(X, y_2d, groups)) @@ -193,6 +198,11 @@ def test_kfold_valueerrors(): with pytest.warns(Warning, match="The least populated class"): next(skf_3.split(X2, y)) + sgkf_3 = StratifiedGroupKFold(3) + naive_groups = np.arange(len(y)) + with pytest.warns(Warning, match="The least populated class"): + next(sgkf_3.split(X2, y, naive_groups)) + # Check that despite the warning the folds are still computed even # though all the classes are not necessarily represented at on each # side of the split at each split @@ -200,12 +210,20 @@ def test_kfold_valueerrors(): warnings.simplefilter("ignore") check_cv_coverage(skf_3, X2, y, groups=None, expected_n_splits=3) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + check_cv_coverage( + sgkf_3, X2, y, groups=naive_groups, expected_n_splits=3 + ) + # Check that errors are raised if all n_groups for individual # classes are less than n_splits. y = np.array([3, 3, -1, -1, 2]) with pytest.raises(ValueError): next(skf_3.split(X2, y)) + with pytest.raises(ValueError): + next(sgkf_3.split(X2, y)) # Error when number of folds is <= 1 with pytest.raises(ValueError): @@ -218,6 +236,10 @@ def test_kfold_valueerrors(): StratifiedKFold(0) with pytest.raises(ValueError, match=error_string): StratifiedKFold(1) + with pytest.raises(ValueError, match=error_string): + StratifiedGroupKFold(0) + with pytest.raises(ValueError, match=error_string): + StratifiedGroupKFold(1) # When n_splits is not integer: with pytest.raises(ValueError): @@ -228,6 +250,10 @@ def test_kfold_valueerrors(): StratifiedKFold(1.5) with pytest.raises(ValueError): StratifiedKFold(2.0) + with pytest.raises(ValueError): + StratifiedGroupKFold(1.5) + with pytest.raises(ValueError): + StratifiedGroupKFold(2.0) # When shuffle is not a bool: with pytest.raises(TypeError): @@ -318,7 +344,8 @@ def test_stratified_kfold_no_shuffle(): @pytest.mark.parametrize('shuffle', [False, True]) @pytest.mark.parametrize('k', [4, 5, 6, 7, 8, 9, 10]) -def test_stratified_kfold_ratios(k, shuffle): [email protected]('kfold', [StratifiedKFold, StratifiedGroupKFold]) +def test_stratified_kfold_ratios(k, shuffle, kfold): # Check that stratified kfold preserves class ratios in individual splits # Repeat with shuffling turned off and on n_samples = 1000 @@ -326,12 +353,14 @@ def test_stratified_kfold_ratios(k, shuffle): y = np.array([4] * int(0.10 * n_samples) + [0] * int(0.89 * n_samples) + [1] * int(0.01 * n_samples)) + # ensure perfect stratification with StratifiedGroupKFold + groups = np.arange(len(y)) distr = np.bincount(y) / len(y) test_sizes = [] random_state = None if not shuffle else 0 - skf = StratifiedKFold(k, random_state=random_state, shuffle=shuffle) - for train, test in skf.split(X, y): + skf = kfold(k, random_state=random_state, shuffle=shuffle) + for train, test in skf.split(X, y, groups=groups): assert_allclose(np.bincount(y[train]) / len(train), distr, atol=0.02) assert_allclose(np.bincount(y[test]) / len(test), distr, atol=0.02) test_sizes.append(len(test)) @@ -340,20 +369,23 @@ def test_stratified_kfold_ratios(k, shuffle): @pytest.mark.parametrize('shuffle', [False, True]) @pytest.mark.parametrize('k', [4, 6, 7]) -def test_stratified_kfold_label_invariance(k, shuffle): [email protected]('kfold', [StratifiedKFold, StratifiedGroupKFold]) +def test_stratified_kfold_label_invariance(k, shuffle, kfold): # Check that stratified kfold gives the same indices regardless of labels n_samples = 100 y = np.array([2] * int(0.10 * n_samples) + [0] * int(0.89 * n_samples) + [1] * int(0.01 * n_samples)) X = np.ones(len(y)) + # ensure perfect stratification with StratifiedGroupKFold + groups = np.arange(len(y)) def get_splits(y): random_state = None if not shuffle else 0 return [(list(train), list(test)) for train, test - in StratifiedKFold(k, random_state=random_state, - shuffle=shuffle).split(X, y)] + in kfold(k, random_state=random_state, + shuffle=shuffle).split(X, y, groups=groups)] splits_base = get_splits(y) for perm in permutations([0, 1, 2]): @@ -372,17 +404,20 @@ def test_kfold_balance(): assert np.sum(sizes) == i -def test_stratifiedkfold_balance(): [email protected]('kfold', [StratifiedKFold, StratifiedGroupKFold]) +def test_stratifiedkfold_balance(kfold): # Check that KFold returns folds with balanced sizes (only when # stratification is possible) # Repeat with shuffling turned off and on X = np.ones(17) y = [0] * 3 + [1] * 14 + # ensure perfect stratification with StratifiedGroupKFold + groups = np.arange(len(y)) for shuffle in (True, False): - cv = StratifiedKFold(3, shuffle=shuffle) + cv = kfold(3, shuffle=shuffle) for i in range(11, 17): - skf = cv.split(X[:i], y[:i]) + skf = cv.split(X[:i], y[:i], groups[:i]) sizes = [len(test) for _, test in skf] assert (np.max(sizes) - np.min(sizes)) <= 1 @@ -411,39 +446,39 @@ def test_shuffle_kfold(): assert sum(all_folds) == 300 -def test_shuffle_kfold_stratifiedkfold_reproducibility(): [email protected]("kfold", + [KFold, StratifiedKFold, StratifiedGroupKFold]) +def test_shuffle_kfold_stratifiedkfold_reproducibility(kfold): X = np.ones(15) # Divisible by 3 y = [0] * 7 + [1] * 8 + groups_1 = np.arange(len(y)) X2 = np.ones(16) # Not divisible by 3 y2 = [0] * 8 + [1] * 8 + groups_2 = np.arange(len(y2)) # Check that when the shuffle is True, multiple split calls produce the # same split when random_state is int - kf = KFold(3, shuffle=True, random_state=0) - skf = StratifiedKFold(3, shuffle=True, random_state=0) + kf = kfold(3, shuffle=True, random_state=0) - for cv in (kf, skf): - np.testing.assert_equal(list(cv.split(X, y)), list(cv.split(X, y))) - np.testing.assert_equal(list(cv.split(X2, y2)), list(cv.split(X2, y2))) + np.testing.assert_equal( + list(kf.split(X, y, groups_1)), + list(kf.split(X, y, groups_1)) + ) # Check that when the shuffle is True, multiple split calls often # (not always) produce different splits when random_state is # RandomState instance or None - kf = KFold(3, shuffle=True, random_state=np.random.RandomState(0)) - skf = StratifiedKFold(3, shuffle=True, - random_state=np.random.RandomState(0)) - - for cv in (kf, skf): - for data in zip((X, X2), (y, y2)): - # Test if the two splits are different cv - for (_, test_a), (_, test_b) in zip(cv.split(*data), - cv.split(*data)): - # cv.split(...) returns an array of tuples, each tuple - # consisting of an array with train indices and test indices - # Ensure that the splits for data are not same - # when random state is not set - with pytest.raises(AssertionError): - np.testing.assert_array_equal(test_a, test_b) + kf = kfold(3, shuffle=True, random_state=np.random.RandomState(0)) + for data in zip((X, X2), (y, y2), (groups_1, groups_2)): + # Test if the two splits are different cv + for (_, test_a), (_, test_b) in zip(kf.split(*data), + kf.split(*data)): + # cv.split(...) returns an array of tuples, each tuple + # consisting of an array with train indices and test indices + # Ensure that the splits for data are not same + # when random state is not set + with pytest.raises(AssertionError): + np.testing.assert_array_equal(test_a, test_b) def test_shuffle_stratifiedkfold(): @@ -514,6 +549,96 @@ def test_kfold_can_detect_dependent_samples_on_digits(): # see #2372 assert mean_score > 0.80 +def test_stratified_group_kfold_trivial(): + sgkf = StratifiedGroupKFold(n_splits=3) + # Trivial example - groups with the same distribution + y = np.array([1] * 6 + [0] * 12) + X = np.ones_like(y).reshape(-1, 1) + groups = np.asarray((1, 2, 3, 4, 5, 6, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6)) + distr = np.bincount(y) / len(y) + test_sizes = [] + for train, test in sgkf.split(X, y, groups): + # check group constraint + assert np.intersect1d(groups[train], groups[test]).size == 0 + # check y distribution + assert_allclose(np.bincount(y[train]) / len(train), distr, atol=0.02) + assert_allclose(np.bincount(y[test]) / len(test), distr, atol=0.02) + test_sizes.append(len(test)) + assert np.ptp(test_sizes) <= 1 + + +def test_stratified_group_kfold_approximate(): + # Not perfect stratification (even though it is possible) because of + # iteration over groups + sgkf = StratifiedGroupKFold(n_splits=3) + y = np.array([1] * 6 + [0] * 12) + X = np.ones_like(y).reshape(-1, 1) + groups = np.array([1, 2, 3, 3, 4, 4, 1, 1, 2, 2, 3, 4, 5, 5, 5, 6, 6, 6]) + expected = np.asarray([[0.833, 0.166], [0.666, 0.333], [0.5, 0.5]]) + test_sizes = [] + for (train, test), expect_dist in zip(sgkf.split(X, y, groups), expected): + # check group constraint + assert np.intersect1d(groups[train], groups[test]).size == 0 + split_dist = np.bincount(y[test]) / len(test) + assert_allclose(split_dist, expect_dist, atol=0.001) + test_sizes.append(len(test)) + assert np.ptp(test_sizes) <= 1 + + [email protected]('y, groups, expected', + [(np.array([0] * 6 + [1] * 6), + np.array([1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6]), + np.asarray([[.5, .5], + [.5, .5], + [.5, .5]])), + (np.array([0] * 9 + [1] * 3), + np.array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 5, 6]), + np.asarray([[.75, .25], + [.75, .25], + [.75, .25]]))]) +def test_stratified_group_kfold_homogeneous_groups(y, groups, expected): + sgkf = StratifiedGroupKFold(n_splits=3) + X = np.ones_like(y).reshape(-1, 1) + for (train, test), expect_dist in zip(sgkf.split(X, y, groups), expected): + # check group constraint + assert np.intersect1d(groups[train], groups[test]).size == 0 + split_dist = np.bincount(y[test]) / len(test) + assert_allclose(split_dist, expect_dist, atol=0.001) + + [email protected]('cls_distr', + [(0.4, 0.6), + (0.3, 0.7), + (0.2, 0.8), + (0.8, 0.2)]) [email protected]('n_groups', [5, 30, 70]) +def test_stratified_group_kfold_against_group_kfold(cls_distr, n_groups): + # Check that given sufficient amount of samples StratifiedGroupKFold + # produces better stratified folds than regular GroupKFold + n_splits = 5 + sgkf = StratifiedGroupKFold(n_splits=n_splits) + gkf = GroupKFold(n_splits=n_splits) + rng = np.random.RandomState(0) + n_points = 1000 + y = rng.choice(2, size=n_points, p=cls_distr) + X = np.ones_like(y).reshape(-1, 1) + g = rng.choice(n_groups, n_points) + sgkf_folds = sgkf.split(X, y, groups=g) + gkf_folds = gkf.split(X, y, groups=g) + sgkf_entr = 0 + gkf_entr = 0 + for (sgkf_train, sgkf_test), (_, gkf_test) in zip(sgkf_folds, gkf_folds): + # check group constraint + assert np.intersect1d(g[sgkf_train], g[sgkf_test]).size == 0 + sgkf_distr = np.bincount(y[sgkf_test]) / len(sgkf_test) + gkf_distr = np.bincount(y[gkf_test]) / len(gkf_test) + sgkf_entr += stats.entropy(sgkf_distr, qk=cls_distr) + gkf_entr += stats.entropy(gkf_distr, qk=cls_distr) + sgkf_entr /= n_splits + gkf_entr /= n_splits + assert sgkf_entr <= gkf_entr + + def test_shuffle_split(): ss1 = ShuffleSplit(test_size=0.2, random_state=0).split(X) ss2 = ShuffleSplit(test_size=2, random_state=0).split(X) @@ -1310,7 +1435,8 @@ def test_cv_iterable_wrapper(): "successive calls to split should yield different results") -def test_group_kfold(): [email protected]('kfold', [GroupKFold, StratifiedGroupKFold]) +def test_group_kfold(kfold): rng = np.random.RandomState(0) # Parameters of the test @@ -1329,7 +1455,7 @@ def test_group_kfold(): len(np.unique(groups)) # Get the test fold indices from the test set indices of each fold folds = np.zeros(n_samples) - lkf = GroupKFold(n_splits=n_splits) + lkf = kfold(n_splits=n_splits) for i, (_, test) in enumerate(lkf.split(X, y, groups)): folds[test] = i @@ -1569,7 +1695,7 @@ def test_nested_cv(): groups = rng.randint(0, 5, 15) cvs = [LeaveOneGroupOut(), LeaveOneOut(), GroupKFold(n_splits=3), - StratifiedKFold(), + StratifiedKFold(), StratifiedGroupKFold(), StratifiedShuffleSplit(n_splits=3, random_state=0)] for inner_cv, outer_cv in combinations_with_replacement(cvs, 2): @@ -1640,7 +1766,8 @@ def test_leave_p_out_empty_trainset(): next(cv.split(X, y, groups=[1, 2])) [email protected]('Klass', (KFold, StratifiedKFold)) [email protected]('Klass', + (KFold, StratifiedKFold, StratifiedGroupKFold)) def test_random_state_shuffle_false(Klass): # passing a non-default random_state when shuffle=False makes no sense with pytest.raises(ValueError, @@ -1653,6 +1780,8 @@ def test_random_state_shuffle_false(Klass): (KFold(shuffle=True, random_state=123), True), (StratifiedKFold(), True), (StratifiedKFold(shuffle=True, random_state=123), True), + (StratifiedGroupKFold(shuffle=True, random_state=123), True), + (StratifiedGroupKFold(), True), (RepeatedKFold(random_state=123), True), (RepeatedStratifiedKFold(random_state=123), True), (ShuffleSplit(random_state=123), True), @@ -1664,7 +1793,6 @@ def test_random_state_shuffle_false(Klass): (LeaveOneGroupOut(), True), (LeavePGroupsOut(n_groups=2), True), (LeavePOut(p=2), True), - (KFold(shuffle=True, random_state=None), False), (KFold(shuffle=True, random_state=None), False), (StratifiedKFold(shuffle=True, random_state=np.random.RandomState(0)),
[ { "path": "doc/modules/classes.rst", "old_path": "a/doc/modules/classes.rst", "new_path": "b/doc/modules/classes.rst", "metadata": "diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst\nindex c658bc6b12452..d019af3cfb1ff 100644\n--- a/doc/modules/classes.rst\n+++ b/doc/modules/classes.rst\n@@ -1176,6 +1176,7 @@ Splitter Classes\n model_selection.ShuffleSplit\n model_selection.StratifiedKFold\n model_selection.StratifiedShuffleSplit\n+ model_selection.StratifiedGroupKFold\n model_selection.TimeSeriesSplit\n \n Splitter Functions\n" }, { "path": "doc/modules/cross_validation.rst", "old_path": "a/doc/modules/cross_validation.rst", "new_path": "b/doc/modules/cross_validation.rst", "metadata": "diff --git a/doc/modules/cross_validation.rst b/doc/modules/cross_validation.rst\nindex ae3d38f168f3f..0b090fd7385b6 100644\n--- a/doc/modules/cross_validation.rst\n+++ b/doc/modules/cross_validation.rst\n@@ -353,7 +353,7 @@ Example of 2-fold cross-validation on a dataset with 4 samples::\n Here is a visualization of the cross-validation behavior. Note that\n :class:`KFold` is not affected by classes or groups.\n \n-.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_004.png\n+.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_006.png\n :target: ../auto_examples/model_selection/plot_cv_indices.html\n :align: center\n :scale: 75%\n@@ -509,7 +509,7 @@ Here is a usage example::\n Here is a visualization of the cross-validation behavior. Note that\n :class:`ShuffleSplit` is not affected by classes or groups.\n \n-.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_006.png\n+.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_008.png\n :target: ../auto_examples/model_selection/plot_cv_indices.html\n :align: center\n :scale: 75%\n@@ -566,7 +566,7 @@ We can see that :class:`StratifiedKFold` preserves the class ratios\n \n Here is a visualization of the cross-validation behavior.\n \n-.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_007.png\n+.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_009.png\n :target: ../auto_examples/model_selection/plot_cv_indices.html\n :align: center\n :scale: 75%\n@@ -585,7 +585,7 @@ percentage for each target class as in the complete set.\n \n Here is a visualization of the cross-validation behavior.\n \n-.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_009.png\n+.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_012.png\n :target: ../auto_examples/model_selection/plot_cv_indices.html\n :align: center\n :scale: 75%\n@@ -645,6 +645,58 @@ size due to the imbalance in the data.\n \n Here is a visualization of the cross-validation behavior.\n \n+.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_007.png\n+ :target: ../auto_examples/model_selection/plot_cv_indices.html\n+ :align: center\n+ :scale: 75%\n+\n+.. _stratified_group_k_fold:\n+\n+StratifiedGroupKFold\n+^^^^^^^^^^^^^^^^^^^^\n+\n+:class:`StratifiedGroupKFold` is a cross-validation scheme that combines both\n+:class:`StratifiedKFold` and :class:`GroupKFold`. The idea is to try to\n+preserve the distribution of classes in each split while keeping each group\n+within a single split. That might be useful when you have an unbalanced\n+dataset so that using just :class:`GroupKFold` might produce skewed splits.\n+\n+Example::\n+\n+ >>> from sklearn.model_selection import StratifiedGroupKFold\n+ >>> X = list(range(18))\n+ >>> y = [1] * 6 + [0] * 12\n+ >>> groups = [1, 2, 3, 3, 4, 4, 1, 1, 2, 2, 3, 4, 5, 5, 5, 6, 6, 6]\n+ >>> sgkf = StratifiedGroupKFold(n_splits=3)\n+ >>> for train, test in sgkf.split(X, y, groups=groups):\n+ ... print(\"%s %s\" % (train, test))\n+ [ 0 2 3 4 5 6 7 10 11 15 16 17] [ 1 8 9 12 13 14]\n+ [ 0 1 4 5 6 7 8 9 11 12 13 14] [ 2 3 10 15 16 17]\n+ [ 1 2 3 8 9 10 12 13 14 15 16 17] [ 0 4 5 6 7 11]\n+\n+Implementation notes:\n+\n+- With the current implementation full shuffle is not possible in most\n+ scenarios. When shuffle=True, the following happens:\n+\n+ 1. All groups a shuffled.\n+ 2. Groups are sorted by standard deviation of classes using stable sort.\n+ 3. Sorted groups are iterated over and assigned to folds.\n+\n+ That means that only groups with the same standard deviation of class\n+ distribution will be shuffled, which might be useful when each group has only\n+ a single class.\n+- The algorithm greedily assigns each group to one of n_splits test sets,\n+ choosing the test set that minimises the variance in class distribution\n+ across test sets. Group assignment proceeds from groups with highest to\n+ lowest variance in class frequency, i.e. large groups peaked on one or few\n+ classes are assigned first.\n+- This split is suboptimal in a sense that it might produce imbalanced splits\n+ even if perfect stratification is possible. If you have relatively close\n+ distribution of classes in each group, using :class:`GroupKFold` is better.\n+\n+Here is a visualization of cross-validation behavior for uneven groups:\n+\n .. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_005.png\n :target: ../auto_examples/model_selection/plot_cv_indices.html\n :align: center\n@@ -733,7 +785,7 @@ Here is a usage example::\n \n Here is a visualization of the cross-validation behavior.\n \n-.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_008.png\n+.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_011.png\n :target: ../auto_examples/model_selection/plot_cv_indices.html\n :align: center\n :scale: 75%\n@@ -835,7 +887,7 @@ Example of 3-split time series cross-validation on a dataset with 6 samples::\n \n Here is a visualization of the cross-validation behavior.\n \n-.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_010.png\n+.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_013.png\n :target: ../auto_examples/model_selection/plot_cv_indices.html\n :align: center\n :scale: 75%\n" }, { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 34f39ca48f20a..985fe57164824 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -183,6 +183,16 @@ Changelog\n are integral.\n :pr:`9843` by :user:`Jon Crall <Erotemic>`.\n \n+:mod:`sklearn.model_selection`\n+..............................\n+\n+- |Feature| added :class:`model_selection.StratifiedGroupKFold`, that combines\n+ :class:`model_selection.StratifiedKFold` and `model_selection.GroupKFold`,\n+ providing an ability to split data preserving the distribution of classes in\n+ each split while keeping each group within a single split.\n+ :pr:`18649` by `Leandro Hermida <hermidalc>` and\n+ `Rodion Martynov <marrodion>`.\n+\n :mod:`sklearn.naive_bayes`\n ..........................\n \n" } ]
1.00
fe897c0ba0f00171333dcbdb483ca0d0346fed95
[]
[ "sklearn/model_selection/tests/test_split.py::test_train_test_split_mock_pandas", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedGroupKFold-5-False]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv25-False]", "sklearn/model_selection/tests/test_split.py::test_stratified_shuffle_split_multilabel_many_labels", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv8-True]", "sklearn/model_selection/tests/test_split.py::test_repeated_cv_value_errors", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedKFold-8-True]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_label_invariance[StratifiedGroupKFold-6-False]", "sklearn/model_selection/tests/test_split.py::test_shuffle_split_default_test_size[0.8-8-2-StratifiedShuffleSplit]", "sklearn/model_selection/tests/test_split.py::test_kfold_indices", "sklearn/model_selection/tests/test_split.py::test_predefinedsplit_with_kfold_split", "sklearn/model_selection/tests/test_split.py::test_shuffle_kfold_stratifiedkfold_reproducibility[StratifiedGroupKFold]", "sklearn/model_selection/tests/test_split.py::test_stratifiedkfold_balance[StratifiedGroupKFold]", "sklearn/model_selection/tests/test_split.py::test_time_series_test_size", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedKFold-9-True]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv23-False]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_label_invariance[StratifiedGroupKFold-6-True]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_default_test_size[8-8-2]", "sklearn/model_selection/tests/test_split.py::test_stratified_group_kfold_against_group_kfold[70-cls_distr0]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_default_test_size[None-7-3]", "sklearn/model_selection/tests/test_split.py::test_shuffle_split_empty_trainset[GroupShuffleSplit]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_label_invariance[StratifiedGroupKFold-4-False]", "sklearn/model_selection/tests/test_split.py::test_leave_one_p_group_out", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedKFold-7-False]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedGroupKFold-6-False]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedGroupKFold-8-True]", "sklearn/model_selection/tests/test_split.py::test_2d_y", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes1[0.0-0.8]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_label_invariance[StratifiedKFold-6-True]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_label_invariance[StratifiedGroupKFold-7-False]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv12-True]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedKFold-10-True]", "sklearn/model_selection/tests/test_split.py::test_shuffle_split_default_test_size[None-9-1-ShuffleSplit]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedKFold-6-True]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_pandas", "sklearn/model_selection/tests/test_split.py::test_group_shuffle_split", "sklearn/model_selection/tests/test_split.py::test_shufflesplit_errors[8-3]", "sklearn/model_selection/tests/test_split.py::test_leave_group_out_changing_groups", "sklearn/model_selection/tests/test_split.py::test_train_test_split_list_input", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedGroupKFold-10-True]", "sklearn/model_selection/tests/test_split.py::test_stratified_group_kfold_against_group_kfold[5-cls_distr0]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes1[1.0-0.8]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_no_shuffle", "sklearn/model_selection/tests/test_split.py::test_stratified_group_kfold_trivial", "sklearn/model_selection/tests/test_split.py::test_stratified_group_kfold_against_group_kfold[70-cls_distr3]", "sklearn/model_selection/tests/test_split.py::test_cross_validator_with_default_params", "sklearn/model_selection/tests/test_split.py::test_stratified_group_kfold_against_group_kfold[5-cls_distr3]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedKFold-10-False]", "sklearn/model_selection/tests/test_split.py::test_train_test_split", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedGroupKFold-9-False]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv15-True]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes1[0.8-1.0]", "sklearn/model_selection/tests/test_split.py::test_stratified_group_kfold_against_group_kfold[30-cls_distr0]", "sklearn/model_selection/tests/test_split.py::test_stratified_group_kfold_against_group_kfold[5-cls_distr1]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv6-True]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv19-False]", "sklearn/model_selection/tests/test_split.py::test_kfold_no_shuffle", "sklearn/model_selection/tests/test_split.py::test_stratifiedshufflesplit_list_input", "sklearn/model_selection/tests/test_split.py::test_repeated_stratified_kfold_determinstic_split", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes2[0.8--10]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv3-True]", "sklearn/model_selection/tests/test_split.py::test_stratified_shuffle_split_multilabel", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedKFold-5-False]", "sklearn/model_selection/tests/test_split.py::test_stratified_shuffle_split_respects_test_size", "sklearn/model_selection/tests/test_split.py::test_time_series_gap", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedKFold-7-True]", "sklearn/model_selection/tests/test_split.py::test_build_repr", "sklearn/model_selection/tests/test_split.py::test_shuffle_stratifiedkfold", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedGroupKFold-8-False]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes1[1.2-0.8]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_label_invariance[StratifiedKFold-7-True]", "sklearn/model_selection/tests/test_split.py::test_leave_one_out_empty_trainset", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv21-False]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv24-False]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv20-False]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_label_invariance[StratifiedKFold-6-False]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_label_invariance[StratifiedKFold-4-False]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_allow_nans", "sklearn/model_selection/tests/test_split.py::test_random_state_shuffle_false[StratifiedKFold]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes2[0.8-11]", "sklearn/model_selection/tests/test_split.py::test_shufflesplit_errors[2.0-None]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedKFold-4-True]", "sklearn/model_selection/tests/test_split.py::test_stratified_group_kfold_against_group_kfold[70-cls_distr1]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv30-False]", "sklearn/model_selection/tests/test_split.py::test_shuffle_kfold", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_label_invariance[StratifiedKFold-7-False]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedGroupKFold-6-True]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_label_invariance[StratifiedKFold-4-True]", "sklearn/model_selection/tests/test_split.py::test_shufflesplit_errors[1.0-None]", "sklearn/model_selection/tests/test_split.py::test_random_state_shuffle_false[KFold]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv2-True]", "sklearn/model_selection/tests/test_split.py::test_stratified_group_kfold_homogeneous_groups[y0-groups0-expected0]", "sklearn/model_selection/tests/test_split.py::test_shuffle_split", "sklearn/model_selection/tests/test_split.py::test_time_series_cv", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes1[0.8--0.2]", "sklearn/model_selection/tests/test_split.py::test_stratified_group_kfold_against_group_kfold[30-cls_distr3]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes2[-10-0.8]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedGroupKFold-10-False]", "sklearn/model_selection/tests/test_split.py::test_shuffle_split_empty_trainset[StratifiedShuffleSplit]", "sklearn/model_selection/tests/test_split.py::test_stratified_group_kfold_homogeneous_groups[y1-groups1-expected1]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_label_invariance[StratifiedGroupKFold-4-True]", "sklearn/model_selection/tests/test_split.py::test_cv_iterable_wrapper", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv11-True]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_sparse", "sklearn/model_selection/tests/test_split.py::test_shufflesplit_reproducible", "sklearn/model_selection/tests/test_split.py::test_group_kfold[GroupKFold]", "sklearn/model_selection/tests/test_split.py::test_group_shuffle_split_default_test_size[None-8-2]", "sklearn/model_selection/tests/test_split.py::test_time_series_max_train_size", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv5-True]", "sklearn/model_selection/tests/test_split.py::test_group_kfold[StratifiedGroupKFold]", "sklearn/model_selection/tests/test_split.py::test_nested_cv", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv28-False]", "sklearn/model_selection/tests/test_split.py::test_check_cv", "sklearn/model_selection/tests/test_split.py::test_stratified_group_kfold_against_group_kfold[5-cls_distr2]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedGroupKFold-4-False]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_default_test_size[0.8-8-2]", "sklearn/model_selection/tests/test_split.py::test_stratified_shuffle_split_even", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv4-True]", "sklearn/model_selection/tests/test_split.py::test_group_shuffle_split_default_test_size[0.7-7-3]", "sklearn/model_selection/tests/test_split.py::test_leave_one_p_group_out_error_on_fewer_number_of_groups", "sklearn/model_selection/tests/test_split.py::test_stratified_group_kfold_against_group_kfold[30-cls_distr2]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedKFold-9-False]", "sklearn/model_selection/tests/test_split.py::test_stratified_shuffle_split_overlap_train_test_bug", "sklearn/model_selection/tests/test_split.py::test_shuffle_split_default_test_size[None-9-1-StratifiedShuffleSplit]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes2[0.8-0]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv7-True]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv18-False]", "sklearn/model_selection/tests/test_split.py::test_kfold_balance", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv16-True]", "sklearn/model_selection/tests/test_split.py::test_stratified_group_kfold_against_group_kfold[30-cls_distr1]", "sklearn/model_selection/tests/test_split.py::test_shuffle_split_default_test_size[8-8-2-ShuffleSplit]", "sklearn/model_selection/tests/test_split.py::test_shuffle_split_default_test_size[8-8-2-StratifiedShuffleSplit]", "sklearn/model_selection/tests/test_split.py::test_stratified_shuffle_split_init", "sklearn/model_selection/tests/test_split.py::test_train_test_split_empty_trainset", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv29-False]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_errors", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes1[0.8-0.0]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedKFold-5-True]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv26-False]", "sklearn/model_selection/tests/test_split.py::test_shuffle_split_default_test_size[0.8-8-2-ShuffleSplit]", "sklearn/model_selection/tests/test_split.py::test_shufflesplit_errors[10-None]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes1[-0.2-0.8]", "sklearn/model_selection/tests/test_split.py::test_get_n_splits_for_repeated_kfold", "sklearn/model_selection/tests/test_split.py::test_shufflesplit_errors[None-1j]", "sklearn/model_selection/tests/test_split.py::test_get_n_splits_for_repeated_stratified_kfold", "sklearn/model_selection/tests/test_split.py::test_stratified_shuffle_split_iter", "sklearn/model_selection/tests/test_split.py::test_repeated_cv_repr[RepeatedStratifiedKFold]", "sklearn/model_selection/tests/test_split.py::test_repeated_kfold_determinstic_split", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedGroupKFold-7-False]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv9-True]", "sklearn/model_selection/tests/test_split.py::test_kfold_can_detect_dependent_samples_on_digits", "sklearn/model_selection/tests/test_split.py::test_stratifiedkfold_balance[StratifiedKFold]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedGroupKFold-4-True]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedKFold-4-False]", "sklearn/model_selection/tests/test_split.py::test_random_state_shuffle_false[StratifiedGroupKFold]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedKFold-8-False]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedKFold-6-False]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_label_invariance[StratifiedGroupKFold-7-True]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes2[11-0.8]", "sklearn/model_selection/tests/test_split.py::test_shuffle_kfold_stratifiedkfold_reproducibility[KFold]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedGroupKFold-5-True]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedGroupKFold-7-True]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv13-True]", "sklearn/model_selection/tests/test_split.py::test_shuffle_kfold_stratifiedkfold_reproducibility[StratifiedKFold]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv17-False]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv22-False]", "sklearn/model_selection/tests/test_split.py::test_stratified_group_kfold_approximate", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes2[0-0.8]", "sklearn/model_selection/tests/test_split.py::test_shufflesplit_errors[0.1-0.95]", "sklearn/model_selection/tests/test_split.py::test_leave_p_out_empty_trainset", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv27-False]", "sklearn/model_selection/tests/test_split.py::test_shufflesplit_errors[11-None]", "sklearn/model_selection/tests/test_split.py::test_repeated_cv_repr[RepeatedKFold]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv14-True]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv10-True]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[StratifiedGroupKFold-9-True]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes1[0.8-1.2]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv0-True]", "sklearn/model_selection/tests/test_split.py::test_kfold_valueerrors", "sklearn/model_selection/tests/test_split.py::test_shuffle_split_empty_trainset[ShuffleSplit]", "sklearn/model_selection/tests/test_split.py::test_group_shuffle_split_default_test_size[7-7-3]", "sklearn/model_selection/tests/test_split.py::test_stratified_group_kfold_against_group_kfold[70-cls_distr2]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv1-True]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/modules/classes.rst", "old_path": "a/doc/modules/classes.rst", "new_path": "b/doc/modules/classes.rst", "metadata": "diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst\nindex c658bc6b12452..d019af3cfb1ff 100644\n--- a/doc/modules/classes.rst\n+++ b/doc/modules/classes.rst\n@@ -1176,6 +1176,7 @@ Splitter Classes\n model_selection.ShuffleSplit\n model_selection.StratifiedKFold\n model_selection.StratifiedShuffleSplit\n+ model_selection.StratifiedGroupKFold\n model_selection.TimeSeriesSplit\n \n Splitter Functions\n" }, { "path": "doc/modules/cross_validation.rst", "old_path": "a/doc/modules/cross_validation.rst", "new_path": "b/doc/modules/cross_validation.rst", "metadata": "diff --git a/doc/modules/cross_validation.rst b/doc/modules/cross_validation.rst\nindex ae3d38f168f3f..0b090fd7385b6 100644\n--- a/doc/modules/cross_validation.rst\n+++ b/doc/modules/cross_validation.rst\n@@ -353,7 +353,7 @@ Example of 2-fold cross-validation on a dataset with 4 samples::\n Here is a visualization of the cross-validation behavior. Note that\n :class:`KFold` is not affected by classes or groups.\n \n-.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_004.png\n+.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_006.png\n :target: ../auto_examples/model_selection/plot_cv_indices.html\n :align: center\n :scale: 75%\n@@ -509,7 +509,7 @@ Here is a usage example::\n Here is a visualization of the cross-validation behavior. Note that\n :class:`ShuffleSplit` is not affected by classes or groups.\n \n-.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_006.png\n+.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_008.png\n :target: ../auto_examples/model_selection/plot_cv_indices.html\n :align: center\n :scale: 75%\n@@ -566,7 +566,7 @@ We can see that :class:`StratifiedKFold` preserves the class ratios\n \n Here is a visualization of the cross-validation behavior.\n \n-.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_007.png\n+.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_009.png\n :target: ../auto_examples/model_selection/plot_cv_indices.html\n :align: center\n :scale: 75%\n@@ -585,7 +585,7 @@ percentage for each target class as in the complete set.\n \n Here is a visualization of the cross-validation behavior.\n \n-.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_009.png\n+.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_012.png\n :target: ../auto_examples/model_selection/plot_cv_indices.html\n :align: center\n :scale: 75%\n@@ -645,6 +645,58 @@ size due to the imbalance in the data.\n \n Here is a visualization of the cross-validation behavior.\n \n+.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_007.png\n+ :target: ../auto_examples/model_selection/plot_cv_indices.html\n+ :align: center\n+ :scale: 75%\n+\n+.. _stratified_group_k_fold:\n+\n+StratifiedGroupKFold\n+^^^^^^^^^^^^^^^^^^^^\n+\n+:class:`StratifiedGroupKFold` is a cross-validation scheme that combines both\n+:class:`StratifiedKFold` and :class:`GroupKFold`. The idea is to try to\n+preserve the distribution of classes in each split while keeping each group\n+within a single split. That might be useful when you have an unbalanced\n+dataset so that using just :class:`GroupKFold` might produce skewed splits.\n+\n+Example::\n+\n+ >>> from sklearn.model_selection import StratifiedGroupKFold\n+ >>> X = list(range(18))\n+ >>> y = [1] * 6 + [0] * 12\n+ >>> groups = [1, 2, 3, 3, 4, 4, 1, 1, 2, 2, 3, 4, 5, 5, 5, 6, 6, 6]\n+ >>> sgkf = StratifiedGroupKFold(n_splits=3)\n+ >>> for train, test in sgkf.split(X, y, groups=groups):\n+ ... print(\"%s %s\" % (train, test))\n+ [ 0 2 3 4 5 6 7 10 11 15 16 17] [ 1 8 9 12 13 14]\n+ [ 0 1 4 5 6 7 8 9 11 12 13 14] [ 2 3 10 15 16 17]\n+ [ 1 2 3 8 9 10 12 13 14 15 16 17] [ 0 4 5 6 7 11]\n+\n+Implementation notes:\n+\n+- With the current implementation full shuffle is not possible in most\n+ scenarios. When shuffle=True, the following happens:\n+\n+ 1. All groups a shuffled.\n+ 2. Groups are sorted by standard deviation of classes using stable sort.\n+ 3. Sorted groups are iterated over and assigned to folds.\n+\n+ That means that only groups with the same standard deviation of class\n+ distribution will be shuffled, which might be useful when each group has only\n+ a single class.\n+- The algorithm greedily assigns each group to one of n_splits test sets,\n+ choosing the test set that minimises the variance in class distribution\n+ across test sets. Group assignment proceeds from groups with highest to\n+ lowest variance in class frequency, i.e. large groups peaked on one or few\n+ classes are assigned first.\n+- This split is suboptimal in a sense that it might produce imbalanced splits\n+ even if perfect stratification is possible. If you have relatively close\n+ distribution of classes in each group, using :class:`GroupKFold` is better.\n+\n+Here is a visualization of cross-validation behavior for uneven groups:\n+\n .. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_005.png\n :target: ../auto_examples/model_selection/plot_cv_indices.html\n :align: center\n@@ -733,7 +785,7 @@ Here is a usage example::\n \n Here is a visualization of the cross-validation behavior.\n \n-.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_008.png\n+.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_011.png\n :target: ../auto_examples/model_selection/plot_cv_indices.html\n :align: center\n :scale: 75%\n@@ -835,7 +887,7 @@ Example of 3-split time series cross-validation on a dataset with 6 samples::\n \n Here is a visualization of the cross-validation behavior.\n \n-.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_010.png\n+.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_013.png\n :target: ../auto_examples/model_selection/plot_cv_indices.html\n :align: center\n :scale: 75%\n" }, { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 34f39ca48f20a..985fe57164824 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -183,6 +183,16 @@ Changelog\n are integral.\n :pr:`<PRID>` by :user:`<NAME>`.\n \n+:mod:`sklearn.model_selection`\n+..............................\n+\n+- |Feature| added :class:`model_selection.StratifiedGroupKFold`, that combines\n+ :class:`model_selection.StratifiedKFold` and `model_selection.GroupKFold`,\n+ providing an ability to split data preserving the distribution of classes in\n+ each split while keeping each group within a single split.\n+ :pr:`<PRID>` by `Leandro Hermida <hermidalc>` and\n+ `Rodion Martynov <marrodion>`.\n+\n :mod:`sklearn.naive_bayes`\n ..........................\n \n" } ]
diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst index c658bc6b12452..d019af3cfb1ff 100644 --- a/doc/modules/classes.rst +++ b/doc/modules/classes.rst @@ -1176,6 +1176,7 @@ Splitter Classes model_selection.ShuffleSplit model_selection.StratifiedKFold model_selection.StratifiedShuffleSplit + model_selection.StratifiedGroupKFold model_selection.TimeSeriesSplit Splitter Functions diff --git a/doc/modules/cross_validation.rst b/doc/modules/cross_validation.rst index ae3d38f168f3f..0b090fd7385b6 100644 --- a/doc/modules/cross_validation.rst +++ b/doc/modules/cross_validation.rst @@ -353,7 +353,7 @@ Example of 2-fold cross-validation on a dataset with 4 samples:: Here is a visualization of the cross-validation behavior. Note that :class:`KFold` is not affected by classes or groups. -.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_004.png +.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_006.png :target: ../auto_examples/model_selection/plot_cv_indices.html :align: center :scale: 75% @@ -509,7 +509,7 @@ Here is a usage example:: Here is a visualization of the cross-validation behavior. Note that :class:`ShuffleSplit` is not affected by classes or groups. -.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_006.png +.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_008.png :target: ../auto_examples/model_selection/plot_cv_indices.html :align: center :scale: 75% @@ -566,7 +566,7 @@ We can see that :class:`StratifiedKFold` preserves the class ratios Here is a visualization of the cross-validation behavior. -.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_007.png +.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_009.png :target: ../auto_examples/model_selection/plot_cv_indices.html :align: center :scale: 75% @@ -585,7 +585,7 @@ percentage for each target class as in the complete set. Here is a visualization of the cross-validation behavior. -.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_009.png +.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_012.png :target: ../auto_examples/model_selection/plot_cv_indices.html :align: center :scale: 75% @@ -645,6 +645,58 @@ size due to the imbalance in the data. Here is a visualization of the cross-validation behavior. +.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_007.png + :target: ../auto_examples/model_selection/plot_cv_indices.html + :align: center + :scale: 75% + +.. _stratified_group_k_fold: + +StratifiedGroupKFold +^^^^^^^^^^^^^^^^^^^^ + +:class:`StratifiedGroupKFold` is a cross-validation scheme that combines both +:class:`StratifiedKFold` and :class:`GroupKFold`. The idea is to try to +preserve the distribution of classes in each split while keeping each group +within a single split. That might be useful when you have an unbalanced +dataset so that using just :class:`GroupKFold` might produce skewed splits. + +Example:: + + >>> from sklearn.model_selection import StratifiedGroupKFold + >>> X = list(range(18)) + >>> y = [1] * 6 + [0] * 12 + >>> groups = [1, 2, 3, 3, 4, 4, 1, 1, 2, 2, 3, 4, 5, 5, 5, 6, 6, 6] + >>> sgkf = StratifiedGroupKFold(n_splits=3) + >>> for train, test in sgkf.split(X, y, groups=groups): + ... print("%s %s" % (train, test)) + [ 0 2 3 4 5 6 7 10 11 15 16 17] [ 1 8 9 12 13 14] + [ 0 1 4 5 6 7 8 9 11 12 13 14] [ 2 3 10 15 16 17] + [ 1 2 3 8 9 10 12 13 14 15 16 17] [ 0 4 5 6 7 11] + +Implementation notes: + +- With the current implementation full shuffle is not possible in most + scenarios. When shuffle=True, the following happens: + + 1. All groups a shuffled. + 2. Groups are sorted by standard deviation of classes using stable sort. + 3. Sorted groups are iterated over and assigned to folds. + + That means that only groups with the same standard deviation of class + distribution will be shuffled, which might be useful when each group has only + a single class. +- The algorithm greedily assigns each group to one of n_splits test sets, + choosing the test set that minimises the variance in class distribution + across test sets. Group assignment proceeds from groups with highest to + lowest variance in class frequency, i.e. large groups peaked on one or few + classes are assigned first. +- This split is suboptimal in a sense that it might produce imbalanced splits + even if perfect stratification is possible. If you have relatively close + distribution of classes in each group, using :class:`GroupKFold` is better. + +Here is a visualization of cross-validation behavior for uneven groups: + .. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_005.png :target: ../auto_examples/model_selection/plot_cv_indices.html :align: center @@ -733,7 +785,7 @@ Here is a usage example:: Here is a visualization of the cross-validation behavior. -.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_008.png +.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_011.png :target: ../auto_examples/model_selection/plot_cv_indices.html :align: center :scale: 75% @@ -835,7 +887,7 @@ Example of 3-split time series cross-validation on a dataset with 6 samples:: Here is a visualization of the cross-validation behavior. -.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_010.png +.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_cv_indices_013.png :target: ../auto_examples/model_selection/plot_cv_indices.html :align: center :scale: 75% diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index 34f39ca48f20a..985fe57164824 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -183,6 +183,16 @@ Changelog are integral. :pr:`<PRID>` by :user:`<NAME>`. +:mod:`sklearn.model_selection` +.............................. + +- |Feature| added :class:`model_selection.StratifiedGroupKFold`, that combines + :class:`model_selection.StratifiedKFold` and `model_selection.GroupKFold`, + providing an ability to split data preserving the distribution of classes in + each split while keeping each group within a single split. + :pr:`<PRID>` by `Leandro Hermida <hermidalc>` and + `Rodion Martynov <marrodion>`. + :mod:`sklearn.naive_bayes` ..........................
scikit-learn/scikit-learn
scikit-learn__scikit-learn-18368
https://github.com/scikit-learn/scikit-learn/pull/18368
diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst index 84f8097cbbe9d..65d555f978df0 100644 --- a/doc/modules/classes.rst +++ b/doc/modules/classes.rst @@ -1414,6 +1414,7 @@ details. preprocessing.PowerTransformer preprocessing.QuantileTransformer preprocessing.RobustScaler + preprocessing.SplineTransformer preprocessing.StandardScaler .. autosummary:: diff --git a/doc/modules/preprocessing.rst b/doc/modules/preprocessing.rst index 801d9a98ed1f4..a339b4bfae4e2 100644 --- a/doc/modules/preprocessing.rst +++ b/doc/modules/preprocessing.rst @@ -624,7 +624,9 @@ of continuous attributes to one with only nominal attributes. One-hot encoded discretized features can make a model more expressive, while maintaining interpretability. For instance, pre-processing with a discretizer -can introduce nonlinearity to linear models. +can introduce nonlinearity to linear models. For more advanced possibilities, +in particular smooth ones, see :ref:`generating_polynomial_features` further +below. K-bins discretization --------------------- @@ -756,12 +758,24 @@ Imputation of missing values Tools for imputing missing values are discussed at :ref:`impute`. -.. _polynomial_features: +.. _generating_polynomial_features: Generating polynomial features ============================== -Often it's useful to add complexity to the model by considering nonlinear features of the input data. A simple and common method to use is polynomial features, which can get features' high-order and interaction terms. It is implemented in :class:`PolynomialFeatures`:: +Often it's useful to add complexity to a model by considering nonlinear +features of the input data. We show two possibilities that are both based on +polynomials: The first one uses pure polynomials, the second one uses splines, +i.e. piecewise polynomials. + +.. _polynomial_features: + +Polynomial features +------------------- + +A simple and common method to use is polynomial features, which can get +features' high-order and interaction terms. It is implemented in +:class:`PolynomialFeatures`:: >>> import numpy as np >>> from sklearn.preprocessing import PolynomialFeatures @@ -776,9 +790,11 @@ Often it's useful to add complexity to the model by considering nonlinear featur [ 1., 2., 3., 4., 6., 9.], [ 1., 4., 5., 16., 20., 25.]]) -The features of X have been transformed from :math:`(X_1, X_2)` to :math:`(1, X_1, X_2, X_1^2, X_1X_2, X_2^2)`. +The features of X have been transformed from :math:`(X_1, X_2)` to +:math:`(1, X_1, X_2, X_1^2, X_1X_2, X_2^2)`. -In some cases, only interaction terms among features are required, and it can be gotten with the setting ``interaction_only=True``:: +In some cases, only interaction terms among features are required, and it can +be gotten with the setting ``interaction_only=True``:: >>> X = np.arange(9).reshape(3, 3) >>> X @@ -791,11 +807,94 @@ In some cases, only interaction terms among features are required, and it can be [ 1., 3., 4., 5., 12., 15., 20., 60.], [ 1., 6., 7., 8., 42., 48., 56., 336.]]) -The features of X have been transformed from :math:`(X_1, X_2, X_3)` to :math:`(1, X_1, X_2, X_3, X_1X_2, X_1X_3, X_2X_3, X_1X_2X_3)`. +The features of X have been transformed from :math:`(X_1, X_2, X_3)` to +:math:`(1, X_1, X_2, X_3, X_1X_2, X_1X_3, X_2X_3, X_1X_2X_3)`. + +Note that polynomial features are used implicitly in `kernel methods +<https://en.wikipedia.org/wiki/Kernel_method>`_ (e.g., :class:`~sklearn.svm.SVC`, +:class:`~sklearn.decomposition.KernelPCA`) when using polynomial :ref:`svm_kernels`. + +See :ref:`sphx_glr_auto_examples_linear_model_plot_polynomial_interpolation.py` +for Ridge regression using created polynomial features. + +.. _spline_transformer: + +Spline transformer +------------------ + +Another way to add nonlinear terms instead of pure polynomials of features is +to generate spline basis functions for each feature with the +:class:`SplineTransformer`. Splines are piecewise polynomials, parametrized by +their polynomial degree and the positions of the knots. The +:class:`SplineTransformer` implements a B-spline basis, cf. the references +below. + +.. note:: + + The :class:`SplineTransformer` treats each feature separately, i.e. it + won't give you interaction terms. + +Some of the advantages of splines over polynomials are: + + - B-splines are very flexible and robust if you keep a fixed low degree, + usually 3, and parsimoniously adapt the number of knots. Polynomials + would need a higher degree, which leads to the next point. + - B-splines do not have oscillatory behaviour at the boundaries as have + polynomials (the higher the degree, the worse). This is known as `Runge's + phenomenon <https://en.wikipedia.org/wiki/Runge%27s_phenomenon>`_. + - B-splines provide good options for extrapolation beyond the boundaries, + i.e. beyond the range of fitted values. Have a look at the option + ``extrapolation``. + - B-splines generate a feature matrix with a banded structure. For a single + feature, every row contains only ``degree + 1`` non-zero elements, which + occur consecutively and are even positive. This results in a matrix with + good numerical properties, e.g. a low condition number, in sharp contrast + to a matrix of polynomials, which goes under the name + `Vandermonde matrix <https://en.wikipedia.org/wiki/Vandermonde_matrix>`_. + A low condition number is important for stable algorithms of linear + models. + +The following code snippet shows splines in action:: + + >>> import numpy as np + >>> from sklearn.preprocessing import SplineTransformer + >>> X = np.arange(5).reshape(5, 1) + >>> X + array([[0], + [1], + [2], + [3], + [4]]) + >>> spline = SplineTransformer(degree=2, n_knots=3) + >>> spline.fit_transform(X) + array([[0.5 , 0.5 , 0. , 0. ], + [0.125, 0.75 , 0.125, 0. ], + [0. , 0.5 , 0.5 , 0. ], + [0. , 0.125, 0.75 , 0.125], + [0. , 0. , 0.5 , 0.5 ]]) + +As the ``X`` is sorted, one can easily see the banded matrix output. Only the +three middle diagonals are non-zero for ``degree=2``. The higher the degree, +the more overlapping of the splines. + +Interestingly, a :class:`SplineTransformer` of ``degree=0`` is the same as +:class:`~sklearn.preprocessing.KBinsDiscretizer` with ``encode='onehot-dense`` +and ``n_bins = n_knots - 1`` if ``knots = strategy``. + +.. topic:: Examples: + + * :ref:`sphx_glr_auto_examples_linear_model_plot_polynomial_interpolation.py` + +.. topic:: References: -Note that polynomial features are used implicitly in `kernel methods <https://en.wikipedia.org/wiki/Kernel_method>`_ (e.g., :class:`~sklearn.svm.SVC`, :class:`~sklearn.decomposition.KernelPCA`) when using polynomial :ref:`svm_kernels`. + * Eilers, P., & Marx, B. (1996). Flexible Smoothing with B-splines and + Penalties. Statist. Sci. 11 (1996), no. 2, 89--121. + `doi:10.1214/ss/1038425655 <https://doi.org/10.1214/ss/1038425655>`_ -See :ref:`sphx_glr_auto_examples_linear_model_plot_polynomial_interpolation.py` for Ridge regression using created polynomial features. + * Perperoglou, A., Sauerbrei, W., Abrahamowicz, M. et al. A review of + spline function procedures in R. BMC Med Res Methodol 19, 46 (2019). + `doi:10.1186/s12874-019-0666-3 + <https://doi.org/10.1186/s12874-019-0666-3>`_ .. _function_transformer: diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index 652eba896903b..177dab23b3e62 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -110,6 +110,15 @@ Changelog Use ``var_`` instead. :pr:`18842` by :user:`Hong Shao Yang <hongshaoyang>`. +:mod:`sklearn.preprocessing` +............................ + +- |Feature| The new :class:`preprocessing.SplineTransformer` is a feature + preprocessing tool for the generation of B-splines, parametrized by the + polynomial ``degree`` of the splines, number of knots ``n_knots`` and knot + positioning strategy ``knots``. + :pr:`18368` by :user:`Christian Lorentzen <lorentzenchr>`. + :mod:`sklearn.tree` ................... diff --git a/examples/linear_model/plot_polynomial_interpolation.py b/examples/linear_model/plot_polynomial_interpolation.py index 6f2face73c83e..cfa684ffd79ca 100644 --- a/examples/linear_model/plot_polynomial_interpolation.py +++ b/examples/linear_model/plot_polynomial_interpolation.py @@ -1,72 +1,147 @@ -#!/usr/bin/env python """ -======================== -Polynomial interpolation -======================== - -This example demonstrates how to approximate a function with a polynomial of -degree n_degree by using ridge regression. Concretely, from n_samples 1d -points, it suffices to build the Vandermonde matrix, which is n_samples x -n_degree+1 and has the following form: - -[[1, x_1, x_1 ** 2, x_1 ** 3, ...], - [1, x_2, x_2 ** 2, x_2 ** 3, ...], - ...] - -Intuitively, this matrix can be interpreted as a matrix of pseudo features (the -points raised to some power). The matrix is akin to (but different from) the -matrix induced by a polynomial kernel. - -This example shows that you can do non-linear regression with a linear model, -using a pipeline to add non-linear features. Kernel methods extend this idea -and can induce very high (even infinite) dimensional feature spaces. +=================================== +Polynomial and Spline interpolation +=================================== + +This example demonstrates how to approximate a function with polynomials up to +degree ``degree`` by using ridge regression. We show two different ways given +``n_samples`` of 1d points ``x_i``: + +- :class:`~sklearn.preprocessing.PolynomialFeatures` generates all monomials + up to ``degree``. This gives us the so called Vandermonde matrix with + ``n_samples`` rows and ``degree + 1`` columns:: + + [[1, x_0, x_0 ** 2, x_0 ** 3, ..., x_0 ** degree], + [1, x_1, x_1 ** 2, x_1 ** 3, ..., x_1 ** degree], + ...] + + Intuitively, this matrix can be interpreted as a matrix of pseudo features + (the points raised to some power). The matrix is akin to (but different from) + the matrix induced by a polynomial kernel. + +- :class:`~sklearn.preprocessing.SplineTransformer` generates B-spline basis + functions. A basis function of a B-spline is a piece-wise polynomial function + of degree ``degree`` that is non-zero only between ``degree+1`` consecutive + knots. Given ``n_knots`` number of knots, this results in matrix of + ``n_samples`` rows and ``n_knots + degree - 1`` columns:: + + [[basis_1(x_0), basis_2(x_0), ...], + [basis_1(x_1), basis_2(x_1), ...], + ...] + +This example shows that these two transformers are well suited to model +non-linear effects with a linear model, using a pipeline to add non-linear +features. Kernel methods extend this idea and can induce very high (even +infinite) dimensional feature spaces. """ print(__doc__) # Author: Mathieu Blondel # Jake Vanderplas +# Christian Lorentzen # License: BSD 3 clause import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import Ridge -from sklearn.preprocessing import PolynomialFeatures +from sklearn.preprocessing import PolynomialFeatures, SplineTransformer from sklearn.pipeline import make_pipeline +# %% +# We start by defining a function that we intent to approximate and prepare +# plotting it. + def f(x): - """ function to approximate by polynomial interpolation""" + """Function to be approximated by polynomial interpolation.""" return x * np.sin(x) -# generate points used to plot -x_plot = np.linspace(0, 10, 100) +# whole range we want to plot +x_plot = np.linspace(-1, 11, 100) + +# %% +# To make it interesting, we only give a small subset of points to train on. -# generate points and keep a subset of them -x = np.linspace(0, 10, 100) +x_train = np.linspace(0, 10, 100) rng = np.random.RandomState(0) -rng.shuffle(x) -x = np.sort(x[:20]) -y = f(x) +x_train = np.sort(rng.choice(x_train, size=20, replace=False)) +y_train = f(x_train) -# create matrix versions of these arrays -X = x[:, np.newaxis] +# create 2D-array versions of these arrays to feed to transformers +X_train = x_train[:, np.newaxis] X_plot = x_plot[:, np.newaxis] -colors = ['teal', 'yellowgreen', 'gold'] -lw = 2 -plt.plot(x_plot, f(x_plot), color='cornflowerblue', linewidth=lw, - label="ground truth") -plt.scatter(x, y, color='navy', s=30, marker='o', label="training points") +# %% +# Now we are ready to create polynomial features and splines, fit on the +# training points and show how well they interpolate. -for count, degree in enumerate([3, 4, 5]): - model = make_pipeline(PolynomialFeatures(degree), Ridge()) - model.fit(X, y) +# plot function +lw = 2 +fig, ax = plt.subplots() +ax.set_prop_cycle(color=[ + "black", "teal", "yellowgreen", "gold", "darkorange", "tomato" +]) +ax.plot(x_plot, f(x_plot), linewidth=lw, label="ground truth") + +# plot training points +ax.scatter(x_train, y_train, label="training points") + +# polynomial features +for degree in [3, 4, 5]: + model = make_pipeline(PolynomialFeatures(degree), Ridge(alpha=1e-3)) + model.fit(X_train, y_train) y_plot = model.predict(X_plot) - plt.plot(x_plot, y_plot, color=colors[count], linewidth=lw, - label="degree %d" % degree) + ax.plot(x_plot, y_plot, label=f"degree {degree}") -plt.legend(loc='lower left') +# B-spline with 4 + 3 - 1 = 6 basis functions +model = make_pipeline(SplineTransformer(n_knots=4, degree=3), + Ridge(alpha=1e-3)) +model.fit(X_train, y_train) +y_plot = model.predict(X_plot) +ax.plot(x_plot, y_plot, label="B-spline") +ax.legend(loc='lower center') +ax.set_ylim(-20, 10) plt.show() + +# %% +# This shows nicely that higher degree polynomials can fit the data better. But +# at the same time, too high powers can show unwanted oscillatory behaviour +# and are particularly dangerous for extrapolation beyond the range of fitted +# data. This is an advantage of B-splines. They usually fit the data as well as +# polynomials and show very nice and smooth behaviour. They have also good +# options to control the extrapolation, which defaults to continue with a +# constant. Note that most often, you would rather increase the number of knots +# but keep ``degree=3``. +# +# In order to give more insights into the generated feature bases, we plot all +# columns of both transformers separately. + +fig, axes = plt.subplots(ncols=2, figsize=(16, 5)) +pft = PolynomialFeatures(degree=3).fit(X_train) +axes[0].plot(x_plot, pft.transform(X_plot)) +axes[0].legend(axes[0].lines, [f"degree {n}" for n in range(4)]) +axes[0].set_title("PolynomialFeatures") + +splt = SplineTransformer(n_knots=4, degree=3).fit(X_train) +axes[1].plot(x_plot, splt.transform(X_plot)) +axes[1].legend(axes[1].lines, [f"spline {n}" for n in range(4)]) +axes[1].set_title("SplineTransformer") + +# plot knots of spline +knots = splt.bsplines_[0].t +axes[1].vlines(knots[3:-3], ymin=0, ymax=0.8, linestyles='dashed') +plt.show() + +# %% +# In the left plot, we recognize the lines corresponding to simple monomials +# from ``x**0`` to ``x**3``. In the right figure, we see the four B-spline +# basis functions of ``degree=3`` and also the four knot positions that were +# chosen during ``fit``. Note that there are ``degree`` number of additional +# knots each to the left and to the right of the fitted interval. These are +# there for technical reasons, so we refrain from showing them. Every basis +# function has local support and is continued as a constant beyond the fitted +# range. This extrapolating behaviour could be changed by the argument +# ``extrapolation``. diff --git a/sklearn/preprocessing/__init__.py b/sklearn/preprocessing/__init__.py index d048b30e1f3d0..076b9e85e1150 100644 --- a/sklearn/preprocessing/__init__.py +++ b/sklearn/preprocessing/__init__.py @@ -35,6 +35,8 @@ from ._discretization import KBinsDiscretizer +from ._polynomial import SplineTransformer + __all__ = [ 'Binarizer', @@ -52,6 +54,7 @@ 'OrdinalEncoder', 'PowerTransformer', 'RobustScaler', + 'SplineTransformer', 'StandardScaler', 'add_dummy_feature', 'PolynomialFeatures', diff --git a/sklearn/preprocessing/_data.py b/sklearn/preprocessing/_data.py index 3921b898c072d..5814875e04bff 100644 --- a/sklearn/preprocessing/_data.py +++ b/sklearn/preprocessing/_data.py @@ -1620,6 +1620,11 @@ class PolynomialFeatures(TransformerMixin, BaseEstimator): features is computed by iterating over all suitably sized combinations of input features. + See Also + -------- + SplineTransformer : Transformer that generates univariate B-spline bases + for features + Notes ----- Be aware that the number of features in the output array scales @@ -1711,7 +1716,7 @@ def fit(self, X, y=None): return self def transform(self, X): - """Transform data to polynomial features + """Transform data to polynomial features. Parameters ---------- diff --git a/sklearn/preprocessing/_polynomial.py b/sklearn/preprocessing/_polynomial.py new file mode 100644 index 0000000000000..47ab90be2ebcd --- /dev/null +++ b/sklearn/preprocessing/_polynomial.py @@ -0,0 +1,429 @@ +""" +This file contains preprocessing tools based on polynomials. +""" +import numbers + +import numpy as np +from scipy.interpolate import BSpline + +from ..base import BaseEstimator, TransformerMixin +from ..utils import check_array +from ..utils.fixes import linspace +from ..utils.validation import check_is_fitted, FLOAT_DTYPES + + +__all__ = [ + "SplineTransformer", +] + + +# TODO: +# - sparse support (either scipy or own cython solution)? +# - extrapolation (cyclic) +class SplineTransformer(TransformerMixin, BaseEstimator): + """Generate univariate B-spline bases for features. + + Generate a new feature matrix consisting of + `n_splines=n_knots + degree - 1` spline basis functions (B-splines) of + polynomial order=`degree` for each feature. + + Read more in the :ref:`User Guide <spline_transformer>`. + + .. versionadded:: 1.0 + + Parameters + ---------- + n_knots : int, default=5 + Number of knots of the splines if `knots` equals one of + {'uniform', 'quantile'}. Must be larger or equal 2. + + degree : int, default=3 + The polynomial degree of the spline basis. Must be a non-negative + integer. + + knots : {'uniform', 'quantile'} or array-like of shape \ + (n_knots, n_features), default='uniform' + Set knot positions such that first knot <= features <= last knot. + + - If 'uniform', `n_knots` number of knots are distributed uniformly + from min to max values of the features. + - If 'quantile', they are distributed uniformly along the quantiles of + the features. + - If an array-like is given, it directly specifies the sorted knot + positions including the boundary knots. Note that, internally, + `degree` number of knots are added before the first knot, the same + after the last knot. + + extrapolation : {'error', 'constant', 'linear', 'continue'}, \ + default='constant' + If 'error', values outside the min and max values of the training + features raises a `ValueError`. If 'constant', the value of the + splines at minimum and maximum value of the features is used as + constant extrapolation. If 'linear', a linear extrapolation is used. + If 'continue', the splines are extrapolated as is, i.e. option + `extrapolate=True` in :class:`scipy.interpolate.BSpline`. + + include_bias : bool, default=True + If True (default), then the last spline element inside the data range + of a feature is dropped. As B-splines sum to one over the spline basis + functions for each data point, they implicitly include a bias term, + i.e. a column of ones. It acts as an intercept term in a linear models. + + order : {'C', 'F'}, default='C' + Order of output array. 'F' order is faster to compute, but may slow + down subsequent estimators. + + Attributes + ---------- + bsplines_ : list of shape (n_features,) + List of BSplines objects, one for each feature. + + n_features_in_ : int + The total number of input features. + + n_features_out_ : int + The total number of output features, which is computed as + `n_features * n_splines`, where `n_splines` is + the number of bases elements of the B-splines, `n_knots + degree - 1`. + If `include_bias=False`, then it is only + `n_features * (n_splines - 1)`. + + See Also + -------- + KBinsDiscretizer : Transformer that bins continuous data into intervals. + + PolynomialFeatures : Transformer that generates polynomial and interaction + features. + + Notes + ----- + High degrees and a high number of knots can cause overfitting. + + See :ref:`examples/linear_model/plot_polynomial_interpolation.py + <sphx_glr_auto_examples_linear_model_plot_polynomial_interpolation.py>`. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.preprocessing import SplineTransformer + >>> X = np.arange(6).reshape(6, 1) + >>> spline = SplineTransformer(degree=2, n_knots=3) + >>> spline.fit_transform(X) + array([[0.5 , 0.5 , 0. , 0. ], + [0.18, 0.74, 0.08, 0. ], + [0.02, 0.66, 0.32, 0. ], + [0. , 0.32, 0.66, 0.02], + [0. , 0.08, 0.74, 0.18], + [0. , 0. , 0.5 , 0.5 ]]) + """ + + def __init__( + self, + n_knots=5, + degree=3, + *, + knots="uniform", + extrapolation="constant", + include_bias=True, + order="C", + ): + self.n_knots = n_knots + self.degree = degree + self.knots = knots + self.extrapolation = extrapolation + self.include_bias = include_bias + self.order = order + + @staticmethod + def _get_base_knot_positions(X, n_knots=10, knots="uniform"): + """Calculate base knot positions. + + Base knots such that first knot <= feature <= last knot. For the + B-spline construction with scipy.interpolate.BSpline, 2*degree knots + beyond the base interval are added. + + Returns + ------- + knots : ndarray of shape (n_knots, n_features), dtype=np.float64 + Knot positions (points) of base interval. + """ + if knots == "quantile": + knots = np.percentile( + X, + 100 + * np.linspace(start=0, stop=1, num=n_knots, dtype=np.float64), + axis=0, + ) + else: + # knots == 'uniform': + # Note that the variable `knots` has already been validated and + # `else` is therefore safe. + x_min = np.amin(X, axis=0) + x_max = np.amax(X, axis=0) + knots = linspace( + start=x_min, + stop=x_max, + num=n_knots, + endpoint=True, + dtype=np.float64, + ) + + return knots + + def get_feature_names(self, input_features=None): + """Return feature names for output features. + + Parameters + ---------- + input_features : list of str of shape (n_features,), default=None + String names for input features if available. By default, + "x0", "x1", ... "xn_features" is used. + + Returns + ------- + output_feature_names : list of str of shape (n_output_features,) + """ + n_splines = self.bsplines_[0].c.shape[0] + if input_features is None: + input_features = ["x%d" % i for i in range(self.n_features_in_)] + feature_names = [] + for i in range(self.n_features_in_): + for j in range(n_splines - 1 + self.include_bias): + feature_names.append(f"{input_features[i]}_sp_{j}") + return feature_names + + def fit(self, X, y=None): + """Compute knot positions of splines. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + The data. + + y : None + Ignored. + + Returns + ------- + self : object + Fitted transformer. + """ + X = self._validate_data( + X, + reset=True, + accept_sparse=False, + ensure_min_samples=2, + ensure_2d=True, + ) + n_samples, n_features = X.shape + + if not ( + isinstance(self.degree, numbers.Integral) and self.degree >= 0 + ): + raise ValueError("degree must be a non-negative integer.") + + if not ( + isinstance(self.n_knots, numbers.Integral) and self.n_knots >= 2 + ): + raise ValueError("n_knots must be a positive integer >= 2.") + + if isinstance(self.knots, str) and self.knots in [ + "uniform", + "quantile", + ]: + base_knots = self._get_base_knot_positions( + X, n_knots=self.n_knots, knots=self.knots + ) + else: + base_knots = check_array(self.knots) + if base_knots.shape[0] < 2: + raise ValueError( + "Number of knots, knots.shape[0], must be >= " "2." + ) + elif base_knots.shape[1] != n_features: + raise ValueError("knots.shape[1] == n_features is violated.") + elif not np.all(np.diff(base_knots, axis=0) > 0): + raise ValueError("knots must be sorted without duplicates.") + + if self.extrapolation not in ( + "error", + "constant", + "linear", + "continue", + ): + raise ValueError( + "extrapolation must be one of 'error', " + "'constant', 'linear' or 'continue'." + ) + + if not isinstance(self.include_bias, (bool, np.bool_)): + raise ValueError("include_bias must be bool.") + + # number of knots for base interval + n_knots = base_knots.shape[0] + # number of splines basis functions + n_splines = n_knots + self.degree - 1 + degree = self.degree + n_out = n_features * n_splines + # We have to add degree number of knots below, and degree number knots + # above the base knots in order to make the spline basis complete. + # Eilers & Marx in "Flexible smoothing with B-splines and penalties" + # https://doi.org/10.1214/ss/1038425655 advice against repeating first + # and last knot several times, which would have inferior behaviour at + # boundaries if combined with a penalty (hence P-Spline). We follow + # this advice even if our splines are unpenalized. + # Meaning we do not: + # knots = np.r_[np.tile(base_knots.min(axis=0), reps=[degree, 1]), + # base_knots, + # np.tile(base_knots.max(axis=0), reps=[degree, 1]) + # ] + # Instead, we reuse the distance of the 2 fist/last knots. + dist_min = base_knots[1] - base_knots[0] + dist_max = base_knots[-1] - base_knots[-2] + knots = np.r_[ + linspace( + base_knots[0] - degree * dist_min, + base_knots[0] - dist_min, + num=degree, + ), + base_knots, + linspace( + base_knots[-1] + dist_max, + base_knots[-1] + degree * dist_max, + num=degree, + ), + ] + + # With a diagonal coefficient matrix, we get back the spline basis + # elements, i.e. the design matrix of the spline. + # Note, BSpline appreciates C-contiguous float64 arrays as c=coef. + coef = np.eye(n_knots + self.degree - 1, dtype=np.float64) + extrapolate = self.extrapolation == "continue" + bsplines = [ + BSpline.construct_fast( + knots[:, i], coef, self.degree, extrapolate=extrapolate + ) + for i in range(n_features) + ] + self.bsplines_ = bsplines + + self.n_features_out_ = n_out - n_features * self.include_bias + return self + + def transform(self, X): + """Transform each feature data to B-splines. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + The data to transform. + + Returns + ------- + XBS : ndarray of shape (n_samples, n_features * n_splines) + The matrix of features, where n_splines is the number of bases + elements of the B-splines, n_knots + degree - 1. + """ + check_is_fitted(self) + + X = self._validate_data( + X, reset=False, accept_sparse=False, ensure_2d=True + ) + + n_samples, n_features = X.shape + n_splines = self.bsplines_[0].c.shape[0] + degree = self.degree + + # Note that scipy BSpline returns float64 arrays and converts input + # x=X[:, i] to c-contiguous float64. + n_out = self.n_features_out_ + n_features * self.include_bias + if X.dtype in FLOAT_DTYPES: + dtype = X.dtype + else: + dtype = np.float64 + XBS = np.zeros((n_samples, n_out), dtype=dtype, order=self.order) + + for i in range(n_features): + spl = self.bsplines_[i] + + if self.extrapolation in ("continue", "error"): + XBS[:, (i * n_splines):((i + 1) * n_splines)] = spl(X[:, i]) + else: + xmin = spl.t[degree] + xmax = spl.t[-degree - 1] + mask = (xmin <= X[:, i]) & (X[:, i] <= xmax) + XBS[mask, (i * n_splines):((i + 1) * n_splines)] = spl( + X[mask, i] + ) + + # Note for extrapolation: + # 'continue' is already returned as is by scipy BSplines + if self.extrapolation == "error": + # BSpline with extrapolate=False does not raise an error, but + # output np.nan. + if np.any( + np.isnan(XBS[:, (i * n_splines):((i + 1) * n_splines)]) + ): + raise ValueError( + "X contains values beyond the limits of the knots." + ) + elif self.extrapolation == "constant": + # Set all values beyond xmin and xmax to the value of the + # spline basis functions at those two positions. + # Only the first degree and last degree number of splines + # have non-zero values at the boundaries. + + # spline values at boundaries + f_min = spl(xmin) + f_max = spl(xmax) + mask = X[:, i] < xmin + if np.any(mask): + XBS[ + mask, (i * n_splines):(i * n_splines + degree) + ] = f_min[:degree] + + mask = X[:, i] > xmax + if np.any(mask): + XBS[ + mask, + ((i + 1) * n_splines - degree):((i + 1) * n_splines), + ] = f_max[-degree:] + elif self.extrapolation == "linear": + # Continue the degree first and degree last spline bases + # linearly beyond the boundaries, with slope = derivative at + # the boundary. + # Note that all others have derivative = value = 0 at the + # boundaries. + + # spline values at boundaries + f_min, f_max = spl(xmin), spl(xmax) + # spline derivatives = slopes at boundaries + fp_min, fp_max = spl(xmin, nu=1), spl(xmax, nu=1) + # Compute the linear continuation. + if degree <= 1: + # For degree=1, the derivative of 2nd spline is not zero at + # boundary. For degree=0 it is the same as 'constant'. + degree += 1 + for j in range(degree): + mask = X[:, i] < xmin + if np.any(mask): + XBS[mask, i * n_splines + j] = ( + f_min[j] + (X[mask, i] - xmin) * fp_min[j] + ) + + mask = X[:, i] > xmax + if np.any(mask): + k = n_splines - 1 - j + XBS[mask, i * n_splines + k] = ( + f_max[k] + (X[mask, i] - xmax) * fp_max[k] + ) + + if self.include_bias: + return XBS + else: + # We throw away one spline basis per feature. + # We chose the last one. + indices = [ + j for j in range(XBS.shape[1]) if (j + 1) % n_splines != 0 + ] + return XBS[:, indices] diff --git a/sklearn/utils/fixes.py b/sklearn/utils/fixes.py index 49519ed55c82c..593e0eb332a99 100644 --- a/sklearn/utils/fixes.py +++ b/sklearn/utils/fixes.py @@ -220,3 +220,51 @@ def __init__(self, function): def __call__(self, *args, **kwargs): with config_context(**self.config): return self.function(*args, **kwargs) + + +def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, + axis=0): + """Implements a simplified linspace function as of numpy verion >= 1.16. + + As of numpy 1.16, the arguments start and stop can be array-like and + there is an optional argument `axis`. + For simplicity, we only allow 1d array-like to be passed to start and stop. + See: https://github.com/numpy/numpy/pull/12388 and numpy 1.16 release + notes about start and stop arrays for linspace logspace and geomspace. + + Returns + ------- + out : ndarray of shape (num, n_start) or (num,) + The output array with `n_start=start.shape[0]` columns. + """ + if np_version < parse_version('1.16'): + start = np.asanyarray(start) * 1.0 + stop = np.asanyarray(stop) * 1.0 + dt = np.result_type(start, stop, float(num)) + if dtype is None: + dtype = dt + + if start.ndim == 0 == stop.ndim: + return np.linspace(start=start, stop=stop, num=num, + endpoint=endpoint, retstep=retstep, dtype=dtype) + + if start.ndim != 1 or stop.ndim != 1 or start.shape != stop.shape: + raise ValueError("start and stop must be 1d array-like of same" + " shape.") + n_start = start.shape[0] + out = np.empty((num, n_start), dtype=dtype) + step = np.empty(n_start, dtype=np.float) + for i in range(n_start): + out[:, i], step[i] = np.linspace(start=start[i], stop=stop[i], + num=num, endpoint=endpoint, + retstep=True, dtype=dtype) + if axis != 0: + out = np.moveaxis(out, 0, axis) + + if retstep: + return out, step + else: + return out + else: + return np.linspace(start=start, stop=stop, num=num, endpoint=endpoint, + retstep=retstep, dtype=dtype, axis=axis)
diff --git a/sklearn/preprocessing/tests/test_data.py b/sklearn/preprocessing/tests/test_data.py index b0fbee8db9455..974dad31258eb 100644 --- a/sklearn/preprocessing/tests/test_data.py +++ b/sklearn/preprocessing/tests/test_data.py @@ -28,26 +28,27 @@ from sklearn.utils._testing import _convert_container from sklearn.utils.sparsefuncs import mean_variance_axis +from sklearn.preprocessing import Binarizer +from sklearn.preprocessing import KernelCenterer +from sklearn.preprocessing import Normalizer +from sklearn.preprocessing import normalize +from sklearn.preprocessing import StandardScaler +from sklearn.preprocessing import scale +from sklearn.preprocessing import MinMaxScaler +from sklearn.preprocessing import minmax_scale +from sklearn.preprocessing import QuantileTransformer +from sklearn.preprocessing import quantile_transform +from sklearn.preprocessing import MaxAbsScaler +from sklearn.preprocessing import maxabs_scale +from sklearn.preprocessing import RobustScaler +from sklearn.preprocessing import robust_scale +from sklearn.preprocessing import add_dummy_feature +from sklearn.preprocessing import PolynomialFeatures +from sklearn.preprocessing import PowerTransformer +from sklearn.preprocessing import power_transform from sklearn.preprocessing._data import _handle_zeros_in_scale -from sklearn.preprocessing._data import Binarizer -from sklearn.preprocessing._data import KernelCenterer -from sklearn.preprocessing._data import Normalizer -from sklearn.preprocessing._data import normalize -from sklearn.preprocessing._data import StandardScaler -from sklearn.preprocessing._data import scale -from sklearn.preprocessing._data import MinMaxScaler -from sklearn.preprocessing._data import minmax_scale -from sklearn.preprocessing._data import QuantileTransformer -from sklearn.preprocessing._data import quantile_transform -from sklearn.preprocessing._data import MaxAbsScaler -from sklearn.preprocessing._data import maxabs_scale -from sklearn.preprocessing._data import RobustScaler -from sklearn.preprocessing._data import robust_scale -from sklearn.preprocessing._data import add_dummy_feature -from sklearn.preprocessing._data import PolynomialFeatures -from sklearn.preprocessing._data import PowerTransformer -from sklearn.preprocessing._data import power_transform from sklearn.preprocessing._data import BOUNDS_THRESHOLD + from sklearn.exceptions import NotFittedError from sklearn.base import clone @@ -58,6 +59,7 @@ from sklearn import datasets + iris = datasets.load_iris() # Make some data to be used many times @@ -148,6 +150,7 @@ def test_polynomial_feature_names(): def test_polynomial_feature_array_order(): + """Test that output array has the given order.""" X = np.arange(10).reshape(5, 2) def is_c_contiguous(a): @@ -1591,15 +1594,13 @@ def test_quantile_transform_bounds(): transformer = QuantileTransformer() transformer.fit(X) assert (transformer.transform([[-10]]) == - transformer.transform([[np.min(X)]])) + transformer.transform([[np.min(X)]])) assert (transformer.transform([[10]]) == - transformer.transform([[np.max(X)]])) + transformer.transform([[np.max(X)]])) assert (transformer.inverse_transform([[-10]]) == - transformer.inverse_transform( - [[np.min(transformer.references_)]])) + transformer.inverse_transform([[np.min(transformer.references_)]])) assert (transformer.inverse_transform([[10]]) == - transformer.inverse_transform( - [[np.max(transformer.references_)]])) + transformer.inverse_transform([[np.max(transformer.references_)]])) def test_quantile_transform_and_inverse(): @@ -1904,9 +1905,9 @@ def test_maxabs_scaler_partial_fit(): scaler_incr_csc.max_abs_) assert scaler_batch.n_samples_seen_ == scaler_incr.n_samples_seen_ assert (scaler_batch.n_samples_seen_ == - scaler_incr_csr.n_samples_seen_) + scaler_incr_csr.n_samples_seen_) assert (scaler_batch.n_samples_seen_ == - scaler_incr_csc.n_samples_seen_) + scaler_incr_csc.n_samples_seen_) assert_array_almost_equal(scaler_batch.scale_, scaler_incr.scale_) assert_array_almost_equal(scaler_batch.scale_, scaler_incr_csr.scale_) assert_array_almost_equal(scaler_batch.scale_, scaler_incr_csc.scale_) diff --git a/sklearn/preprocessing/tests/test_polynomial.py b/sklearn/preprocessing/tests/test_polynomial.py new file mode 100644 index 0000000000000..9dd65c44d8bba --- /dev/null +++ b/sklearn/preprocessing/tests/test_polynomial.py @@ -0,0 +1,245 @@ +import numpy as np +from numpy.testing import assert_allclose, assert_array_equal +import pytest + +from sklearn.linear_model import LinearRegression +from sklearn.pipeline import Pipeline +from sklearn.preprocessing import KBinsDiscretizer, SplineTransformer + + +# TODO: add PolynomialFeatures if it moves to _polynomial.py [email protected]("est", (SplineTransformer,)) +def test_polynomial_and_spline_array_order(est): + """Test that output array has the given order.""" + X = np.arange(10).reshape(5, 2) + + def is_c_contiguous(a): + return np.isfortran(a.T) + + assert is_c_contiguous(est().fit_transform(X)) + assert is_c_contiguous(est(order="C").fit_transform(X)) + assert np.isfortran(est(order="F").fit_transform(X)) + + [email protected]( + "params, err_msg", + [ + ({"degree": -1}, "degree must be a non-negative integer."), + ({"degree": 2.5}, "degree must be a non-negative integer."), + ({"degree": "string"}, "degree must be a non-negative integer."), + ({"n_knots": 1}, "n_knots must be a positive integer >= 2."), + ({"n_knots": 1}, "n_knots must be a positive integer >= 2."), + ({"n_knots": 2.5}, "n_knots must be a positive integer >= 2."), + ({"n_knots": "string"}, "n_knots must be a positive integer >= 2."), + ({"knots": "string"}, "Expected 2D array, got scalar array instead:"), + ({"knots": [1, 2]}, "Expected 2D array, got 1D array instead:"), + ( + {"knots": [[1]]}, + r"Number of knots, knots.shape\[0\], must be >= 2.", + ), + ( + {"knots": [[1, 5], [2, 6]]}, + r"knots.shape\[1\] == n_features is violated.", + ), + ( + {"knots": [[1], [1], [2]]}, + "knots must be sorted without duplicates.", + ), + ({"knots": [[2], [1]]}, "knots must be sorted without duplicates."), + ( + {"extrapolation": None}, + "extrapolation must be one of 'error', 'constant', 'linear' or " + "'continue'.", + ), + ( + {"extrapolation": 1}, + "extrapolation must be one of 'error', 'constant', 'linear' or " + "'continue'.", + ), + ( + {"extrapolation": "string"}, + "extrapolation must be one of 'error', 'constant', 'linear' or " + "'continue'.", + ), + ({"include_bias": None}, "include_bias must be bool."), + ({"include_bias": 1}, "include_bias must be bool."), + ({"include_bias": "string"}, "include_bias must be bool."), + ], +) +def test_spline_transformer_input_validation(params, err_msg): + """Test that we raise errors for invalid input in SplineTransformer.""" + X = [[1], [2]] + + with pytest.raises(ValueError, match=err_msg): + SplineTransformer(**params).fit(X) + + +def test_spline_transformer_manual_knot_input(): + """Test that array-like knot positions in SplineTransformer are accepted. + """ + X = np.arange(20).reshape(10, 2) + knots = [[0.5, 1], [1.5, 2], [5, 10]] + st1 = SplineTransformer(degree=3, knots=knots).fit(X) + knots = np.asarray(knots) + st2 = SplineTransformer(degree=3, knots=knots).fit(X) + for i in range(X.shape[1]): + assert_allclose(st1.bsplines_[i].t, st2.bsplines_[i].t) + + +def test_spline_transformer_feature_names(): + """Test that SplineTransformer generates correct features name.""" + X = np.arange(20).reshape(10, 2) + splt = SplineTransformer(n_knots=3, degree=3, include_bias=True).fit(X) + feature_names = splt.get_feature_names() + assert_array_equal( + feature_names, + [ + "x0_sp_0", + "x0_sp_1", + "x0_sp_2", + "x0_sp_3", + "x0_sp_4", + "x1_sp_0", + "x1_sp_1", + "x1_sp_2", + "x1_sp_3", + "x1_sp_4", + ], + ) + + splt = SplineTransformer(n_knots=3, degree=3, include_bias=False).fit(X) + feature_names = splt.get_feature_names(["a", "b"]) + assert_array_equal( + feature_names, + [ + "a_sp_0", + "a_sp_1", + "a_sp_2", + "a_sp_3", + "b_sp_0", + "b_sp_1", + "b_sp_2", + "b_sp_3", + ], + ) + + [email protected]("degree", range(1, 5)) [email protected]("n_knots", range(3, 5)) [email protected]("knots", ["uniform", "quantile"]) +def test_spline_transformer_unity_decomposition(degree, n_knots, knots): + """Test that B-splines are indeed a decomposition of unity. + + Splines basis functions must sum up to 1 per row, if we stay in between + boundaries. + """ + X = np.linspace(0, 1, 100)[:, None] + # make the boundaries 0 and 1 part of X_train, for sure. + X_train = np.r_[[[0]], X[::2, :], [[1]]] + X_test = X[1::2, :] + splt = SplineTransformer( + n_knots=n_knots, degree=degree, knots=knots, include_bias=True + ) + splt.fit(X_train) + for X in [X_train, X_test]: + assert_allclose(np.sum(splt.transform(X), axis=1), 1) + + [email protected](["bias", "intercept"], [(True, False), (False, True)]) +def test_spline_transformer_linear_regression(bias, intercept): + """Test that B-splines fit a sinusodial curve pretty well.""" + X = np.linspace(0, 10, 100)[:, None] + y = np.sin(X[:, 0]) + 2 # +2 to avoid the value 0 in assert_allclose + pipe = Pipeline( + steps=[ + ( + "spline", + SplineTransformer( + n_knots=15, + degree=3, + include_bias=bias, + extrapolation="constant", + ), + ), + ("ols", LinearRegression(fit_intercept=intercept)), + ] + ) + pipe.fit(X, y) + assert_allclose(pipe.predict(X), y, rtol=1e-3) + + [email protected](["bias", "intercept"], [(True, False), (False, True)]) [email protected]("degree", [1, 2, 3, 4, 5]) +def test_spline_transformer_extrapolation(bias, intercept, degree): + """Test that B-spline extrapolation works correctly.""" + # we use a straight line for that + X = np.linspace(-1, 1, 100)[:, None] + y = X.squeeze() + + # 'constant' + pipe = Pipeline( + [ + [ + "spline", + SplineTransformer( + n_knots=4, + degree=degree, + include_bias=bias, + extrapolation="constant", + ), + ], + ["ols", LinearRegression(fit_intercept=intercept)], + ] + ) + pipe.fit(X, y) + assert_allclose(pipe.predict([[-10], [5]]), [-1, 1]) + + # 'linear' + pipe = Pipeline( + [ + [ + "spline", + SplineTransformer( + n_knots=4, + degree=degree, + include_bias=bias, + extrapolation="linear", + ), + ], + ["ols", LinearRegression(fit_intercept=intercept)], + ] + ) + pipe.fit(X, y) + assert_allclose(pipe.predict([[-10], [5]]), [-10, 5]) + + # 'error' + splt = SplineTransformer( + n_knots=4, degree=degree, include_bias=bias, extrapolation="error" + ) + splt.fit(X) + with pytest.raises(ValueError): + splt.transform([[-10]]) + with pytest.raises(ValueError): + splt.transform([[5]]) + + +def test_spline_transformer_kbindiscretizer(): + """Test that a B-spline of degree=0 is equivalent to KBinsDiscretizer.""" + rng = np.random.RandomState(97531) + X = rng.randn(200).reshape(200, 1) + n_bins = 5 + n_knots = n_bins + 1 + + splt = SplineTransformer( + n_knots=n_knots, degree=0, knots="quantile", include_bias=True + ) + splines = splt.fit_transform(X) + + kbd = KBinsDiscretizer( + n_bins=n_bins, encode="onehot-dense", strategy="quantile" + ) + kbins = kbd.fit_transform(X) + + # Though they should be exactly equal, we test approximately with high + # accuracy. + assert_allclose(splines, kbins, rtol=1e-13) diff --git a/sklearn/utils/tests/test_fixes.py b/sklearn/utils/tests/test_fixes.py index 28824a6acee55..03e11f5bc1a08 100644 --- a/sklearn/utils/tests/test_fixes.py +++ b/sklearn/utils/tests/test_fixes.py @@ -15,6 +15,7 @@ from sklearn.utils.fixes import _object_dtype_isnan from sklearn.utils.fixes import loguniform from sklearn.utils.fixes import MaskedArray +from sklearn.utils.fixes import linspace, parse_version, np_version @pytest.mark.parametrize('joblib_version', ('0.11', '0.12.0')) @@ -89,3 +90,37 @@ def test_loguniform(low, high, base): def test_masked_array_deprecated(): # TODO: remove in 1.0 with pytest.warns(FutureWarning, match='is deprecated'): MaskedArray() + + +def test_linspace(): + """Test that linespace works like np.linespace as of numpy version 1.16.""" + start, stop = 0, 10 + num = 6 + out = linspace(start=start, stop=stop, num=num, endpoint=True) + assert_array_equal(out, np.array([0., 2, 4, 6, 8, 10])) + + start, stop = [0, 100], [10, 1100] + num = 6 + out = linspace(start=start, stop=stop, num=num, endpoint=True) + res = np.c_[[0., 2, 4, 6, 8, 10], + [100, 300, 500, 700, 900, 1100]] + assert_array_equal(out, res) + + out2 = linspace(start=start, stop=stop, num=num, endpoint=True, axis=1) + assert_array_equal(out2, out.T) + + out, step = linspace( + start=start, + stop=stop, + num=num, + endpoint=True, + retstep=True, + ) + assert_array_equal(out, res) + assert_array_equal(step, [2, 200]) + + if np_version < parse_version('1.16'): + with pytest.raises(ValueError): + linspace(start=[0, 1], stop=10) + else: + linspace(start=[0, 1], stop=10)
[ { "path": "doc/modules/classes.rst", "old_path": "a/doc/modules/classes.rst", "new_path": "b/doc/modules/classes.rst", "metadata": "diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst\nindex 84f8097cbbe9d..65d555f978df0 100644\n--- a/doc/modules/classes.rst\n+++ b/doc/modules/classes.rst\n@@ -1414,6 +1414,7 @@ details.\n preprocessing.PowerTransformer\n preprocessing.QuantileTransformer\n preprocessing.RobustScaler\n+ preprocessing.SplineTransformer\n preprocessing.StandardScaler\n \n .. autosummary::\n" }, { "path": "doc/modules/preprocessing.rst", "old_path": "a/doc/modules/preprocessing.rst", "new_path": "b/doc/modules/preprocessing.rst", "metadata": "diff --git a/doc/modules/preprocessing.rst b/doc/modules/preprocessing.rst\nindex 801d9a98ed1f4..a339b4bfae4e2 100644\n--- a/doc/modules/preprocessing.rst\n+++ b/doc/modules/preprocessing.rst\n@@ -624,7 +624,9 @@ of continuous attributes to one with only nominal attributes.\n \n One-hot encoded discretized features can make a model more expressive, while\n maintaining interpretability. For instance, pre-processing with a discretizer\n-can introduce nonlinearity to linear models.\n+can introduce nonlinearity to linear models. For more advanced possibilities,\n+in particular smooth ones, see :ref:`generating_polynomial_features` further\n+below.\n \n K-bins discretization\n ---------------------\n@@ -756,12 +758,24 @@ Imputation of missing values\n \n Tools for imputing missing values are discussed at :ref:`impute`.\n \n-.. _polynomial_features:\n+.. _generating_polynomial_features:\n \n Generating polynomial features\n ==============================\n \n-Often it's useful to add complexity to the model by considering nonlinear features of the input data. A simple and common method to use is polynomial features, which can get features' high-order and interaction terms. It is implemented in :class:`PolynomialFeatures`::\n+Often it's useful to add complexity to a model by considering nonlinear\n+features of the input data. We show two possibilities that are both based on\n+polynomials: The first one uses pure polynomials, the second one uses splines,\n+i.e. piecewise polynomials.\n+\n+.. _polynomial_features:\n+\n+Polynomial features\n+-------------------\n+\n+A simple and common method to use is polynomial features, which can get\n+features' high-order and interaction terms. It is implemented in\n+:class:`PolynomialFeatures`::\n \n >>> import numpy as np\n >>> from sklearn.preprocessing import PolynomialFeatures\n@@ -776,9 +790,11 @@ Often it's useful to add complexity to the model by considering nonlinear featur\n [ 1., 2., 3., 4., 6., 9.],\n [ 1., 4., 5., 16., 20., 25.]])\n \n-The features of X have been transformed from :math:`(X_1, X_2)` to :math:`(1, X_1, X_2, X_1^2, X_1X_2, X_2^2)`.\n+The features of X have been transformed from :math:`(X_1, X_2)` to\n+:math:`(1, X_1, X_2, X_1^2, X_1X_2, X_2^2)`.\n \n-In some cases, only interaction terms among features are required, and it can be gotten with the setting ``interaction_only=True``::\n+In some cases, only interaction terms among features are required, and it can\n+be gotten with the setting ``interaction_only=True``::\n \n >>> X = np.arange(9).reshape(3, 3)\n >>> X\n@@ -791,11 +807,94 @@ In some cases, only interaction terms among features are required, and it can be\n [ 1., 3., 4., 5., 12., 15., 20., 60.],\n [ 1., 6., 7., 8., 42., 48., 56., 336.]])\n \n-The features of X have been transformed from :math:`(X_1, X_2, X_3)` to :math:`(1, X_1, X_2, X_3, X_1X_2, X_1X_3, X_2X_3, X_1X_2X_3)`.\n+The features of X have been transformed from :math:`(X_1, X_2, X_3)` to\n+:math:`(1, X_1, X_2, X_3, X_1X_2, X_1X_3, X_2X_3, X_1X_2X_3)`.\n+\n+Note that polynomial features are used implicitly in `kernel methods\n+<https://en.wikipedia.org/wiki/Kernel_method>`_ (e.g., :class:`~sklearn.svm.SVC`,\n+:class:`~sklearn.decomposition.KernelPCA`) when using polynomial :ref:`svm_kernels`.\n+\n+See :ref:`sphx_glr_auto_examples_linear_model_plot_polynomial_interpolation.py`\n+for Ridge regression using created polynomial features.\n+\n+.. _spline_transformer:\n+\n+Spline transformer\n+------------------\n+\n+Another way to add nonlinear terms instead of pure polynomials of features is\n+to generate spline basis functions for each feature with the\n+:class:`SplineTransformer`. Splines are piecewise polynomials, parametrized by\n+their polynomial degree and the positions of the knots. The\n+:class:`SplineTransformer` implements a B-spline basis, cf. the references\n+below.\n+\n+.. note::\n+\n+ The :class:`SplineTransformer` treats each feature separately, i.e. it\n+ won't give you interaction terms.\n+\n+Some of the advantages of splines over polynomials are:\n+\n+ - B-splines are very flexible and robust if you keep a fixed low degree,\n+ usually 3, and parsimoniously adapt the number of knots. Polynomials\n+ would need a higher degree, which leads to the next point.\n+ - B-splines do not have oscillatory behaviour at the boundaries as have\n+ polynomials (the higher the degree, the worse). This is known as `Runge's\n+ phenomenon <https://en.wikipedia.org/wiki/Runge%27s_phenomenon>`_.\n+ - B-splines provide good options for extrapolation beyond the boundaries,\n+ i.e. beyond the range of fitted values. Have a look at the option\n+ ``extrapolation``.\n+ - B-splines generate a feature matrix with a banded structure. For a single\n+ feature, every row contains only ``degree + 1`` non-zero elements, which\n+ occur consecutively and are even positive. This results in a matrix with\n+ good numerical properties, e.g. a low condition number, in sharp contrast\n+ to a matrix of polynomials, which goes under the name\n+ `Vandermonde matrix <https://en.wikipedia.org/wiki/Vandermonde_matrix>`_.\n+ A low condition number is important for stable algorithms of linear\n+ models.\n+\n+The following code snippet shows splines in action::\n+\n+ >>> import numpy as np\n+ >>> from sklearn.preprocessing import SplineTransformer\n+ >>> X = np.arange(5).reshape(5, 1)\n+ >>> X\n+ array([[0],\n+ [1],\n+ [2],\n+ [3],\n+ [4]])\n+ >>> spline = SplineTransformer(degree=2, n_knots=3)\n+ >>> spline.fit_transform(X)\n+ array([[0.5 , 0.5 , 0. , 0. ],\n+ [0.125, 0.75 , 0.125, 0. ],\n+ [0. , 0.5 , 0.5 , 0. ],\n+ [0. , 0.125, 0.75 , 0.125],\n+ [0. , 0. , 0.5 , 0.5 ]])\n+\n+As the ``X`` is sorted, one can easily see the banded matrix output. Only the\n+three middle diagonals are non-zero for ``degree=2``. The higher the degree,\n+the more overlapping of the splines.\n+\n+Interestingly, a :class:`SplineTransformer` of ``degree=0`` is the same as\n+:class:`~sklearn.preprocessing.KBinsDiscretizer` with ``encode='onehot-dense``\n+and ``n_bins = n_knots - 1`` if ``knots = strategy``.\n+\n+.. topic:: Examples:\n+\n+ * :ref:`sphx_glr_auto_examples_linear_model_plot_polynomial_interpolation.py`\n+\n+.. topic:: References:\n \n-Note that polynomial features are used implicitly in `kernel methods <https://en.wikipedia.org/wiki/Kernel_method>`_ (e.g., :class:`~sklearn.svm.SVC`, :class:`~sklearn.decomposition.KernelPCA`) when using polynomial :ref:`svm_kernels`.\n+ * Eilers, P., & Marx, B. (1996). Flexible Smoothing with B-splines and\n+ Penalties. Statist. Sci. 11 (1996), no. 2, 89--121.\n+ `doi:10.1214/ss/1038425655 <https://doi.org/10.1214/ss/1038425655>`_\n \n-See :ref:`sphx_glr_auto_examples_linear_model_plot_polynomial_interpolation.py` for Ridge regression using created polynomial features.\n+ * Perperoglou, A., Sauerbrei, W., Abrahamowicz, M. et al. A review of\n+ spline function procedures in R. BMC Med Res Methodol 19, 46 (2019).\n+ `doi:10.1186/s12874-019-0666-3\n+ <https://doi.org/10.1186/s12874-019-0666-3>`_\n \n .. _function_transformer:\n \n" }, { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 652eba896903b..177dab23b3e62 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -110,6 +110,15 @@ Changelog\n Use ``var_`` instead.\n :pr:`18842` by :user:`Hong Shao Yang <hongshaoyang>`.\n \n+:mod:`sklearn.preprocessing`\n+............................\n+\n+- |Feature| The new :class:`preprocessing.SplineTransformer` is a feature\n+ preprocessing tool for the generation of B-splines, parametrized by the\n+ polynomial ``degree`` of the splines, number of knots ``n_knots`` and knot\n+ positioning strategy ``knots``.\n+ :pr:`18368` by :user:`Christian Lorentzen <lorentzenchr>`.\n+\n :mod:`sklearn.tree`\n ...................\n \n" } ]
1.00
8c6a045e46abe94e43a971d4f8042728addfd6a7
[ "sklearn/preprocessing/tests/test_data.py::test_polynomial_features_csr_X_dim_edges[2-2-True]", "sklearn/preprocessing/tests/test_data.py::test_polynomial_features_csr_X_floats[3-False-False-float64]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_equivalence_dense_sparse[positive-0]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_equivalence_dense_sparse[None-1]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_dtype[False-csr_matrix]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_sparse_partial_fit_finite_variance[X_21]", "sklearn/preprocessing/tests/test_data.py::test_center_kernel", "sklearn/preprocessing/tests/test_data.py::test_polynomial_features_csr_X_zero_row[0-3-False]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_attributes[X0-True-False]", "sklearn/preprocessing/tests/test_data.py::test_polynomial_features_csr_X_dim_edges[3-3-False]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_sample_weight[array-Xw1-X1-sample_weight1]", "sklearn/preprocessing/tests/test_data.py::test_optimization_power_transformer[yeo-johnson-1.0]", "sklearn/preprocessing/tests/test_data.py::test_polynomial_features_csr_X[3-False-False-float64]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_attributes[X0-False-False]", "sklearn/preprocessing/tests/test_data.py::test_partial_fit_sparse_input[True]", "sklearn/preprocessing/tests/test_data.py::test_scaler_n_samples_seen_with_nan[csc_matrix-False-False]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_equivalence_dense_sparse[negative-0.1]", "sklearn/preprocessing/tests/test_data.py::test_scaler_without_copy", "sklearn/preprocessing/tests/test_data.py::test_polynomial_features_csc_X[2-True-False-float64]", "sklearn/preprocessing/tests/test_data.py::test_polynomial_features_csr_X_zero_row[2-3-True]", "sklearn/preprocessing/tests/test_data.py::test_polynomial_features_csr_X_zero_row[1-3-True]", "sklearn/preprocessing/tests/test_data.py::test_scaler_n_samples_seen_with_nan[csr_matrix-True-False]", "sklearn/preprocessing/tests/test_data.py::test_quantile_transformer_sorted_quantiles[array]", "sklearn/preprocessing/tests/test_data.py::test_scaler_n_samples_seen_with_nan[asarray-False-False]", "sklearn/preprocessing/tests/test_data.py::test_quantile_transform_sparse_toy", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_partial_fit_numerical_stability", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_method_exception", "sklearn/preprocessing/tests/test_data.py::test_scaler_float16_overflow", "sklearn/preprocessing/tests/test_data.py::test_yeo_johnson_darwin_example", "sklearn/preprocessing/tests/test_data.py::test_polynomial_features_csr_X[2-True-False-float32]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_iris", "sklearn/preprocessing/tests/test_data.py::test_pairwise_deprecated", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_equivalence_dense_sparse[positive-0.1]", "sklearn/preprocessing/tests/test_data.py::test_polynomial_features_csr_X_dim_edges[3-3-True]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_invalid_range", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_fit_transform[True-box-cox]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_sample_weight[sparse_csr-Xw1-X1-sample_weight1]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_2d_arrays", "sklearn/preprocessing/tests/test_data.py::test_polynomial_features_csr_X_dim_edges[2-2-False]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_equivalence_dense_sparse[zeros-0.1]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_partial_fit", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_equivalence_dense_sparse[positive-1]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_equivalence_dense_sparse[None-0.1]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_fit_transform[False-box-cox]", "sklearn/preprocessing/tests/test_data.py::test_maxabs_scaler_large_negative_value", "sklearn/preprocessing/tests/test_data.py::test_polynomial_features_csr_X_degree_4[True-False]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_equivalence_dense_sparse[zeros-0.05]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_1d", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_copy_True[False-box-cox]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_2d", "sklearn/preprocessing/tests/test_data.py::test_polynomial_features_csr_X_dim_edges[2-1-True]", "sklearn/preprocessing/tests/test_data.py::test_fit_cold_start", "sklearn/preprocessing/tests/test_data.py::test_polynomial_features", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_shape_exception[box-cox]", "sklearn/preprocessing/tests/test_data.py::test_polynomial_features_csr_X_dim_edges[2-1-False]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_equivalence_dense_sparse[negative-0]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_yeojohnson_any_input[X2]", "sklearn/preprocessing/tests/test_data.py::test_polynomial_features_csc_X[3-False-False-float64]", "sklearn/preprocessing/tests/test_data.py::test_polynomial_features_csr_X_floats[3-False-True-float64]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_dtype[True-None]", "sklearn/preprocessing/tests/test_data.py::test_scaler_return_identity", "sklearn/preprocessing/tests/test_data.py::test_quantile_transform_bounds", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_fit_transform[False-yeo-johnson]", "sklearn/preprocessing/tests/test_data.py::test_min_max_scaler_iris", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_iris_quantiles", "sklearn/preprocessing/tests/test_data.py::test_polynomial_features_csr_X_dim_edges[3-2-False]", "sklearn/preprocessing/tests/test_data.py::test_maxabs_scaler_zero_variance_features", "sklearn/preprocessing/tests/test_data.py::test_polynomial_features_csc_X[2-True-False-float32]", "sklearn/preprocessing/tests/test_data.py::test_quantile_transform_axis1", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_error_sparse", "sklearn/preprocessing/tests/test_data.py::test_quantile_transformer_sorted_quantiles[sparse]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_equivalence_dense_sparse[None-0]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_1d", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_equivalence_dense_sparse[None-0.5]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_equivalence_dense_sparse[positive-0.5]", "sklearn/preprocessing/tests/test_data.py::test_scaler_n_samples_seen_with_nan[csr_matrix-False-False]", "sklearn/preprocessing/tests/test_data.py::test_binarizer", "sklearn/preprocessing/tests/test_data.py::test_quantile_transform_and_inverse", "sklearn/preprocessing/tests/test_data.py::test_polynomial_features_csr_X_zero_row[0-2-True]", "sklearn/preprocessing/tests/test_data.py::test_polynomial_features_csr_X_dim_edges[3-2-True]", "sklearn/preprocessing/tests/test_data.py::test_polynomial_features_csr_X_zero_row[1-2-True]", "sklearn/preprocessing/tests/test_data.py::test_polynomial_features_csc_X[3-False-True-float64]", "sklearn/preprocessing/tests/test_data.py::test_polynomial_features_csr_X[3-False-True-float64]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_trasform_with_partial_fit[None]", "sklearn/preprocessing/tests/test_data.py::test_scale_input_finiteness_validation", "sklearn/preprocessing/tests/test_data.py::test_minmax_scale_axis1", "sklearn/preprocessing/tests/test_data.py::test_quantile_transform_subsampling", "sklearn/preprocessing/tests/test_data.py::test_scaler_n_samples_seen_with_nan[asarray-False-True]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_attributes[X1-True-False]", "sklearn/preprocessing/tests/test_data.py::test_quantile_transform_iris", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_sample_weight[sparse_csc-Xw1-X1-sample_weight1]", "sklearn/preprocessing/tests/test_data.py::test_optimization_power_transformer[box-cox-0.1]", "sklearn/preprocessing/tests/test_data.py::test_optimization_power_transformer[yeo-johnson-0.5]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_nans[yeo-johnson]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_attributes[X0-True-True]", "sklearn/preprocessing/tests/test_data.py::test_polynomial_features_csr_X_dim_edges[3-1-False]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_zero_variance_features", "sklearn/preprocessing/tests/test_data.py::test_normalizer_l1", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_notfitted[box-cox]", "sklearn/preprocessing/tests/test_data.py::test_polynomial_features_csr_X_zero_row[2-2-False]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_lambda_one", "sklearn/preprocessing/tests/test_data.py::test_polynomial_features_csr_X_degree_4[False-False]", "sklearn/preprocessing/tests/test_data.py::test_polynomial_features_csr_X[1-True-False-int]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_attributes[X0-False-True]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_inverse[X0-True-yeo-johnson]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_inverse[X1-False-yeo-johnson]", "sklearn/preprocessing/tests/test_data.py::test_polynomial_features_csr_X_zero_row[0-3-True]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_copy_False[True-yeo-johnson]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_equivalence_dense_sparse[zeros-0.5]", "sklearn/preprocessing/tests/test_data.py::test_maxabs_scaler_partial_fit", "sklearn/preprocessing/tests/test_data.py::test_normalizer_l2", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_dtype[False-csc_matrix]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_inverse[X1-True-yeo-johnson]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_transform_one_row_csr", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_sample_weight[array-Xw2-X2-sample_weight2]", "sklearn/preprocessing/tests/test_data.py::test_add_dummy_feature", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_dtype[True-csc_matrix]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_inverse[X0-False-box-cox]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_boxcox_strictly_positive_exception", "sklearn/preprocessing/tests/test_data.py::test_normalize", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_copy_False[False-yeo-johnson]", "sklearn/preprocessing/tests/test_data.py::test_minmax_scaler_clip[feature_range0]", "sklearn/preprocessing/tests/test_data.py::test_maxabs_scaler_transform_one_row_csr", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_sample_weight[array-Xw0-X0-sample_weight0]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_sample_weight[sparse_csr-Xw2-X2-sample_weight2]", "sklearn/preprocessing/tests/test_data.py::test_min_max_scaler_zero_variance_features", "sklearn/preprocessing/tests/test_data.py::test_maxabs_scaler_1d", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_shape_exception[yeo-johnson]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_equivalence_dense_sparse[negative-0.05]", "sklearn/preprocessing/tests/test_data.py::test_scaler_without_centering[True]", "sklearn/preprocessing/tests/test_data.py::test_polynomial_feature_names", "sklearn/preprocessing/tests/test_data.py::test_minmax_scaler_partial_fit", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_dtype[True-csr_matrix]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_equivalence_dense_sparse[None-0.05]", "sklearn/preprocessing/tests/test_data.py::test_optimization_power_transformer[box-cox-0.5]", "sklearn/preprocessing/tests/test_data.py::test_polynomial_features_csr_X_floats[2-True-False-float64]", "sklearn/preprocessing/tests/test_data.py::test_scale_sparse_with_mean_raise_exception", "sklearn/preprocessing/tests/test_data.py::test_optimization_power_transformer[yeo-johnson-0.1]", "sklearn/preprocessing/tests/test_data.py::test_polynomial_features_csc_X[4-False-False-float64]", "sklearn/preprocessing/tests/test_data.py::test_normalizer_max_sign", "sklearn/preprocessing/tests/test_data.py::test_polynomial_features_csr_X_zero_row[0-2-False]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_lambda_zero", "sklearn/preprocessing/tests/test_data.py::test_polynomial_features_csr_X_degree_4[False-True]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_equivalence_dense_sparse[positive-0.05]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_attributes[X1-False-False]", "sklearn/preprocessing/tests/test_data.py::test_quantile_transform_dense_toy", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_numerical_stability", "sklearn/preprocessing/tests/test_data.py::test_polynomial_features_csr_X_zero_row[1-2-False]", "sklearn/preprocessing/tests/test_data.py::test_quantile_transform_check_error", "sklearn/preprocessing/tests/test_data.py::test_quantile_transform_sparse_ignore_zeros", "sklearn/preprocessing/tests/test_data.py::test_robust_scale_1d_array", "sklearn/preprocessing/tests/test_data.py::test_scale_1d", "sklearn/preprocessing/tests/test_data.py::test_scaler_n_samples_seen_with_nan[asarray-True-False]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_copy_True[True-yeo-johnson]", "sklearn/preprocessing/tests/test_data.py::test_robust_scale_axis1", "sklearn/preprocessing/tests/test_data.py::test_min_max_scaler_1d", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_notfitted[yeo-johnson]", "sklearn/preprocessing/tests/test_data.py::test_polynomial_features_csc_X[4-False-True-float64]", "sklearn/preprocessing/tests/test_data.py::test_polynomial_features_csr_X_floats[2-True-False-float32]", "sklearn/preprocessing/tests/test_data.py::test_scaler_int", "sklearn/preprocessing/tests/test_data.py::test_polynomial_features_csr_X_dim_edges[3-1-True]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_unit_variance", "sklearn/preprocessing/tests/test_data.py::test_polynomial_features_csr_X_zero_row[1-3-False]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_equivalence_dense_sparse[negative-0.5]", "sklearn/preprocessing/tests/test_data.py::test_add_dummy_feature_csr", "sklearn/preprocessing/tests/test_data.py::test_scaler_2d_arrays", "sklearn/preprocessing/tests/test_data.py::test_scaler_n_samples_seen_with_nan[csc_matrix-True-False]", "sklearn/preprocessing/tests/test_data.py::test_handle_zeros_in_scale", "sklearn/preprocessing/tests/test_data.py::test_polynomial_features_csr_X_zero_row[2-2-True]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_inverse[X0-False-yeo-johnson]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_sample_weight[sparse_csc-Xw2-X2-sample_weight2]", "sklearn/preprocessing/tests/test_data.py::test_scaler_without_centering[None]", "sklearn/preprocessing/tests/test_data.py::test_polynomial_features_csr_X_zero_row[2-3-False]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_inverse[X0-True-box-cox]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_nans[box-cox]", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_dtype[False-None]", "sklearn/preprocessing/tests/test_data.py::test_fit_transform", "sklearn/preprocessing/tests/test_data.py::test_cv_pipeline_precomputed", "sklearn/preprocessing/tests/test_data.py::test_quantile_transform_nan", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_yeojohnson_any_input[X3]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_fit_transform[True-yeo-johnson]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_copy_True[False-yeo-johnson]", "sklearn/preprocessing/tests/test_data.py::test_quantile_transform_valid_axis", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_equivalence_dense_sparse[zeros-0]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_col_zero_sparse", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_trasform_with_partial_fit[True]", "sklearn/preprocessing/tests/test_data.py::test_polynomial_features_csc_X[1-True-False-int]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_inverse[X1-True-box-cox]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_equivalence_dense_sparse[negative-1]", "sklearn/preprocessing/tests/test_data.py::test_add_dummy_feature_csc", "sklearn/preprocessing/tests/test_data.py::test_normalizer_max", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_sample_weight[sparse_csc-Xw0-X0-sample_weight0]", "sklearn/preprocessing/tests/test_data.py::test_scaler_n_samples_seen_with_nan[asarray-True-True]", "sklearn/preprocessing/tests/test_data.py::test_add_dummy_feature_coo", "sklearn/preprocessing/tests/test_data.py::test_polynomial_feature_array_order", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_sparse_partial_fit_finite_variance[X_20]", "sklearn/preprocessing/tests/test_data.py::test_polynomial_features_csc_X[2-True-False-int]", "sklearn/preprocessing/tests/test_data.py::test_robust_scaler_equivalence_dense_sparse[zeros-1]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_yeojohnson_any_input[X1]", "sklearn/preprocessing/tests/test_data.py::test_scale_function_without_centering", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_inverse[X1-False-box-cox]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_copy_False[True-box-cox]", "sklearn/preprocessing/tests/test_data.py::test_minmax_scaler_clip[feature_range1]", "sklearn/preprocessing/tests/test_data.py::test_raises_value_error_if_sample_weights_greater_than_1d", "sklearn/preprocessing/tests/test_data.py::test_standard_scaler_sample_weight[sparse_csr-Xw0-X0-sample_weight0]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_yeojohnson_any_input[X0]", "sklearn/preprocessing/tests/test_data.py::test_polynomial_features_csr_X[2-True-False-float64]", "sklearn/preprocessing/tests/test_data.py::test_polynomial_features_csr_X_degree_4[True-True]", "sklearn/preprocessing/tests/test_data.py::test_partial_fit_sparse_input[None]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_copy_True[True-box-cox]", "sklearn/preprocessing/tests/test_data.py::test_polynomial_features_csr_X[2-True-False-int]", "sklearn/preprocessing/tests/test_data.py::test_power_transformer_copy_False[False-box-cox]" ]
[ "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[uniform-3-1]", "sklearn/utils/tests/test_fixes.py::test_object_dtype_isnan[object-1]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_input_validation[params12-knots must be sorted without duplicates.]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_input_validation[params0-degree must be a non-negative integer.]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_manual_knot_input", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_input_validation[params7-Expected 2D array, got scalar array instead:]", "sklearn/utils/tests/test_fixes.py::test_object_dtype_isnan[float-1]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[uniform-4-1]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_input_validation[params18-include_bias must be bool.]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_extrapolation[5-True-False]", "sklearn/utils/tests/test_fixes.py::test_loguniform[-1-0-10]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_input_validation[params11-knots must be sorted without duplicates.]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_input_validation[params1-degree must be a non-negative integer.]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[quantile-4-2]", "sklearn/utils/tests/test_fixes.py::test_linspace", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_input_validation[params6-n_knots must be a positive integer >= 2.]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_linear_regression[False-True]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_input_validation[params10-knots.shape\\\\[1\\\\] == n_features is violated.]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[uniform-3-4]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_extrapolation[3-False-True]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_input_validation[params16-include_bias must be bool.]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[quantile-4-1]", "sklearn/utils/tests/test_fixes.py::test_loguniform[-1-1-2]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_extrapolation[3-True-False]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[uniform-4-2]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_input_validation[params15-extrapolation must be one of 'error', 'constant', 'linear' or 'continue'.]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_input_validation[params4-n_knots must be a positive integer >= 2.]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_input_validation[params5-n_knots must be a positive integer >= 2.]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_and_spline_array_order[SplineTransformer]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[uniform-3-3]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[quantile-3-1]", "sklearn/utils/tests/test_fixes.py::test_masked_array_deprecated", "sklearn/utils/tests/test_fixes.py::test_joblib_parallel_args[0.11]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_extrapolation[2-True-False]", "sklearn/utils/tests/test_fixes.py::test_loguniform[0-2-2.718281828459045]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[uniform-4-3]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_input_validation[params3-n_knots must be a positive integer >= 2.]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_input_validation[params8-Expected 2D array, got 1D array instead:]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[quantile-3-2]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[uniform-4-4]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_input_validation[params13-extrapolation must be one of 'error', 'constant', 'linear' or 'continue'.]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_input_validation[params17-include_bias must be bool.]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[uniform-3-2]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[quantile-4-3]", "sklearn/utils/tests/test_fixes.py::test_joblib_parallel_args[0.12.0]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_extrapolation[1-False-True]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_linear_regression[True-False]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_input_validation[params9-Number of knots, knots.shape\\\\[0\\\\], must be >= 2.]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_extrapolation[2-False-True]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_extrapolation[4-True-False]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[quantile-4-4]", "sklearn/utils/tests/test_fixes.py::test_object_dtype_isnan[object-a]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_extrapolation[1-True-False]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[quantile-3-4]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_kbindiscretizer", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_extrapolation[5-False-True]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_extrapolation[4-False-True]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_feature_names", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[quantile-3-3]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_input_validation[params14-extrapolation must be one of 'error', 'constant', 'linear' or 'continue'.]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_input_validation[params2-degree must be a non-negative integer.]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [ { "type": "file", "name": "sklearn/preprocessing/_polynomial.py" } ] }
[ { "path": "doc/modules/classes.rst", "old_path": "a/doc/modules/classes.rst", "new_path": "b/doc/modules/classes.rst", "metadata": "diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst\nindex 84f8097cbbe9d..65d555f978df0 100644\n--- a/doc/modules/classes.rst\n+++ b/doc/modules/classes.rst\n@@ -1414,6 +1414,7 @@ details.\n preprocessing.PowerTransformer\n preprocessing.QuantileTransformer\n preprocessing.RobustScaler\n+ preprocessing.SplineTransformer\n preprocessing.StandardScaler\n \n .. autosummary::\n" }, { "path": "doc/modules/preprocessing.rst", "old_path": "a/doc/modules/preprocessing.rst", "new_path": "b/doc/modules/preprocessing.rst", "metadata": "diff --git a/doc/modules/preprocessing.rst b/doc/modules/preprocessing.rst\nindex 801d9a98ed1f4..a339b4bfae4e2 100644\n--- a/doc/modules/preprocessing.rst\n+++ b/doc/modules/preprocessing.rst\n@@ -624,7 +624,9 @@ of continuous attributes to one with only nominal attributes.\n \n One-hot encoded discretized features can make a model more expressive, while\n maintaining interpretability. For instance, pre-processing with a discretizer\n-can introduce nonlinearity to linear models.\n+can introduce nonlinearity to linear models. For more advanced possibilities,\n+in particular smooth ones, see :ref:`generating_polynomial_features` further\n+below.\n \n K-bins discretization\n ---------------------\n@@ -756,12 +758,24 @@ Imputation of missing values\n \n Tools for imputing missing values are discussed at :ref:`impute`.\n \n-.. _polynomial_features:\n+.. _generating_polynomial_features:\n \n Generating polynomial features\n ==============================\n \n-Often it's useful to add complexity to the model by considering nonlinear features of the input data. A simple and common method to use is polynomial features, which can get features' high-order and interaction terms. It is implemented in :class:`PolynomialFeatures`::\n+Often it's useful to add complexity to a model by considering nonlinear\n+features of the input data. We show two possibilities that are both based on\n+polynomials: The first one uses pure polynomials, the second one uses splines,\n+i.e. piecewise polynomials.\n+\n+.. _polynomial_features:\n+\n+Polynomial features\n+-------------------\n+\n+A simple and common method to use is polynomial features, which can get\n+features' high-order and interaction terms. It is implemented in\n+:class:`PolynomialFeatures`::\n \n >>> import numpy as np\n >>> from sklearn.preprocessing import PolynomialFeatures\n@@ -776,9 +790,11 @@ Often it's useful to add complexity to the model by considering nonlinear featur\n [ 1., 2., 3., 4., 6., 9.],\n [ 1., 4., 5., 16., 20., 25.]])\n \n-The features of X have been transformed from :math:`(X_1, X_2)` to :math:`(1, X_1, X_2, X_1^2, X_1X_2, X_2^2)`.\n+The features of X have been transformed from :math:`(X_1, X_2)` to\n+:math:`(1, X_1, X_2, X_1^2, X_1X_2, X_2^2)`.\n \n-In some cases, only interaction terms among features are required, and it can be gotten with the setting ``interaction_only=True``::\n+In some cases, only interaction terms among features are required, and it can\n+be gotten with the setting ``interaction_only=True``::\n \n >>> X = np.arange(9).reshape(3, 3)\n >>> X\n@@ -791,11 +807,94 @@ In some cases, only interaction terms among features are required, and it can be\n [ 1., 3., 4., 5., 12., 15., 20., 60.],\n [ 1., 6., 7., 8., 42., 48., 56., 336.]])\n \n-The features of X have been transformed from :math:`(X_1, X_2, X_3)` to :math:`(1, X_1, X_2, X_3, X_1X_2, X_1X_3, X_2X_3, X_1X_2X_3)`.\n+The features of X have been transformed from :math:`(X_1, X_2, X_3)` to\n+:math:`(1, X_1, X_2, X_3, X_1X_2, X_1X_3, X_2X_3, X_1X_2X_3)`.\n+\n+Note that polynomial features are used implicitly in `kernel methods\n+<https://en.wikipedia.org/wiki/Kernel_method>`_ (e.g., :class:`~sklearn.svm.SVC`,\n+:class:`~sklearn.decomposition.KernelPCA`) when using polynomial :ref:`svm_kernels`.\n+\n+See :ref:`sphx_glr_auto_examples_linear_model_plot_polynomial_interpolation.py`\n+for Ridge regression using created polynomial features.\n+\n+.. _spline_transformer:\n+\n+Spline transformer\n+------------------\n+\n+Another way to add nonlinear terms instead of pure polynomials of features is\n+to generate spline basis functions for each feature with the\n+:class:`SplineTransformer`. Splines are piecewise polynomials, parametrized by\n+their polynomial degree and the positions of the knots. The\n+:class:`SplineTransformer` implements a B-spline basis, cf. the references\n+below.\n+\n+.. note::\n+\n+ The :class:`SplineTransformer` treats each feature separately, i.e. it\n+ won't give you interaction terms.\n+\n+Some of the advantages of splines over polynomials are:\n+\n+ - B-splines are very flexible and robust if you keep a fixed low degree,\n+ usually 3, and parsimoniously adapt the number of knots. Polynomials\n+ would need a higher degree, which leads to the next point.\n+ - B-splines do not have oscillatory behaviour at the boundaries as have\n+ polynomials (the higher the degree, the worse). This is known as `Runge's\n+ phenomenon <https://en.wikipedia.org/wiki/Runge%27s_phenomenon>`_.\n+ - B-splines provide good options for extrapolation beyond the boundaries,\n+ i.e. beyond the range of fitted values. Have a look at the option\n+ ``extrapolation``.\n+ - B-splines generate a feature matrix with a banded structure. For a single\n+ feature, every row contains only ``degree + 1`` non-zero elements, which\n+ occur consecutively and are even positive. This results in a matrix with\n+ good numerical properties, e.g. a low condition number, in sharp contrast\n+ to a matrix of polynomials, which goes under the name\n+ `Vandermonde matrix <https://en.wikipedia.org/wiki/Vandermonde_matrix>`_.\n+ A low condition number is important for stable algorithms of linear\n+ models.\n+\n+The following code snippet shows splines in action::\n+\n+ >>> import numpy as np\n+ >>> from sklearn.preprocessing import SplineTransformer\n+ >>> X = np.arange(5).reshape(5, 1)\n+ >>> X\n+ array([[0],\n+ [1],\n+ [2],\n+ [3],\n+ [4]])\n+ >>> spline = SplineTransformer(degree=2, n_knots=3)\n+ >>> spline.fit_transform(X)\n+ array([[0.5 , 0.5 , 0. , 0. ],\n+ [0.125, 0.75 , 0.125, 0. ],\n+ [0. , 0.5 , 0.5 , 0. ],\n+ [0. , 0.125, 0.75 , 0.125],\n+ [0. , 0. , 0.5 , 0.5 ]])\n+\n+As the ``X`` is sorted, one can easily see the banded matrix output. Only the\n+three middle diagonals are non-zero for ``degree=2``. The higher the degree,\n+the more overlapping of the splines.\n+\n+Interestingly, a :class:`SplineTransformer` of ``degree=0`` is the same as\n+:class:`~sklearn.preprocessing.KBinsDiscretizer` with ``encode='onehot-dense``\n+and ``n_bins = n_knots - 1`` if ``knots = strategy``.\n+\n+.. topic:: Examples:\n+\n+ * :ref:`sphx_glr_auto_examples_linear_model_plot_polynomial_interpolation.py`\n+\n+.. topic:: References:\n \n-Note that polynomial features are used implicitly in `kernel methods <https://en.wikipedia.org/wiki/Kernel_method>`_ (e.g., :class:`~sklearn.svm.SVC`, :class:`~sklearn.decomposition.KernelPCA`) when using polynomial :ref:`svm_kernels`.\n+ * Eilers, P., & Marx, B. (1996). Flexible Smoothing with B-splines and\n+ Penalties. Statist. Sci. 11 (1996), no. 2, 89--121.\n+ `doi:10.1214/ss/1038425655 <https://doi.org/10.1214/ss/1038425655>`_\n \n-See :ref:`sphx_glr_auto_examples_linear_model_plot_polynomial_interpolation.py` for Ridge regression using created polynomial features.\n+ * Perperoglou, A., Sauerbrei, W., Abrahamowicz, M. et al. A review of\n+ spline function procedures in R. BMC Med Res Methodol 19, 46 (2019).\n+ `doi:10.1186/s12874-019-0666-3\n+ <https://doi.org/10.1186/s12874-019-0666-3>`_\n \n .. _function_transformer:\n \n" }, { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 652eba896903b..177dab23b3e62 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -110,6 +110,15 @@ Changelog\n Use ``var_`` instead.\n :pr:`<PRID>` by :user:`<NAME>`.\n \n+:mod:`sklearn.preprocessing`\n+............................\n+\n+- |Feature| The new :class:`preprocessing.SplineTransformer` is a feature\n+ preprocessing tool for the generation of B-splines, parametrized by the\n+ polynomial ``degree`` of the splines, number of knots ``n_knots`` and knot\n+ positioning strategy ``knots``.\n+ :pr:`<PRID>` by :user:`<NAME>`.\n+\n :mod:`sklearn.tree`\n ...................\n \n" } ]
diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst index 84f8097cbbe9d..65d555f978df0 100644 --- a/doc/modules/classes.rst +++ b/doc/modules/classes.rst @@ -1414,6 +1414,7 @@ details. preprocessing.PowerTransformer preprocessing.QuantileTransformer preprocessing.RobustScaler + preprocessing.SplineTransformer preprocessing.StandardScaler .. autosummary:: diff --git a/doc/modules/preprocessing.rst b/doc/modules/preprocessing.rst index 801d9a98ed1f4..a339b4bfae4e2 100644 --- a/doc/modules/preprocessing.rst +++ b/doc/modules/preprocessing.rst @@ -624,7 +624,9 @@ of continuous attributes to one with only nominal attributes. One-hot encoded discretized features can make a model more expressive, while maintaining interpretability. For instance, pre-processing with a discretizer -can introduce nonlinearity to linear models. +can introduce nonlinearity to linear models. For more advanced possibilities, +in particular smooth ones, see :ref:`generating_polynomial_features` further +below. K-bins discretization --------------------- @@ -756,12 +758,24 @@ Imputation of missing values Tools for imputing missing values are discussed at :ref:`impute`. -.. _polynomial_features: +.. _generating_polynomial_features: Generating polynomial features ============================== -Often it's useful to add complexity to the model by considering nonlinear features of the input data. A simple and common method to use is polynomial features, which can get features' high-order and interaction terms. It is implemented in :class:`PolynomialFeatures`:: +Often it's useful to add complexity to a model by considering nonlinear +features of the input data. We show two possibilities that are both based on +polynomials: The first one uses pure polynomials, the second one uses splines, +i.e. piecewise polynomials. + +.. _polynomial_features: + +Polynomial features +------------------- + +A simple and common method to use is polynomial features, which can get +features' high-order and interaction terms. It is implemented in +:class:`PolynomialFeatures`:: >>> import numpy as np >>> from sklearn.preprocessing import PolynomialFeatures @@ -776,9 +790,11 @@ Often it's useful to add complexity to the model by considering nonlinear featur [ 1., 2., 3., 4., 6., 9.], [ 1., 4., 5., 16., 20., 25.]]) -The features of X have been transformed from :math:`(X_1, X_2)` to :math:`(1, X_1, X_2, X_1^2, X_1X_2, X_2^2)`. +The features of X have been transformed from :math:`(X_1, X_2)` to +:math:`(1, X_1, X_2, X_1^2, X_1X_2, X_2^2)`. -In some cases, only interaction terms among features are required, and it can be gotten with the setting ``interaction_only=True``:: +In some cases, only interaction terms among features are required, and it can +be gotten with the setting ``interaction_only=True``:: >>> X = np.arange(9).reshape(3, 3) >>> X @@ -791,11 +807,94 @@ In some cases, only interaction terms among features are required, and it can be [ 1., 3., 4., 5., 12., 15., 20., 60.], [ 1., 6., 7., 8., 42., 48., 56., 336.]]) -The features of X have been transformed from :math:`(X_1, X_2, X_3)` to :math:`(1, X_1, X_2, X_3, X_1X_2, X_1X_3, X_2X_3, X_1X_2X_3)`. +The features of X have been transformed from :math:`(X_1, X_2, X_3)` to +:math:`(1, X_1, X_2, X_3, X_1X_2, X_1X_3, X_2X_3, X_1X_2X_3)`. + +Note that polynomial features are used implicitly in `kernel methods +<https://en.wikipedia.org/wiki/Kernel_method>`_ (e.g., :class:`~sklearn.svm.SVC`, +:class:`~sklearn.decomposition.KernelPCA`) when using polynomial :ref:`svm_kernels`. + +See :ref:`sphx_glr_auto_examples_linear_model_plot_polynomial_interpolation.py` +for Ridge regression using created polynomial features. + +.. _spline_transformer: + +Spline transformer +------------------ + +Another way to add nonlinear terms instead of pure polynomials of features is +to generate spline basis functions for each feature with the +:class:`SplineTransformer`. Splines are piecewise polynomials, parametrized by +their polynomial degree and the positions of the knots. The +:class:`SplineTransformer` implements a B-spline basis, cf. the references +below. + +.. note:: + + The :class:`SplineTransformer` treats each feature separately, i.e. it + won't give you interaction terms. + +Some of the advantages of splines over polynomials are: + + - B-splines are very flexible and robust if you keep a fixed low degree, + usually 3, and parsimoniously adapt the number of knots. Polynomials + would need a higher degree, which leads to the next point. + - B-splines do not have oscillatory behaviour at the boundaries as have + polynomials (the higher the degree, the worse). This is known as `Runge's + phenomenon <https://en.wikipedia.org/wiki/Runge%27s_phenomenon>`_. + - B-splines provide good options for extrapolation beyond the boundaries, + i.e. beyond the range of fitted values. Have a look at the option + ``extrapolation``. + - B-splines generate a feature matrix with a banded structure. For a single + feature, every row contains only ``degree + 1`` non-zero elements, which + occur consecutively and are even positive. This results in a matrix with + good numerical properties, e.g. a low condition number, in sharp contrast + to a matrix of polynomials, which goes under the name + `Vandermonde matrix <https://en.wikipedia.org/wiki/Vandermonde_matrix>`_. + A low condition number is important for stable algorithms of linear + models. + +The following code snippet shows splines in action:: + + >>> import numpy as np + >>> from sklearn.preprocessing import SplineTransformer + >>> X = np.arange(5).reshape(5, 1) + >>> X + array([[0], + [1], + [2], + [3], + [4]]) + >>> spline = SplineTransformer(degree=2, n_knots=3) + >>> spline.fit_transform(X) + array([[0.5 , 0.5 , 0. , 0. ], + [0.125, 0.75 , 0.125, 0. ], + [0. , 0.5 , 0.5 , 0. ], + [0. , 0.125, 0.75 , 0.125], + [0. , 0. , 0.5 , 0.5 ]]) + +As the ``X`` is sorted, one can easily see the banded matrix output. Only the +three middle diagonals are non-zero for ``degree=2``. The higher the degree, +the more overlapping of the splines. + +Interestingly, a :class:`SplineTransformer` of ``degree=0`` is the same as +:class:`~sklearn.preprocessing.KBinsDiscretizer` with ``encode='onehot-dense`` +and ``n_bins = n_knots - 1`` if ``knots = strategy``. + +.. topic:: Examples: + + * :ref:`sphx_glr_auto_examples_linear_model_plot_polynomial_interpolation.py` + +.. topic:: References: -Note that polynomial features are used implicitly in `kernel methods <https://en.wikipedia.org/wiki/Kernel_method>`_ (e.g., :class:`~sklearn.svm.SVC`, :class:`~sklearn.decomposition.KernelPCA`) when using polynomial :ref:`svm_kernels`. + * Eilers, P., & Marx, B. (1996). Flexible Smoothing with B-splines and + Penalties. Statist. Sci. 11 (1996), no. 2, 89--121. + `doi:10.1214/ss/1038425655 <https://doi.org/10.1214/ss/1038425655>`_ -See :ref:`sphx_glr_auto_examples_linear_model_plot_polynomial_interpolation.py` for Ridge regression using created polynomial features. + * Perperoglou, A., Sauerbrei, W., Abrahamowicz, M. et al. A review of + spline function procedures in R. BMC Med Res Methodol 19, 46 (2019). + `doi:10.1186/s12874-019-0666-3 + <https://doi.org/10.1186/s12874-019-0666-3>`_ .. _function_transformer: diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index 652eba896903b..177dab23b3e62 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -110,6 +110,15 @@ Changelog Use ``var_`` instead. :pr:`<PRID>` by :user:`<NAME>`. +:mod:`sklearn.preprocessing` +............................ + +- |Feature| The new :class:`preprocessing.SplineTransformer` is a feature + preprocessing tool for the generation of B-splines, parametrized by the + polynomial ``degree`` of the splines, number of knots ``n_knots`` and knot + positioning strategy ``knots``. + :pr:`<PRID>` by :user:`<NAME>`. + :mod:`sklearn.tree` ................... If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names: [{'type': 'file', 'name': 'sklearn/preprocessing/_polynomial.py'}]
scikit-learn/scikit-learn
scikit-learn__scikit-learn-19069
https://github.com/scikit-learn/scikit-learn/pull/19069
diff --git a/doc/modules/preprocessing.rst b/doc/modules/preprocessing.rst index e1b4c5599c3b5..b87971ec4ae5a 100644 --- a/doc/modules/preprocessing.rst +++ b/doc/modules/preprocessing.rst @@ -482,6 +482,17 @@ scikit-learn estimators, as these expect continuous input, and would interpret the categories as being ordered, which is often not desired (i.e. the set of browsers was ordered arbitrarily). +:class:`OrdinalEncoder` will also passthrough missing values that are +indicated by `np.nan`. + + >>> enc = preprocessing.OrdinalEncoder() + >>> X = [['male'], ['female'], [np.nan], ['female']] + >>> enc.fit_transform(X) + array([[ 1.], + [ 0.], + [nan], + [ 0.]]) + Another possibility to convert categorical features to features that can be used with scikit-learn estimators is to use a one-of-K, also known as one-hot or dummy encoding. diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index 25e0b369bebd3..6a565b8d5e21b 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -123,6 +123,12 @@ Changelog not corresponding to their objective. :pr:`19172` by :user:`Mathurin Massias <mathurinm>` +:mod:`sklearn.preprocessing` +............................ + +- |Feature| :class:`preprocessing.OrdinalEncoder` supports passing through + missing values by default. :pr:`19069` by `Thomas Fan`_. + - |API|: The parameter ``normalize`` of :class:`linear_model.LinearRegression` is deprecated and will be removed in 1.2. Motivation for this deprecation: ``normalize`` parameter did not take any diff --git a/sklearn/preprocessing/_encoders.py b/sklearn/preprocessing/_encoders.py index 342b730ba91ed..043f9fc40ef53 100644 --- a/sklearn/preprocessing/_encoders.py +++ b/sklearn/preprocessing/_encoders.py @@ -10,6 +10,7 @@ from ..utils import check_array, is_scalar_nan from ..utils.validation import check_is_fitted from ..utils.validation import _deprecate_positional_args +from ..utils._mask import _get_mask from ..utils._encode import _encode, _check_unknown, _unique @@ -752,7 +753,7 @@ def fit(self, X, y=None): if np.dtype(self.dtype).kind != 'f': raise ValueError( f"When unknown_value is np.nan, the dtype " - "parameter should be " + f"parameter should be " f"a float dtype. Got {self.dtype}." ) elif not isinstance(self.unknown_value, numbers.Integral): @@ -765,7 +766,7 @@ def fit(self, X, y=None): f"handle_unknown is 'use_encoded_value', " f"got {self.unknown_value}.") - self._fit(X) + self._fit(X, force_all_finite='allow-nan') if self.handle_unknown == 'use_encoded_value': for feature_cats in self.categories_: @@ -775,6 +776,21 @@ def fit(self, X, y=None): f"values already used for encoding the " f"seen categories.") + # stores the missing indices per category + self._missing_indices = {} + for cat_idx, categories_for_idx in enumerate(self.categories_): + for i, cat in enumerate(categories_for_idx): + if is_scalar_nan(cat): + self._missing_indices[cat_idx] = i + continue + + if np.dtype(self.dtype).kind != 'f' and self._missing_indices: + raise ValueError( + "There are missing values in features " + f"{list(self._missing_indices)}. For OrdinalEncoder to " + "passthrough missing values, the dtype parameter must be a " + "float") + return self def transform(self, X): @@ -791,9 +807,14 @@ def transform(self, X): X_out : sparse matrix or a 2-d array Transformed input. """ - X_int, X_mask = self._transform(X, handle_unknown=self.handle_unknown) + X_int, X_mask = self._transform(X, handle_unknown=self.handle_unknown, + force_all_finite='allow-nan') X_trans = X_int.astype(self.dtype, copy=False) + for cat_idx, missing_idx in self._missing_indices.items(): + X_missing_mask = X_int[:, cat_idx] == missing_idx + X_trans[X_missing_mask, cat_idx] = np.nan + # create separate category for unknown values if self.handle_unknown == 'use_encoded_value': X_trans[~X_mask] = self.unknown_value @@ -814,7 +835,7 @@ def inverse_transform(self, X): Inverse transformed array. """ check_is_fitted(self) - X = check_array(X, accept_sparse='csr') + X = check_array(X, accept_sparse='csr', force_all_finite='allow-nan') n_samples, _ = X.shape n_features = len(self.categories_) @@ -833,6 +854,12 @@ def inverse_transform(self, X): for i in range(n_features): labels = X[:, i].astype('int64', copy=False) + + # replace values of X[:, i] that were nan with actual indices + if i in self._missing_indices: + X_i_mask = _get_mask(X[:, i], np.nan) + labels[X_i_mask] = self._missing_indices[i] + if self.handle_unknown == 'use_encoded_value': unknown_labels = labels == self.unknown_value X_tr[:, i] = self.categories_[i][np.where(
diff --git a/sklearn/preprocessing/tests/test_encoders.py b/sklearn/preprocessing/tests/test_encoders.py index fd28d8c40b46c..b1eff0cad21e0 100644 --- a/sklearn/preprocessing/tests/test_encoders.py +++ b/sklearn/preprocessing/tests/test_encoders.py @@ -574,24 +574,6 @@ def test_ordinal_encoder_inverse(): enc.inverse_transform(X_tr) [email protected]("X", [np.array([[1, np.nan]]).T, - np.array([['a', np.nan]], dtype=object).T], - ids=['numeric', 'object']) -def test_ordinal_encoder_raise_missing(X): - ohe = OrdinalEncoder() - - with pytest.raises(ValueError, match="Input contains NaN"): - ohe.fit(X) - - with pytest.raises(ValueError, match="Input contains NaN"): - ohe.fit_transform(X) - - ohe.fit(X[:1, :]) - - with pytest.raises(ValueError, match="Input contains NaN"): - ohe.transform(X) - - def test_ordinal_encoder_handle_unknowns_string(): enc = OrdinalEncoder(handle_unknown='use_encoded_value', unknown_value=-2) X_fit = np.array([['a', 'x'], ['b', 'y'], ['c', 'z']], dtype=object) @@ -930,3 +912,122 @@ def test_ohe_missing_value_support_pandas_categorical(pd_nan_type): assert len(ohe.categories_) == 1 assert_array_equal(ohe.categories_[0][:-1], ['a', 'b', 'c']) assert np.isnan(ohe.categories_[0][-1]) + + +def test_ordinal_encoder_passthrough_missing_values_float_errors_dtype(): + """Test ordinal encoder with nan passthrough fails when dtype=np.int32.""" + + X = np.array([[np.nan, 3.0, 1.0, 3.0]]).T + oe = OrdinalEncoder(dtype=np.int32) + + msg = (r"There are missing values in features \[0\]. For OrdinalEncoder " + "to passthrough missing values, the dtype parameter must be a " + "float") + with pytest.raises(ValueError, match=msg): + oe.fit(X) + + +def test_ordinal_encoder_passthrough_missing_values_float(): + """Test ordinal encoder with nan on float dtypes.""" + + X = np.array([[np.nan, 3.0, 1.0, 3.0]], dtype=np.float64).T + oe = OrdinalEncoder().fit(X) + + assert len(oe.categories_) == 1 + assert_allclose(oe.categories_[0], [1.0, 3.0, np.nan]) + + X_trans = oe.transform(X) + assert_allclose(X_trans, [[np.nan], [1.0], [0.0], [1.0]]) + + X_inverse = oe.inverse_transform(X_trans) + assert_allclose(X_inverse, X) + + [email protected]('pd_nan_type', ['pd.NA', 'np.nan']) +def test_ordinal_encoder_missing_value_support_pandas_categorical(pd_nan_type): + """Check ordinal encoder is compatible with pandas.""" + # checks pandas dataframe with categorical features + if pd_nan_type == 'pd.NA': + # pd.NA is in pandas 1.0 + pd = pytest.importorskip('pandas', minversion="1.0") + pd_missing_value = pd.NA + else: # np.nan + pd = pytest.importorskip('pandas') + pd_missing_value = np.nan + + df = pd.DataFrame({ + 'col1': pd.Series(['c', 'a', pd_missing_value, 'b', 'a'], + dtype='category'), + }) + + oe = OrdinalEncoder().fit(df) + assert len(oe.categories_) == 1 + assert_array_equal(oe.categories_[0][:3], ['a', 'b', 'c']) + assert np.isnan(oe.categories_[0][-1]) + + df_trans = oe.transform(df) + + assert_allclose(df_trans, [[2.0], [0.0], [np.nan], [1.0], [0.0]]) + + X_inverse = oe.inverse_transform(df_trans) + assert X_inverse.shape == (5, 1) + assert_array_equal(X_inverse[:2, 0], ['c', 'a']) + assert_array_equal(X_inverse[3:, 0], ['b', 'a']) + assert np.isnan(X_inverse[2, 0]) + + [email protected]("X, X2, cats, cat_dtype", [ + ((np.array([['a', np.nan]], dtype=object).T, + np.array([['a', 'b']], dtype=object).T, + [np.array(['a', np.nan, 'd'], dtype=object)], np.object_)), + ((np.array([['a', np.nan]], dtype=object).T, + np.array([['a', 'b']], dtype=object).T, + [np.array(['a', np.nan, 'd'], dtype=object)], np.object_)), + ((np.array([[2.0, np.nan]], dtype=np.float64).T, + np.array([[3.0]], dtype=np.float64).T, + [np.array([2.0, 4.0, np.nan])], np.float64)), + ], ids=['object-None-missing-value', 'object-nan-missing_value', + 'numeric-missing-value']) +def test_ordinal_encoder_specified_categories_missing_passthrough( + X, X2, cats, cat_dtype): + """Test ordinal encoder for specified categories.""" + oe = OrdinalEncoder(categories=cats) + exp = np.array([[0.], [np.nan]]) + assert_array_equal(oe.fit_transform(X), exp) + # manually specified categories should have same dtype as + # the data when coerced from lists + assert oe.categories_[0].dtype == cat_dtype + + # when specifying categories manually, unknown categories should already + # raise when fitting + oe = OrdinalEncoder(categories=cats) + with pytest.raises(ValueError, match="Found unknown categories"): + oe.fit(X2) + + [email protected]("X, expected_X_trans, X_test", [ + (np.array([[1.0, np.nan, 3.0]]).T, + np.array([[0.0, np.nan, 1.0]]).T, + np.array([[4.0]])), + (np.array([[1.0, 4.0, 3.0]]).T, + np.array([[0.0, 2.0, 1.0]]).T, + np.array([[np.nan]])), + (np.array([['c', np.nan, 'b']], dtype=object).T, + np.array([[1.0, np.nan, 0.0]]).T, + np.array([['d']], dtype=object)), + (np.array([['c', 'a', 'b']], dtype=object).T, + np.array([[2.0, 0.0, 1.0]]).T, + np.array([[np.nan]], dtype=object)), +]) +def test_ordinal_encoder_handle_missing_and_unknown( + X, expected_X_trans, X_test +): + """Test the interaction between missing values and handle_unknown""" + + oe = OrdinalEncoder(handle_unknown="use_encoded_value", + unknown_value=-1) + + X_trans = oe.fit_transform(X) + assert_allclose(X_trans, expected_X_trans) + + assert_allclose(oe.transform(X_test), [[-1.0]])
[ { "path": "doc/modules/preprocessing.rst", "old_path": "a/doc/modules/preprocessing.rst", "new_path": "b/doc/modules/preprocessing.rst", "metadata": "diff --git a/doc/modules/preprocessing.rst b/doc/modules/preprocessing.rst\nindex e1b4c5599c3b5..b87971ec4ae5a 100644\n--- a/doc/modules/preprocessing.rst\n+++ b/doc/modules/preprocessing.rst\n@@ -482,6 +482,17 @@ scikit-learn estimators, as these expect continuous input, and would interpret\n the categories as being ordered, which is often not desired (i.e. the set of\n browsers was ordered arbitrarily).\n \n+:class:`OrdinalEncoder` will also passthrough missing values that are\n+indicated by `np.nan`.\n+\n+ >>> enc = preprocessing.OrdinalEncoder()\n+ >>> X = [['male'], ['female'], [np.nan], ['female']]\n+ >>> enc.fit_transform(X)\n+ array([[ 1.],\n+ [ 0.],\n+ [nan],\n+ [ 0.]])\n+\n Another possibility to convert categorical features to features that can be used\n with scikit-learn estimators is to use a one-of-K, also known as one-hot or\n dummy encoding.\n" }, { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 25e0b369bebd3..6a565b8d5e21b 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -123,6 +123,12 @@ Changelog\n not corresponding to their objective. :pr:`19172` by\n :user:`Mathurin Massias <mathurinm>`\n \n+:mod:`sklearn.preprocessing`\n+............................\n+\n+- |Feature| :class:`preprocessing.OrdinalEncoder` supports passing through\n+ missing values by default. :pr:`19069` by `Thomas Fan`_.\n+\n - |API|: The parameter ``normalize`` of :class:`linear_model.LinearRegression`\n is deprecated and will be removed in 1.2.\n Motivation for this deprecation: ``normalize`` parameter did not take any\n" } ]
1.00
5c246225ddf130f1eee398e889e4c2a19b5f1791
[ "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names_unicode", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[mixed-float-nan]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse_if_binary", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_pandas", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder[mixed]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_missing_value_support_pandas", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[int32-float32]", "sklearn/preprocessing/tests/test_encoders.py::test_X_is_not_1D[X1-fit_transform]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_missing_value_support_pandas_categorical[pd.NA]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categories[numeric]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse_transform_raise_error_with_unknown[X1-X_trans1-False]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_unicode_categories[dataframe-U-O]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object-string-nan]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse[None-True]", "sklearn/preprocessing/tests/test_encoders.py::test_encoder_dtypes_pandas", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype_pandas[float32]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_missing_values_get_feature_names[None]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_unicode_categories[array-O-U]", "sklearn/preprocessing/tests/test_encoders.py::test_encoder_dtypes", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_handle_unknown", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[if_binary-if_binary]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_unicode_categories[dataframe-O-U]", "sklearn/preprocessing/tests/test_encoders.py::test_invalid_drop_length[drop1]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_set_params", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_handle_unknown_strings", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_unicode_categories[array-U-O]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_not_fitted", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_manual[None]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[mixed-None]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse_transform_raise_error_with_unknown[X0-X_trans0-False]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[numeric]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_inverse", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_unicode_categories[list-U-U]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_invalid_params[X_fit2-params2-Wrong input for parameter `drop`]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_missing_values_get_feature_names[nan]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categories[missing-float]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names_drop[first]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder[object]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categories[missing-float-nan-object]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_manual[nan0]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_unicode_categories[dataframe-O-O]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse[first-True]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_raise_categories_shape", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_unicode_categories[list-O-U]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categories[object]", "sklearn/preprocessing/tests/test_encoders.py::test_invalid_drop_length[drop0]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype_pandas[int32]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_unsorted_categories", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object-nan-and-None]", "sklearn/preprocessing/tests/test_encoders.py::test_X_is_not_1D_pandas[fit_transform]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_invalid_params[X_fit3-params3-The following categories were supposed]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories_mixed_columns", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_unicode_categories[list-O-O]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[float32-float32]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categories[mixed]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_diff_n_features", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[float64-float64]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_nan_non_float_dtype", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[object]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[first-None]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[float64-float32]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[int32-float64]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse[first-False]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_specified_categories[numeric]", "sklearn/preprocessing/tests/test_encoders.py::test_categories[first-sparse]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[int32-int32]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_numeric[float]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[mixed-None-nan]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object-string]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_numeric[int]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_has_categorical_tags[OrdinalEncoder]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_equals_if_binary", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse_transform_raise_error_with_unknown[X0-X_trans0-True]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[None-None]", "sklearn/preprocessing/tests/test_encoders.py::test_X_is_not_1D[X0-fit_transform]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_warning", "sklearn/preprocessing/tests/test_encoders.py::test_X_is_not_1D[X0-fit]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[numeric]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_unicode_categories[array-U-U]", "sklearn/preprocessing/tests/test_encoders.py::test_categories[first-dense]", "sklearn/preprocessing/tests/test_encoders.py::test_X_is_not_1D_pandas[fit]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_unicode_categories[dataframe-U-U]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object-None-and-nan]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_invalid_params[X_fit0-params0-Wrong input for parameter `drop`]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[first-first]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_raise[params4-ValueError-handle_unknown should be either 'error' or 'use_encoded_value', got ignore.]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names_drop[manual]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_raise[params0-TypeError-unknown_value should be an integer or np.nan when handle_unknown is 'use_encoded_value', got None.]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[float32-int32]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_raise[params1-TypeError-unknown_value should only be set when handle_unknown is 'use_encoded_value', got -2.]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names_drop[binary]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_missing_value_support_pandas_categorical[np.nan]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_specified_categories[object-string-cat]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_nan", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_unicode_categories[array-O-O]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[mixed-None-float-nan]", "sklearn/preprocessing/tests/test_encoders.py::test_categories[manual-dense]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[None-if_binary]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_raise[params3-ValueError-The used value for unknown_value (1) is one of the values already used for encoding the seen categories.]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_sparse_dense", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object-string-none]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_invalid_params[X_fit1-params1-`handle_unknown` must be 'error']", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[if_binary-first]", "sklearn/preprocessing/tests/test_encoders.py::test_categories[manual-sparse]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_has_categorical_tags[OneHotEncoder]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_unicode_categories[list-U-O]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[mixed-nan]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder[numeric]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categories[string]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_specified_categories[object]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[if_binary-None]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse[None-False]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_raise[params2-TypeError-unknown_value should be an integer or np.nan when handle_unknown is 'use_encoded_value', got bla.]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[None-first]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[first-if_binary]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype_pandas[float64]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[float64-int32]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_string", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_manual[nan1]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categories[missing-np.nan-object]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse_transform_raise_error_with_unknown[X1-X_trans1-True]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[mixed]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[float32-float64]", "sklearn/preprocessing/tests/test_encoders.py::test_X_is_not_1D[X1-fit]" ]
[ "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_missing_value_support_pandas_categorical[np.nan]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_specified_categories_missing_passthrough[object-None-missing-value]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_specified_categories_missing_passthrough[numeric-missing-value]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_specified_categories_missing_passthrough[object-nan-missing_value]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_missing_and_unknown[X3-expected_X_trans3-X_test3]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_passthrough_missing_values_float_errors_dtype", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_missing_and_unknown[X1-expected_X_trans1-X_test1]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_passthrough_missing_values_float", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_missing_and_unknown[X0-expected_X_trans0-X_test0]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_missing_value_support_pandas_categorical[pd.NA]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_missing_and_unknown[X2-expected_X_trans2-X_test2]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/modules/preprocessing.rst", "old_path": "a/doc/modules/preprocessing.rst", "new_path": "b/doc/modules/preprocessing.rst", "metadata": "diff --git a/doc/modules/preprocessing.rst b/doc/modules/preprocessing.rst\nindex e1b4c5599c3b5..b87971ec4ae5a 100644\n--- a/doc/modules/preprocessing.rst\n+++ b/doc/modules/preprocessing.rst\n@@ -482,6 +482,17 @@ scikit-learn estimators, as these expect continuous input, and would interpret\n the categories as being ordered, which is often not desired (i.e. the set of\n browsers was ordered arbitrarily).\n \n+:class:`OrdinalEncoder` will also passthrough missing values that are\n+indicated by `np.nan`.\n+\n+ >>> enc = preprocessing.OrdinalEncoder()\n+ >>> X = [['male'], ['female'], [np.nan], ['female']]\n+ >>> enc.fit_transform(X)\n+ array([[ 1.],\n+ [ 0.],\n+ [nan],\n+ [ 0.]])\n+\n Another possibility to convert categorical features to features that can be used\n with scikit-learn estimators is to use a one-of-K, also known as one-hot or\n dummy encoding.\n" }, { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 25e0b369bebd3..6a565b8d5e21b 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -123,6 +123,12 @@ Changelog\n not corresponding to their objective. :pr:`<PRID>` by\n :user:`<NAME>`\n \n+:mod:`sklearn.preprocessing`\n+............................\n+\n+- |Feature| :class:`preprocessing.OrdinalEncoder` supports passing through\n+ missing values by default. :pr:`<PRID>` by `<NAME>`_.\n+\n - |API|: The parameter ``normalize`` of :class:`linear_model.LinearRegression`\n is deprecated and will be removed in 1.2.\n Motivation for this deprecation: ``normalize`` parameter did not take any\n" } ]
diff --git a/doc/modules/preprocessing.rst b/doc/modules/preprocessing.rst index e1b4c5599c3b5..b87971ec4ae5a 100644 --- a/doc/modules/preprocessing.rst +++ b/doc/modules/preprocessing.rst @@ -482,6 +482,17 @@ scikit-learn estimators, as these expect continuous input, and would interpret the categories as being ordered, which is often not desired (i.e. the set of browsers was ordered arbitrarily). +:class:`OrdinalEncoder` will also passthrough missing values that are +indicated by `np.nan`. + + >>> enc = preprocessing.OrdinalEncoder() + >>> X = [['male'], ['female'], [np.nan], ['female']] + >>> enc.fit_transform(X) + array([[ 1.], + [ 0.], + [nan], + [ 0.]]) + Another possibility to convert categorical features to features that can be used with scikit-learn estimators is to use a one-of-K, also known as one-hot or dummy encoding. diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index 25e0b369bebd3..6a565b8d5e21b 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -123,6 +123,12 @@ Changelog not corresponding to their objective. :pr:`<PRID>` by :user:`<NAME>` +:mod:`sklearn.preprocessing` +............................ + +- |Feature| :class:`preprocessing.OrdinalEncoder` supports passing through + missing values by default. :pr:`<PRID>` by `<NAME>`_. + - |API|: The parameter ``normalize`` of :class:`linear_model.LinearRegression` is deprecated and will be removed in 1.2. Motivation for this deprecation: ``normalize`` parameter did not take any
scikit-learn/scikit-learn
scikit-learn__scikit-learn-19041
https://github.com/scikit-learn/scikit-learn/pull/19041
diff --git a/doc/modules/preprocessing.rst b/doc/modules/preprocessing.rst index b87971ec4ae5a..cdde7479b1a4f 100644 --- a/doc/modules/preprocessing.rst +++ b/doc/modules/preprocessing.rst @@ -560,9 +560,7 @@ parameter allows the user to specify a category for each feature to be dropped. This is useful to avoid co-linearity in the input matrix in some classifiers. Such functionality is useful, for example, when using non-regularized regression (:class:`LinearRegression <sklearn.linear_model.LinearRegression>`), -since co-linearity would cause the covariance matrix to be non-invertible. -When this parameter is not None, ``handle_unknown`` must be set to -``error``:: +since co-linearity would cause the covariance matrix to be non-invertible:: >>> X = [['male', 'from US', 'uses Safari'], ... ['female', 'from Europe', 'uses Firefox']] @@ -591,6 +589,30 @@ In the transformed `X`, the first column is the encoding of the feature with categories "male"/"female", while the remaining 6 columns is the encoding of the 2 features with respectively 3 categories each. +When `handle_unknown='ignore'` and `drop` is not None, unknown categories will +be encoded as all zeros:: + + >>> drop_enc = preprocessing.OneHotEncoder(drop='first', + ... handle_unknown='ignore').fit(X) + >>> X_test = [['unknown', 'America', 'IE']] + >>> drop_enc.transform(X_test).toarray() + array([[0., 0., 0., 0., 0.]]) + +All the categories in `X_test` are unknown during transform and will be mapped +to all zeros. This means that unknown categories will have the same mapping as +the dropped category. :meth`OneHotEncoder.inverse_transform` will map all zeros +to the dropped category if a category is dropped and `None` if a category is +not dropped:: + + >>> drop_enc = preprocessing.OneHotEncoder(drop='if_binary', sparse=False, + ... handle_unknown='ignore').fit(X) + >>> X_test = [['unknown', 'America', 'IE']] + >>> X_trans = drop_enc.transform(X_test) + >>> X_trans + array([[0., 0., 0., 0., 0., 0., 0.]]) + >>> drop_enc.inverse_transform(X_trans) + array([['female', None, None]], dtype=object) + :class:`OneHotEncoder` supports categorical features with missing values by considering the missing values as an additional category:: diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index 2b108d2f0e197..2aaecb6d9b438 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -79,6 +79,13 @@ Changelog :mod:`sklearn.cluster` ...................... +:mod:`sklearn.preprocessing` +............................ + +- |Feature| :class:`preprocessing.OneHotEncoder` now supports + `handle_unknown='ignore'` and dropping categories. :pr:`19041` by + `Thomas Fan`_. + - |Efficiency| The "k-means++" initialization of :class:`cluster.KMeans` and :class:`cluster.MiniBatchKMeans` is now faster, especially in multicore settings. :pr:`19002` by :user:`Jon Crall <Erotemic>` and diff --git a/sklearn/preprocessing/_encoders.py b/sklearn/preprocessing/_encoders.py index 043f9fc40ef53..4344e010bba1a 100644 --- a/sklearn/preprocessing/_encoders.py +++ b/sklearn/preprocessing/_encoders.py @@ -2,6 +2,7 @@ # Joris Van den Bossche <[email protected]> # License: BSD 3 clause +import warnings import numpy as np from scipy import sparse import numbers @@ -110,7 +111,8 @@ def _fit(self, X, handle_unknown='error', force_all_finite=True): raise ValueError(msg) self.categories_.append(cats) - def _transform(self, X, handle_unknown='error', force_all_finite=True): + def _transform(self, X, handle_unknown='error', force_all_finite=True, + warn_on_unknown=False): X_list, n_samples, n_features = self._check_X( X, force_all_finite=force_all_finite) @@ -125,6 +127,7 @@ def _transform(self, X, handle_unknown='error', force_all_finite=True): .format(len(self.categories_,), n_features) ) + columns_with_unknown = [] for i in range(n_features): Xi = X_list[i] diff, valid_mask = _check_unknown(Xi, self.categories_[i], @@ -136,6 +139,8 @@ def _transform(self, X, handle_unknown='error', force_all_finite=True): " during transform".format(diff, i)) raise ValueError(msg) else: + if warn_on_unknown: + columns_with_unknown.append(i) # Set the problematic rows to an acceptable value and # continue `The rows are marked `X_mask` and will be # removed later. @@ -153,6 +158,11 @@ def _transform(self, X, handle_unknown='error', force_all_finite=True): # already called above. X_int[:, i] = _encode(Xi, uniques=self.categories_[i], check_unknown=False) + if columns_with_unknown: + warnings.warn("Found unknown categories in columns " + f"{columns_with_unknown} during transform. These " + "unknown categories will be encoded as all zeros", + UserWarning) return X_int, X_mask @@ -327,14 +337,6 @@ def _validate_keywords(self): msg = ("handle_unknown should be either 'error' or 'ignore', " "got {0}.".format(self.handle_unknown)) raise ValueError(msg) - # If we have both dropped columns and ignored unknown - # values, there will be ambiguous cells. This creates difficulties - # in interpreting the model. - if self.drop is not None and self.handle_unknown != 'error': - raise ValueError( - "`handle_unknown` must be 'error' when the drop parameter is " - "specified, as both would create categories that are all " - "zero.") def _compute_drop_idx(self): if self.drop is None: @@ -459,8 +461,11 @@ def transform(self, X): """ check_is_fitted(self) # validation of X happens in _check_X called by _transform + warn_on_unknown = (self.handle_unknown == "ignore" + and self.drop is not None) X_int, X_mask = self._transform(X, handle_unknown=self.handle_unknown, - force_all_finite='allow-nan') + force_all_finite='allow-nan', + warn_on_unknown=warn_on_unknown) n_samples, n_features = X_int.shape @@ -509,8 +514,10 @@ def inverse_transform(self, X): """ Convert the data back to the original representation. - In case unknown categories are encountered (all zeros in the - one-hot encoding), ``None`` is used to represent this category. + When unknown categories are encountered (all zeros in the + one-hot encoding), ``None`` is used to represent this category. If the + feature with the unknown category has a dropped caregory, the dropped + category will be its inverse. Parameters ---------- @@ -571,7 +578,14 @@ def inverse_transform(self, X): unknown = np.asarray(sub.sum(axis=1) == 0).flatten() # ignored unknown categories: we have a row of all zero if unknown.any(): - found_unknown[i] = unknown + # if categories were dropped then unknown categories will + # be mapped to the dropped category + if self.drop_idx_ is None or self.drop_idx_[i] is None: + found_unknown[i] = unknown + else: + X_tr[unknown, i] = self.categories_[i][ + self.drop_idx_[i] + ] else: dropped = np.asarray(sub.sum(axis=1) == 0).flatten() if dropped.any():
diff --git a/sklearn/preprocessing/tests/test_encoders.py b/sklearn/preprocessing/tests/test_encoders.py index b1eff0cad21e0..eb776c4c25267 100644 --- a/sklearn/preprocessing/tests/test_encoders.py +++ b/sklearn/preprocessing/tests/test_encoders.py @@ -775,8 +775,6 @@ def test_one_hot_encoder_drop_manual(missing_value): "X_fit, params, err_msg", [([["Male"], ["Female"]], {'drop': 'second'}, "Wrong input for parameter `drop`"), - ([["Male"], ["Female"]], {'drop': 'first', 'handle_unknown': 'ignore'}, - "`handle_unknown` must be 'error'"), ([['abc', 2, 55], ['def', 1, 55], ['def', 3, 59]], {'drop': np.asarray('b', dtype=object)}, "Wrong input for parameter `drop`"), @@ -914,6 +912,87 @@ def test_ohe_missing_value_support_pandas_categorical(pd_nan_type): assert np.isnan(ohe.categories_[0][-1]) +def test_ohe_drop_first_handle_unknown_ignore_warns(): + """Check drop='first' and handle_unknown='ignore' during transform.""" + X = [['a', 0], ['b', 2], ['b', 1]] + + ohe = OneHotEncoder(drop='first', sparse=False, handle_unknown='ignore') + X_trans = ohe.fit_transform(X) + + X_expected = np.array([ + [0, 0, 0], + [1, 0, 1], + [1, 1, 0], + ]) + assert_allclose(X_trans, X_expected) + + # Both categories are unknown + X_test = [['c', 3]] + X_expected = np.array([[0, 0, 0]]) + + warn_msg = (r"Found unknown categories in columns \[0, 1\] during " + "transform. These unknown categories will be encoded as all " + "zeros") + with pytest.warns(UserWarning, match=warn_msg): + X_trans = ohe.transform(X_test) + assert_allclose(X_trans, X_expected) + + # inverse_transform maps to None + X_inv = ohe.inverse_transform(X_expected) + assert_array_equal(X_inv, np.array([['a', 0]], dtype=object)) + + +def test_ohe_drop_if_binary_handle_unknown_ignore_warns(): + """Check drop='if_binary' and handle_unknown='ignore' during transform.""" + X = [['a', 0], ['b', 2], ['b', 1]] + + ohe = OneHotEncoder(drop='if_binary', sparse=False, + handle_unknown='ignore') + X_trans = ohe.fit_transform(X) + + X_expected = np.array([ + [0, 1, 0, 0], + [1, 0, 0, 1], + [1, 0, 1, 0], + ]) + assert_allclose(X_trans, X_expected) + + # Both categories are unknown + X_test = [['c', 3]] + X_expected = np.array([[0, 0, 0, 0]]) + + warn_msg = (r"Found unknown categories in columns \[0, 1\] during " + "transform. These unknown categories will be encoded as all " + "zeros") + with pytest.warns(UserWarning, match=warn_msg): + X_trans = ohe.transform(X_test) + assert_allclose(X_trans, X_expected) + + # inverse_transform maps to None + X_inv = ohe.inverse_transform(X_expected) + assert_array_equal(X_inv, np.array([['a', None]], dtype=object)) + + +def test_ohe_drop_first_explicit_categories(): + """Check drop='first' and handle_unknown='ignore' during fit with + categories passed in.""" + + X = [['a', 0], ['b', 2], ['b', 1]] + + ohe = OneHotEncoder(drop='first', sparse=False, handle_unknown='ignore', + categories=[['b', 'a'], [1, 2]]) + ohe.fit(X) + + X_test = [['c', 1]] + X_expected = np.array([[0, 0]]) + + warn_msg = (r"Found unknown categories in columns \[0\] during transform. " + r"These unknown categories will be encoded as all zeros") + with pytest.warns(UserWarning, match=warn_msg): + X_trans = ohe.transform(X_test) + assert_allclose(X_trans, X_expected) + + def test_ordinal_encoder_passthrough_missing_values_float_errors_dtype(): """Test ordinal encoder with nan passthrough fails when dtype=np.int32."""
[ { "path": "doc/modules/preprocessing.rst", "old_path": "a/doc/modules/preprocessing.rst", "new_path": "b/doc/modules/preprocessing.rst", "metadata": "diff --git a/doc/modules/preprocessing.rst b/doc/modules/preprocessing.rst\nindex b87971ec4ae5a..cdde7479b1a4f 100644\n--- a/doc/modules/preprocessing.rst\n+++ b/doc/modules/preprocessing.rst\n@@ -560,9 +560,7 @@ parameter allows the user to specify a category for each feature to be dropped.\n This is useful to avoid co-linearity in the input matrix in some classifiers.\n Such functionality is useful, for example, when using non-regularized\n regression (:class:`LinearRegression <sklearn.linear_model.LinearRegression>`),\n-since co-linearity would cause the covariance matrix to be non-invertible.\n-When this parameter is not None, ``handle_unknown`` must be set to\n-``error``::\n+since co-linearity would cause the covariance matrix to be non-invertible::\n \n >>> X = [['male', 'from US', 'uses Safari'],\n ... ['female', 'from Europe', 'uses Firefox']]\n@@ -591,6 +589,30 @@ In the transformed `X`, the first column is the encoding of the feature with\n categories \"male\"/\"female\", while the remaining 6 columns is the encoding of\n the 2 features with respectively 3 categories each.\n \n+When `handle_unknown='ignore'` and `drop` is not None, unknown categories will\n+be encoded as all zeros::\n+\n+ >>> drop_enc = preprocessing.OneHotEncoder(drop='first',\n+ ... handle_unknown='ignore').fit(X)\n+ >>> X_test = [['unknown', 'America', 'IE']]\n+ >>> drop_enc.transform(X_test).toarray()\n+ array([[0., 0., 0., 0., 0.]])\n+\n+All the categories in `X_test` are unknown during transform and will be mapped\n+to all zeros. This means that unknown categories will have the same mapping as\n+the dropped category. :meth`OneHotEncoder.inverse_transform` will map all zeros\n+to the dropped category if a category is dropped and `None` if a category is\n+not dropped::\n+\n+ >>> drop_enc = preprocessing.OneHotEncoder(drop='if_binary', sparse=False,\n+ ... handle_unknown='ignore').fit(X)\n+ >>> X_test = [['unknown', 'America', 'IE']]\n+ >>> X_trans = drop_enc.transform(X_test)\n+ >>> X_trans\n+ array([[0., 0., 0., 0., 0., 0., 0.]])\n+ >>> drop_enc.inverse_transform(X_trans)\n+ array([['female', None, None]], dtype=object)\n+\n :class:`OneHotEncoder` supports categorical features with missing values by\n considering the missing values as an additional category::\n \n" }, { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 2b108d2f0e197..2aaecb6d9b438 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -79,6 +79,13 @@ Changelog\n :mod:`sklearn.cluster`\n ......................\n \n+:mod:`sklearn.preprocessing`\n+............................\n+\n+- |Feature| :class:`preprocessing.OneHotEncoder` now supports\n+ `handle_unknown='ignore'` and dropping categories. :pr:`19041` by\n+ `Thomas Fan`_.\n+\n - |Efficiency| The \"k-means++\" initialization of :class:`cluster.KMeans` and\n :class:`cluster.MiniBatchKMeans` is now faster, especially in multicore\n settings. :pr:`19002` by :user:`Jon Crall <Erotemic>` and\n" } ]
1.00
57d3668f2a1fea69dafc2e68208576a56812cd45
[ "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names_unicode", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[mixed-float-nan]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse_if_binary", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_pandas", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder[mixed]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_missing_value_support_pandas", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[int32-float32]", "sklearn/preprocessing/tests/test_encoders.py::test_X_is_not_1D[X1-fit_transform]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_missing_value_support_pandas_categorical[pd.NA]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categories[numeric]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse_transform_raise_error_with_unknown[X1-X_trans1-False]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_unicode_categories[dataframe-U-O]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_missing_value_support_pandas_categorical[np.nan]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object-string-nan]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse[None-True]", "sklearn/preprocessing/tests/test_encoders.py::test_encoder_dtypes_pandas", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype_pandas[float32]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_missing_values_get_feature_names[None]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_unicode_categories[array-O-U]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_specified_categories_missing_passthrough[object-None-missing-value]", "sklearn/preprocessing/tests/test_encoders.py::test_encoder_dtypes", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_handle_unknown", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[if_binary-if_binary]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_unicode_categories[dataframe-O-U]", "sklearn/preprocessing/tests/test_encoders.py::test_invalid_drop_length[drop1]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_set_params", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_specified_categories_missing_passthrough[numeric-missing-value]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_handle_unknown_strings", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_unicode_categories[array-U-O]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_not_fitted", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_manual[None]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[mixed-None]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse_transform_raise_error_with_unknown[X0-X_trans0-False]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[numeric]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_inverse", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_unicode_categories[list-U-U]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_missing_values_get_feature_names[nan]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categories[missing-float]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names_drop[first]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder[object]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_specified_categories_missing_passthrough[object-nan-missing_value]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categories[missing-float-nan-object]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_manual[nan0]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_unicode_categories[dataframe-O-O]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse[first-True]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_raise_categories_shape", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_unicode_categories[list-O-U]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categories[object]", "sklearn/preprocessing/tests/test_encoders.py::test_invalid_drop_length[drop0]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype_pandas[int32]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_unsorted_categories", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object-nan-and-None]", "sklearn/preprocessing/tests/test_encoders.py::test_X_is_not_1D_pandas[fit_transform]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories_mixed_columns", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_unicode_categories[list-O-O]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[float32-float32]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categories[mixed]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_diff_n_features", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[float64-float64]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_nan_non_float_dtype", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[object]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[first-None]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[float64-float32]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_missing_and_unknown[X3-expected_X_trans3-X_test3]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[int32-float64]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse[first-False]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_specified_categories[numeric]", "sklearn/preprocessing/tests/test_encoders.py::test_categories[first-sparse]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[int32-int32]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_numeric[float]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[mixed-None-nan]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object-string]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_numeric[int]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_has_categorical_tags[OrdinalEncoder]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_passthrough_missing_values_float_errors_dtype", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_equals_if_binary", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse_transform_raise_error_with_unknown[X0-X_trans0-True]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[None-None]", "sklearn/preprocessing/tests/test_encoders.py::test_X_is_not_1D[X0-fit_transform]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_warning", "sklearn/preprocessing/tests/test_encoders.py::test_X_is_not_1D[X0-fit]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[numeric]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_unicode_categories[array-U-U]", "sklearn/preprocessing/tests/test_encoders.py::test_categories[first-dense]", "sklearn/preprocessing/tests/test_encoders.py::test_X_is_not_1D_pandas[fit]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_unicode_categories[dataframe-U-U]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object-None-and-nan]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_invalid_params[X_fit0-params0-Wrong input for parameter `drop`]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_invalid_params[X_fit2-params2-The following categories were supposed]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[first-first]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_raise[params4-ValueError-handle_unknown should be either 'error' or 'use_encoded_value', got ignore.]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names_drop[manual]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_raise[params0-TypeError-unknown_value should be an integer or np.nan when handle_unknown is 'use_encoded_value', got None.]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[float32-int32]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_raise[params1-TypeError-unknown_value should only be set when handle_unknown is 'use_encoded_value', got -2.]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names_drop[binary]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_missing_value_support_pandas_categorical[np.nan]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_specified_categories[object-string-cat]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_nan", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_unicode_categories[array-O-O]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_invalid_params[X_fit1-params1-Wrong input for parameter `drop`]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[mixed-None-float-nan]", "sklearn/preprocessing/tests/test_encoders.py::test_categories[manual-dense]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_missing_and_unknown[X1-expected_X_trans1-X_test1]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_passthrough_missing_values_float", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[None-if_binary]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_raise[params3-ValueError-The used value for unknown_value (1) is one of the values already used for encoding the seen categories.]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_sparse_dense", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object-string-none]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[if_binary-first]", "sklearn/preprocessing/tests/test_encoders.py::test_categories[manual-sparse]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_has_categorical_tags[OneHotEncoder]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_unicode_categories[list-U-O]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_missing_and_unknown[X0-expected_X_trans0-X_test0]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[mixed-nan]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder[numeric]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categories[string]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_specified_categories[object]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[if_binary-None]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse[None-False]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_raise[params2-TypeError-unknown_value should be an integer or np.nan when handle_unknown is 'use_encoded_value', got bla.]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[None-first]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_missing_value_support_pandas_categorical[pd.NA]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[first-if_binary]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype_pandas[float64]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[float64-int32]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_string", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_manual[nan1]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categories[missing-np.nan-object]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse_transform_raise_error_with_unknown[X1-X_trans1-True]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_missing_and_unknown[X2-expected_X_trans2-X_test2]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[mixed]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[float32-float64]", "sklearn/preprocessing/tests/test_encoders.py::test_X_is_not_1D[X1-fit]" ]
[ "sklearn/preprocessing/tests/test_encoders.py::test_ohe_drop_if_binary_handle_unknown_ignore_warns", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_drop_first_explicit_categories", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_drop_first_handle_unknown_ignore_warns" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/modules/preprocessing.rst", "old_path": "a/doc/modules/preprocessing.rst", "new_path": "b/doc/modules/preprocessing.rst", "metadata": "diff --git a/doc/modules/preprocessing.rst b/doc/modules/preprocessing.rst\nindex b87971ec4ae5a..cdde7479b1a4f 100644\n--- a/doc/modules/preprocessing.rst\n+++ b/doc/modules/preprocessing.rst\n@@ -560,9 +560,7 @@ parameter allows the user to specify a category for each feature to be dropped.\n This is useful to avoid co-linearity in the input matrix in some classifiers.\n Such functionality is useful, for example, when using non-regularized\n regression (:class:`LinearRegression <sklearn.linear_model.LinearRegression>`),\n-since co-linearity would cause the covariance matrix to be non-invertible.\n-When this parameter is not None, ``handle_unknown`` must be set to\n-``error``::\n+since co-linearity would cause the covariance matrix to be non-invertible::\n \n >>> X = [['male', 'from US', 'uses Safari'],\n ... ['female', 'from Europe', 'uses Firefox']]\n@@ -591,6 +589,30 @@ In the transformed `X`, the first column is the encoding of the feature with\n categories \"male\"/\"female\", while the remaining 6 columns is the encoding of\n the 2 features with respectively 3 categories each.\n \n+When `handle_unknown='ignore'` and `drop` is not None, unknown categories will\n+be encoded as all zeros::\n+\n+ >>> drop_enc = preprocessing.OneHotEncoder(drop='first',\n+ ... handle_unknown='ignore').fit(X)\n+ >>> X_test = [['unknown', 'America', 'IE']]\n+ >>> drop_enc.transform(X_test).toarray()\n+ array([[0., 0., 0., 0., 0.]])\n+\n+All the categories in `X_test` are unknown during transform and will be mapped\n+to all zeros. This means that unknown categories will have the same mapping as\n+the dropped category. :meth`OneHotEncoder.inverse_transform` will map all zeros\n+to the dropped category if a category is dropped and `None` if a category is\n+not dropped::\n+\n+ >>> drop_enc = preprocessing.OneHotEncoder(drop='if_binary', sparse=False,\n+ ... handle_unknown='ignore').fit(X)\n+ >>> X_test = [['unknown', 'America', 'IE']]\n+ >>> X_trans = drop_enc.transform(X_test)\n+ >>> X_trans\n+ array([[0., 0., 0., 0., 0., 0., 0.]])\n+ >>> drop_enc.inverse_transform(X_trans)\n+ array([['female', None, None]], dtype=object)\n+\n :class:`OneHotEncoder` supports categorical features with missing values by\n considering the missing values as an additional category::\n \n" }, { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 2b108d2f0e197..2aaecb6d9b438 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -79,6 +79,13 @@ Changelog\n :mod:`sklearn.cluster`\n ......................\n \n+:mod:`sklearn.preprocessing`\n+............................\n+\n+- |Feature| :class:`preprocessing.OneHotEncoder` now supports\n+ `handle_unknown='ignore'` and dropping categories. :pr:`<PRID>` by\n+ `Thomas Fan`_.\n+\n - |Efficiency| The \"k-means++\" initialization of :class:`cluster.KMeans` and\n :class:`cluster.MiniBatchKMeans` is now faster, especially in multicore\n settings. :pr:`<PRID>` by :user:`<NAME>` and\n" } ]
diff --git a/doc/modules/preprocessing.rst b/doc/modules/preprocessing.rst index b87971ec4ae5a..cdde7479b1a4f 100644 --- a/doc/modules/preprocessing.rst +++ b/doc/modules/preprocessing.rst @@ -560,9 +560,7 @@ parameter allows the user to specify a category for each feature to be dropped. This is useful to avoid co-linearity in the input matrix in some classifiers. Such functionality is useful, for example, when using non-regularized regression (:class:`LinearRegression <sklearn.linear_model.LinearRegression>`), -since co-linearity would cause the covariance matrix to be non-invertible. -When this parameter is not None, ``handle_unknown`` must be set to -``error``:: +since co-linearity would cause the covariance matrix to be non-invertible:: >>> X = [['male', 'from US', 'uses Safari'], ... ['female', 'from Europe', 'uses Firefox']] @@ -591,6 +589,30 @@ In the transformed `X`, the first column is the encoding of the feature with categories "male"/"female", while the remaining 6 columns is the encoding of the 2 features with respectively 3 categories each. +When `handle_unknown='ignore'` and `drop` is not None, unknown categories will +be encoded as all zeros:: + + >>> drop_enc = preprocessing.OneHotEncoder(drop='first', + ... handle_unknown='ignore').fit(X) + >>> X_test = [['unknown', 'America', 'IE']] + >>> drop_enc.transform(X_test).toarray() + array([[0., 0., 0., 0., 0.]]) + +All the categories in `X_test` are unknown during transform and will be mapped +to all zeros. This means that unknown categories will have the same mapping as +the dropped category. :meth`OneHotEncoder.inverse_transform` will map all zeros +to the dropped category if a category is dropped and `None` if a category is +not dropped:: + + >>> drop_enc = preprocessing.OneHotEncoder(drop='if_binary', sparse=False, + ... handle_unknown='ignore').fit(X) + >>> X_test = [['unknown', 'America', 'IE']] + >>> X_trans = drop_enc.transform(X_test) + >>> X_trans + array([[0., 0., 0., 0., 0., 0., 0.]]) + >>> drop_enc.inverse_transform(X_trans) + array([['female', None, None]], dtype=object) + :class:`OneHotEncoder` supports categorical features with missing values by considering the missing values as an additional category:: diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index 2b108d2f0e197..2aaecb6d9b438 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -79,6 +79,13 @@ Changelog :mod:`sklearn.cluster` ...................... +:mod:`sklearn.preprocessing` +............................ + +- |Feature| :class:`preprocessing.OneHotEncoder` now supports + `handle_unknown='ignore'` and dropping categories. :pr:`<PRID>` by + `Thomas Fan`_. + - |Efficiency| The "k-means++" initialization of :class:`cluster.KMeans` and :class:`cluster.MiniBatchKMeans` is now faster, especially in multicore settings. :pr:`<PRID>` by :user:`<NAME>` and
scikit-learn/scikit-learn
scikit-learn__scikit-learn-18959
https://github.com/scikit-learn/scikit-learn/pull/18959
diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index 0372dcdd1fd4e..f056f3a9be2d3 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -44,6 +44,13 @@ Changelog :pr:`123456` by :user:`Joe Bloggs <joeongithub>`. where 123456 is the *pull request* number, not the issue number. +:mod:`sklearn.tree` +................... + +- |Enhancement| Add `fontname` argument in :func:`tree.export_graphviz` + for non-English characters. :pr:`18959` by :user:`Zero <Zeroto521>` + and :user:`wstates <wstates>`. + :mod:`sklearn.cluster` ...................... diff --git a/sklearn/tree/_export.py b/sklearn/tree/_export.py index 1615c8eb15028..ff29790e3699e 100644 --- a/sklearn/tree/_export.py +++ b/sklearn/tree/_export.py @@ -371,18 +371,17 @@ def __init__(self, out_file=SENTINEL, max_depth=None, feature_names=None, class_names=None, label='all', filled=False, leaves_parallel=False, impurity=True, node_ids=False, proportion=False, rotate=False, rounded=False, - special_characters=False, precision=3): + special_characters=False, precision=3, fontname='helvetica'): super().__init__( max_depth=max_depth, feature_names=feature_names, class_names=class_names, label=label, filled=filled, - impurity=impurity, - node_ids=node_ids, proportion=proportion, rotate=rotate, - rounded=rounded, - precision=precision) + impurity=impurity, node_ids=node_ids, proportion=proportion, + rotate=rotate, rounded=rounded, precision=precision) self.leaves_parallel = leaves_parallel self.out_file = out_file self.special_characters = special_characters + self.fontname = fontname # PostScript compatibility for special characters if special_characters: @@ -449,16 +448,17 @@ def head(self): self.out_file.write( ', style="%s", color="black"' % ", ".join(rounded_filled)) - if self.rounded: - self.out_file.write(', fontname=helvetica') + + self.out_file.write(', fontname="%s"' % self.fontname) self.out_file.write('] ;\n') # Specify graph & edge aesthetics if self.leaves_parallel: self.out_file.write( 'graph [ranksep=equally, splines=polyline] ;\n') - if self.rounded: - self.out_file.write('edge [fontname=helvetica] ;\n') + + self.out_file.write('edge [fontname="%s"] ;\n' % self.fontname) + if self.rotate: self.out_file.write('rankdir=LR ;\n') @@ -667,7 +667,8 @@ def export_graphviz(decision_tree, out_file=None, *, max_depth=None, feature_names=None, class_names=None, label='all', filled=False, leaves_parallel=False, impurity=True, node_ids=False, proportion=False, rotate=False, - rounded=False, special_characters=False, precision=3): + rounded=False, special_characters=False, precision=3, + fontname='helvetica'): """Export a decision tree in DOT format. This function generates a GraphViz representation of the decision tree, @@ -734,8 +735,7 @@ def export_graphviz(decision_tree, out_file=None, *, max_depth=None, When set to ``True``, orient tree left to right rather than top-down. rounded : bool, default=False - When set to ``True``, draw node boxes with rounded corners and use - Helvetica fonts instead of Times-Roman. + When set to ``True``, draw node boxes with rounded corners. special_characters : bool, default=False When set to ``False``, ignore special characters for PostScript @@ -745,6 +745,9 @@ def export_graphviz(decision_tree, out_file=None, *, max_depth=None, Number of digits of precision for floating point in the values of impurity, threshold and value attributes of each node. + fontname : str, default='helvetica' + Name of font used to render text. + Returns ------- dot_data : string @@ -784,7 +787,7 @@ def export_graphviz(decision_tree, out_file=None, *, max_depth=None, filled=filled, leaves_parallel=leaves_parallel, impurity=impurity, node_ids=node_ids, proportion=proportion, rotate=rotate, rounded=rounded, special_characters=special_characters, - precision=precision) + precision=precision, fontname=fontname) exporter.export(decision_tree) if return_string:
diff --git a/sklearn/tree/tests/test_export.py b/sklearn/tree/tests/test_export.py index a1b04e171e59a..6a7bf33b2143f 100644 --- a/sklearn/tree/tests/test_export.py +++ b/sklearn/tree/tests/test_export.py @@ -33,7 +33,8 @@ def test_graphviz_toy(): # Test export code contents1 = export_graphviz(clf, out_file=None) contents2 = 'digraph Tree {\n' \ - 'node [shape=box] ;\n' \ + 'node [shape=box, fontname="helvetica"] ;\n' \ + 'edge [fontname="helvetica"] ;\n' \ '0 [label="X[0] <= 0.0\\ngini = 0.5\\nsamples = 6\\n' \ 'value = [3, 3]"] ;\n' \ '1 [label="gini = 0.0\\nsamples = 3\\nvalue = [3, 0]"] ;\n' \ @@ -50,7 +51,8 @@ def test_graphviz_toy(): contents1 = export_graphviz(clf, feature_names=["feature0", "feature1"], out_file=None) contents2 = 'digraph Tree {\n' \ - 'node [shape=box] ;\n' \ + 'node [shape=box, fontname="helvetica"] ;\n' \ + 'edge [fontname="helvetica"] ;\n' \ '0 [label="feature0 <= 0.0\\ngini = 0.5\\nsamples = 6\\n' \ 'value = [3, 3]"] ;\n' \ '1 [label="gini = 0.0\\nsamples = 3\\nvalue = [3, 0]"] ;\n' \ @@ -66,7 +68,8 @@ def test_graphviz_toy(): # Test with class_names contents1 = export_graphviz(clf, class_names=["yes", "no"], out_file=None) contents2 = 'digraph Tree {\n' \ - 'node [shape=box] ;\n' \ + 'node [shape=box, fontname="helvetica"] ;\n' \ + 'edge [fontname="helvetica"] ;\n' \ '0 [label="X[0] <= 0.0\\ngini = 0.5\\nsamples = 6\\n' \ 'value = [3, 3]\\nclass = yes"] ;\n' \ '1 [label="gini = 0.0\\nsamples = 3\\nvalue = [3, 0]\\n' \ @@ -84,11 +87,11 @@ def test_graphviz_toy(): # Test plot_options contents1 = export_graphviz(clf, filled=True, impurity=False, proportion=True, special_characters=True, - rounded=True, out_file=None) + rounded=True, out_file=None, fontname="sans") contents2 = 'digraph Tree {\n' \ 'node [shape=box, style="filled, rounded", color="black", ' \ - 'fontname=helvetica] ;\n' \ - 'edge [fontname=helvetica] ;\n' \ + 'fontname="sans"] ;\n' \ + 'edge [fontname="sans"] ;\n' \ '0 [label=<X<SUB>0</SUB> &le; 0.0<br/>samples = 100.0%<br/>' \ 'value = [0.5, 0.5]>, fillcolor="#ffffff"] ;\n' \ '1 [label=<samples = 50.0%<br/>value = [1.0, 0.0]>, ' \ @@ -107,7 +110,8 @@ def test_graphviz_toy(): contents1 = export_graphviz(clf, max_depth=0, class_names=True, out_file=None) contents2 = 'digraph Tree {\n' \ - 'node [shape=box] ;\n' \ + 'node [shape=box, fontname="helvetica"] ;\n' \ + 'edge [fontname="helvetica"] ;\n' \ '0 [label="X[0] <= 0.0\\ngini = 0.5\\nsamples = 6\\n' \ 'value = [3, 3]\\nclass = y[0]"] ;\n' \ '1 [label="(...)"] ;\n' \ @@ -122,7 +126,9 @@ def test_graphviz_toy(): contents1 = export_graphviz(clf, max_depth=0, filled=True, out_file=None, node_ids=True) contents2 = 'digraph Tree {\n' \ - 'node [shape=box, style="filled", color="black"] ;\n' \ + 'node [shape=box, style="filled", color="black", '\ + 'fontname="helvetica"] ;\n' \ + 'edge [fontname="helvetica"] ;\n' \ '0 [label="node #0\\nX[0] <= 0.0\\ngini = 0.5\\n' \ 'samples = 6\\nvalue = [3, 3]", fillcolor="#ffffff"] ;\n' \ '1 [label="(...)", fillcolor="#C0C0C0"] ;\n' \ @@ -143,7 +149,9 @@ def test_graphviz_toy(): contents1 = export_graphviz(clf, filled=True, impurity=False, out_file=None) contents2 = 'digraph Tree {\n' \ - 'node [shape=box, style="filled", color="black"] ;\n' \ + 'node [shape=box, style="filled", color="black", ' \ + 'fontname="helvetica"] ;\n' \ + 'edge [fontname="helvetica"] ;\n' \ '0 [label="X[0] <= 0.0\\nsamples = 6\\n' \ 'value = [[3.0, 1.5, 0.0]\\n' \ '[3.0, 1.0, 0.5]]", fillcolor="#ffffff"] ;\n' \ @@ -174,12 +182,13 @@ def test_graphviz_toy(): clf.fit(X, y) contents1 = export_graphviz(clf, filled=True, leaves_parallel=True, - out_file=None, rotate=True, rounded=True) + out_file=None, rotate=True, rounded=True, + fontname="sans") contents2 = 'digraph Tree {\n' \ 'node [shape=box, style="filled, rounded", color="black", ' \ - 'fontname=helvetica] ;\n' \ + 'fontname="sans"] ;\n' \ 'graph [ranksep=equally, splines=polyline] ;\n' \ - 'edge [fontname=helvetica] ;\n' \ + 'edge [fontname="sans"] ;\n' \ 'rankdir=LR ;\n' \ '0 [label="X[0] <= 0.0\\nmse = 1.0\\nsamples = 6\\n' \ 'value = 0.0", fillcolor="#f2c09c"] ;\n' \ @@ -203,7 +212,9 @@ def test_graphviz_toy(): contents1 = export_graphviz(clf, filled=True, out_file=None) contents2 = 'digraph Tree {\n' \ - 'node [shape=box, style="filled", color="black"] ;\n' \ + 'node [shape=box, style="filled", color="black", '\ + 'fontname="helvetica"] ;\n' \ + 'edge [fontname="helvetica"] ;\n' \ '0 [label="gini = 0.0\\nsamples = 6\\nvalue = 6.0", ' \ 'fillcolor="#ffffff"] ;\n' \ '}'
[ { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 0372dcdd1fd4e..f056f3a9be2d3 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -44,6 +44,13 @@ Changelog\n :pr:`123456` by :user:`Joe Bloggs <joeongithub>`.\n where 123456 is the *pull request* number, not the issue number.\n \n+:mod:`sklearn.tree`\n+...................\n+\n+- |Enhancement| Add `fontname` argument in :func:`tree.export_graphviz`\n+ for non-English characters. :pr:`18959` by :user:`Zero <Zeroto521>`\n+ and :user:`wstates <wstates>`.\n+\n :mod:`sklearn.cluster`\n ......................\n \n" } ]
1.00
6b4f82433dc2f219dbff7fe8fa42c10b72379be6
[ "sklearn/tree/tests/test_export.py::test_export_text", "sklearn/tree/tests/test_export.py::test_not_fitted_tree", "sklearn/tree/tests/test_export.py::test_friedman_mse_in_graphviz", "sklearn/tree/tests/test_export.py::test_precision", "sklearn/tree/tests/test_export.py::test_plot_tree_rotate_deprecation", "sklearn/tree/tests/test_export.py::test_plot_tree_gini", "sklearn/tree/tests/test_export.py::test_graphviz_errors", "sklearn/tree/tests/test_export.py::test_plot_tree_entropy", "sklearn/tree/tests/test_export.py::test_export_text_errors" ]
[ "sklearn/tree/tests/test_export.py::test_graphviz_toy" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 0372dcdd1fd4e..f056f3a9be2d3 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -44,6 +44,13 @@ Changelog\n :pr:`<PRID>` by :user:`<NAME>`.\n where <PRID> is the *pull request* number, not the issue number.\n \n+:mod:`sklearn.tree`\n+...................\n+\n+- |Enhancement| Add `fontname` argument in :func:`tree.export_graphviz`\n+ for non-English characters. :pr:`<PRID>` by :user:`<NAME>`\n+ and :user:`<NAME>`.\n+\n :mod:`sklearn.cluster`\n ......................\n \n" } ]
diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index 0372dcdd1fd4e..f056f3a9be2d3 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -44,6 +44,13 @@ Changelog :pr:`<PRID>` by :user:`<NAME>`. where <PRID> is the *pull request* number, not the issue number. +:mod:`sklearn.tree` +................... + +- |Enhancement| Add `fontname` argument in :func:`tree.export_graphviz` + for non-English characters. :pr:`<PRID>` by :user:`<NAME>` + and :user:`<NAME>`. + :mod:`sklearn.cluster` ......................
scikit-learn/scikit-learn
scikit-learn__scikit-learn-20250
https://github.com/scikit-learn/scikit-learn/pull/20250
diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index e4bff3c124dc5..536e61985a50c 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -540,6 +540,10 @@ Changelog :class:`preprocessing.KBinsDiscretizer` from ``auto`` to ``full``. :pr:`19934` by :user:`Gleb Levitskiy <GLevV>`. +- |Feature| :class:`preprocessing.PolynomialFeatures` now supports passing + a tuple to `degree`, i.e. `degree=(min_degree, max_degree)`. + :pr:`20250` by :user:`Christian Lorentzen <lorentzenchr>`. + - |API| The `n_input_features_` attribute of :class:`preprocessing.PolynomialFeatures` is deprecated in favor of `n_features_in_` and will be removed in 1.2. :pr:`20240` by diff --git a/sklearn/preprocessing/_polynomial.py b/sklearn/preprocessing/_polynomial.py index 51287761a84cc..9ccac80c9c692 100644 --- a/sklearn/preprocessing/_polynomial.py +++ b/sklearn/preprocessing/_polynomial.py @@ -1,6 +1,7 @@ """ This file contains preprocessing tools based on polynomials. """ +import collections import numbers from itertools import chain, combinations from itertools import combinations_with_replacement as combinations_w_r @@ -19,6 +20,7 @@ __all__ = [ + "PolynomialFeatures", "SplineTransformer", ] @@ -35,13 +37,21 @@ class PolynomialFeatures(TransformerMixin, BaseEstimator): Parameters ---------- - degree : int, default=2 - The degree of the polynomial features. + degree : int or tuple (min_degree, max_degree), default=2 + If a single int is given, it specifies the maximal degree of the + polynomial features. If a tuple ``(min_degree, max_degree)`` is + passed, then ``min_degree`` is the minimum and ``max_degree`` is the + maximum polynomial degree of the generated features. Note that + min_degree=0 and 1 are equivalent as outputting the degree zero term + is determined by ``include_bias``. interaction_only : bool, default=False If true, only interaction features are produced: features that are - products of at most ``degree`` *distinct* input features (so not - ``x[1] ** 2``, ``x[0] * x[2] ** 3``, etc.). + products of at most ``degree`` *distinct* input features, i.e. terms + with power of 2 or higher of the same input feature are excluded: + + - included: ``x[0]``, `x[1]`, ``x[0] * x[1]``, etc. + - exluded: ``x[0] ** 2``, ``x[0] ** 2 * x[1]``, etc. include_bias : bool, default=True If True (default), then include a bias column, the feature in which @@ -120,15 +130,22 @@ def __init__( self.order = order @staticmethod - def _combinations(n_features, degree, interaction_only, include_bias): + def _combinations( + n_features, min_degree, max_degree, interaction_only, include_bias + ): comb = combinations if interaction_only else combinations_w_r - start = int(not include_bias) - return chain.from_iterable( - comb(range(n_features), i) for i in range(start, degree + 1) + start = max(1, min_degree) + iter = chain.from_iterable( + comb(range(n_features), i) for i in range(start, max_degree + 1) ) + if include_bias: + iter = chain(comb(range(n_features), 0), iter) + return iter @staticmethod - def _num_combinations(n_features, degree, interaction_only, include_bias): + def _num_combinations( + n_features, min_degree, max_degree, interaction_only, include_bias + ): """Calculate number of terms in polynomial expansion This should be equivalent to counting the number of terms returned by @@ -139,11 +156,14 @@ def _num_combinations(n_features, degree, interaction_only, include_bias): combinations = sum( [ comb(n_features, i, exact=True) - for i in range(1, min(degree + 1, n_features + 1)) + for i in range(max(1, min_degree), min(max_degree, n_features) + 1) ] ) else: - combinations = comb(n_features + degree, degree, exact=True) - 1 + combinations = comb(n_features + max_degree, max_degree, exact=True) - 1 + if min_degree > 0: + d = min_degree - 1 + combinations -= comb(n_features + d, d, exact=True) - 1 if include_bias: combinations += 1 @@ -155,7 +175,11 @@ def powers_(self): check_is_fitted(self) combinations = self._combinations( - self.n_features_in_, self.degree, self.interaction_only, self.include_bias + n_features=self.n_features_in_, + min_degree=self._min_degree, + max_degree=self._max_degree, + interaction_only=self.interaction_only, + include_bias=self.include_bias, ) return np.vstack( [np.bincount(c, minlength=self.n_features_in_) for c in combinations] @@ -212,8 +236,52 @@ def fit(self, X, y=None): Fitted transformer. """ _, n_features = self._validate_data(X, accept_sparse=True).shape + + if isinstance(self.degree, numbers.Integral): + if self.degree < 0: + raise ValueError( + f"degree must be a non-negative integer, " f"got {self.degree}." + ) + self._min_degree = 0 + self._max_degree = self.degree + elif ( + isinstance(self.degree, collections.abc.Iterable) and len(self.degree) == 2 + ): + self._min_degree, self._max_degree = self.degree + if not ( + isinstance(self._min_degree, numbers.Integral) + and isinstance(self._max_degree, numbers.Integral) + and self._min_degree >= 0 + and self._min_degree <= self._max_degree + ): + raise ValueError( + f"degree=(min_degree, max_degree) must " + f"be non-negative integers that fulfil " + f"min_degree <= max_degree, got " + f"{self.degree}." + ) + else: + raise ValueError( + f"degree must be a non-negative int or tuple " + f"(min_degree, max_degree), got " + f"{self.degree}." + ) + self.n_output_features_ = self._num_combinations( - n_features, self.degree, self.interaction_only, self.include_bias + n_features=n_features, + min_degree=self._min_degree, + max_degree=self._max_degree, + interaction_only=self.interaction_only, + include_bias=self.include_bias, + ) + # We also record the number of output features for + # _max_degree = 0 + self._n_out_full = self._num_combinations( + n_features=n_features, + min_degree=0, + max_degree=self._max_degree, + interaction_only=self.interaction_only, + include_bias=self.include_bias, ) return self @@ -256,95 +324,117 @@ def transform(self, X): n_samples, n_features = X.shape if sparse.isspmatrix_csr(X): - if self.degree > 3: + if self._max_degree > 3: return self.transform(X.tocsc()).tocsr() to_stack = [] if self.include_bias: - to_stack.append(np.ones(shape=(n_samples, 1), dtype=X.dtype)) - to_stack.append(X) - for deg in range(2, self.degree + 1): + to_stack.append( + sparse.csc_matrix(np.ones(shape=(n_samples, 1), dtype=X.dtype)) + ) + if self._min_degree <= 1: + to_stack.append(X) + for deg in range(max(2, self._min_degree), self._max_degree + 1): Xp_next = _csr_polynomial_expansion( X.data, X.indices, X.indptr, X.shape[1], self.interaction_only, deg ) if Xp_next is None: break to_stack.append(Xp_next) - XP = sparse.hstack(to_stack, format="csr") - elif sparse.isspmatrix_csc(X) and self.degree < 4: + if len(to_stack) == 0: + # edge case: deal with empty matrix + XP = sparse.csr_matrix((n_samples, 0), dtype=X.dtype) + else: + XP = sparse.hstack(to_stack, format="csr") + elif sparse.isspmatrix_csc(X) and self._max_degree < 4: return self.transform(X.tocsr()).tocsc() + elif sparse.isspmatrix(X): + combinations = self._combinations( + n_features=n_features, + min_degree=self._min_degree, + max_degree=self._max_degree, + interaction_only=self.interaction_only, + include_bias=self.include_bias, + ) + columns = [] + for combi in combinations: + if combi: + out_col = 1 + for col_idx in combi: + out_col = X[:, col_idx].multiply(out_col) + columns.append(out_col) + else: + bias = sparse.csc_matrix(np.ones((X.shape[0], 1))) + columns.append(bias) + XP = sparse.hstack(columns, dtype=X.dtype).tocsc() else: - if sparse.isspmatrix(X): - combinations = self._combinations( - n_features, self.degree, self.interaction_only, self.include_bias - ) - columns = [] - for combination in combinations: - if combination: - out_col = 1 - for col_idx in combination: - out_col = X[:, col_idx].multiply(out_col) - columns.append(out_col) - else: - bias = sparse.csc_matrix(np.ones((X.shape[0], 1))) - columns.append(bias) - XP = sparse.hstack(columns, dtype=X.dtype).tocsc() + # Do as if _min_degree = 0 and cut down array after the + # computation, i.e. use _n_out_full instead of n_output_features_. + XP = np.empty( + shape=(n_samples, self._n_out_full), dtype=X.dtype, order=self.order + ) + + # What follows is a faster implementation of: + # for i, comb in enumerate(combinations): + # XP[:, i] = X[:, comb].prod(1) + # This implementation uses two optimisations. + # First one is broadcasting, + # multiply ([X1, ..., Xn], X1) -> [X1 X1, ..., Xn X1] + # multiply ([X2, ..., Xn], X2) -> [X2 X2, ..., Xn X2] + # ... + # multiply ([X[:, start:end], X[:, start]) -> ... + # Second optimisation happens for degrees >= 3. + # Xi^3 is computed reusing previous computation: + # Xi^3 = Xi^2 * Xi. + + # degree 0 term + if self.include_bias: + XP[:, 0] = 1 + current_col = 1 else: - XP = np.empty( - (n_samples, self.n_output_features_), - dtype=X.dtype, - order=self.order, - ) + current_col = 0 + + # degree 1 term + XP[:, current_col : current_col + n_features] = X + index = list(range(current_col, current_col + n_features)) + current_col += n_features + index.append(current_col) + + # loop over degree >= 2 terms + for _ in range(2, self._max_degree + 1): + new_index = [] + end = index[-1] + for feature_idx in range(n_features): + start = index[feature_idx] + new_index.append(current_col) + if self.interaction_only: + start += index[feature_idx + 1] - index[feature_idx] + next_col = current_col + end - start + if next_col <= current_col: + break + # XP[:, start:end] are terms of degree d - 1 + # that exclude feature #feature_idx. + np.multiply( + XP[:, start:end], + X[:, feature_idx : feature_idx + 1], + out=XP[:, current_col:next_col], + casting="no", + ) + current_col = next_col - # What follows is a faster implementation of: - # for i, comb in enumerate(combinations): - # XP[:, i] = X[:, comb].prod(1) - # This implementation uses two optimisations. - # First one is broadcasting, - # multiply ([X1, ..., Xn], X1) -> [X1 X1, ..., Xn X1] - # multiply ([X2, ..., Xn], X2) -> [X2 X2, ..., Xn X2] - # ... - # multiply ([X[:, start:end], X[:, start]) -> ... - # Second optimisation happens for degrees >= 3. - # Xi^3 is computed reusing previous computation: - # Xi^3 = Xi^2 * Xi. + new_index.append(current_col) + index = new_index + if self._min_degree > 1: + n_XP, n_Xout = self._n_out_full, self.n_output_features_ if self.include_bias: - XP[:, 0] = 1 - current_col = 1 + Xout = np.empty( + shape=(n_samples, n_Xout), dtype=XP.dtype, order=self.order + ) + Xout[:, 0] = 1 + Xout[:, 1:] = XP[:, n_XP - n_Xout + 1 :] else: - current_col = 0 - - # d = 0 - XP[:, current_col : current_col + n_features] = X - index = list(range(current_col, current_col + n_features)) - current_col += n_features - index.append(current_col) - - # d >= 1 - for _ in range(1, self.degree): - new_index = [] - end = index[-1] - for feature_idx in range(n_features): - start = index[feature_idx] - new_index.append(current_col) - if self.interaction_only: - start += index[feature_idx + 1] - index[feature_idx] - next_col = current_col + end - start - if next_col <= current_col: - break - # XP[:, start:end] are terms of degree d - 1 - # that exclude feature #feature_idx. - np.multiply( - XP[:, start:end], - X[:, feature_idx : feature_idx + 1], - out=XP[:, current_col:next_col], - casting="no", - ) - current_col = next_col - - new_index.append(current_col) - index = new_index - + Xout = XP[:, n_XP - n_Xout :].copy() + XP = Xout return XP # TODO: Remove in 1.2 @@ -568,7 +658,9 @@ def fit(self, X, y=None): n_samples, n_features = X.shape if not (isinstance(self.degree, numbers.Integral) and self.degree >= 0): - raise ValueError("degree must be a non-negative integer.") + raise ValueError( + f"degree must be a non-negative integer, got " f"{self.degree}." + ) if isinstance(self.knots, str) and self.knots in [ "uniform",
diff --git a/sklearn/preprocessing/tests/test_polynomial.py b/sklearn/preprocessing/tests/test_polynomial.py index 746a1caacc718..97fc539d3e419 100644 --- a/sklearn/preprocessing/tests/test_polynomial.py +++ b/sklearn/preprocessing/tests/test_polynomial.py @@ -32,9 +32,9 @@ def is_c_contiguous(a): @pytest.mark.parametrize( "params, err_msg", [ - ({"degree": -1}, "degree must be a non-negative integer."), - ({"degree": 2.5}, "degree must be a non-negative integer."), - ({"degree": "string"}, "degree must be a non-negative integer."), + ({"degree": -1}, "degree must be a non-negative integer"), + ({"degree": 2.5}, "degree must be a non-negative integer"), + ({"degree": "string"}, "degree must be a non-negative integer"), ({"n_knots": 1}, "n_knots must be a positive integer >= 2."), ({"n_knots": 1}, "n_knots must be a positive integer >= 2."), ({"n_knots": 2.5}, "n_knots must be a positive integer >= 2."), @@ -432,42 +432,145 @@ def test_spline_transformer_n_features_out(n_knots, include_bias, degree): assert splt.transform(X).shape[1] == splt.n_features_out_ -def test_polynomial_features(): - # Test Polynomial Features - X1 = np.arange(6)[:, np.newaxis] - P1 = np.hstack([np.ones_like(X1), X1, X1 ** 2, X1 ** 3]) - deg1 = 3 [email protected]( + "params, err_msg", + [ + ({"degree": -1}, "degree must be a non-negative integer"), + ({"degree": 2.5}, "degree must be a non-negative int or tuple"), + ({"degree": "12"}, r"degree=\(min_degree, max_degree\) must"), + ({"degree": "string"}, "degree must be a non-negative int or tuple"), + ({"degree": (-1, 2)}, r"degree=\(min_degree, max_degree\) must"), + ({"degree": (0, 1.5)}, r"degree=\(min_degree, max_degree\) must"), + ({"degree": (3, 2)}, r"degree=\(min_degree, max_degree\) must"), + ], +) +def test_polynomial_features_input_validation(params, err_msg): + """Test that we raise errors for invalid input in PolynomialFeatures.""" + X = [[1], [2]] - X2 = np.arange(6).reshape((3, 2)) - x1 = X2[:, :1] - x2 = X2[:, 1:] - P2 = np.hstack( - [ - x1 ** 0 * x2 ** 0, - x1 ** 1 * x2 ** 0, - x1 ** 0 * x2 ** 1, - x1 ** 2 * x2 ** 0, - x1 ** 1 * x2 ** 1, - x1 ** 0 * x2 ** 2, - ] - ) - deg2 = 2 + with pytest.raises(ValueError, match=err_msg): + PolynomialFeatures(**params).fit(X) - for (deg, X, P) in [(deg1, X1, P1), (deg2, X2, P2)]: - P_test = PolynomialFeatures(deg, include_bias=True).fit_transform(X) - assert_array_almost_equal(P_test, P) - P_test = PolynomialFeatures(deg, include_bias=False).fit_transform(X) - assert_array_almost_equal(P_test, P[:, 1:]) [email protected]() +def single_feature_degree3(): + X = np.arange(6)[:, np.newaxis] + P = np.hstack([np.ones_like(X), X, X ** 2, X ** 3]) + return X, P - interact = PolynomialFeatures(2, interaction_only=True, include_bias=True) - X_poly = interact.fit_transform(X) - assert_array_almost_equal(X_poly, P2[:, [0, 1, 2, 4]]) - assert interact.powers_.shape == ( - interact.n_output_features_, - interact.n_features_in_, [email protected]( + "degree, include_bias, interaction_only, indices", + [ + (3, True, False, slice(None, None)), + (3, False, False, slice(1, None)), + (3, True, True, [0, 1]), + (3, False, True, [1]), + ((2, 3), True, False, [0, 2, 3]), + ((2, 3), False, False, [2, 3]), + ((2, 3), True, True, [0]), + ((2, 3), False, True, []), + ], +) [email protected]( + "sparse_X", + [False, sparse.csr_matrix, sparse.csc_matrix], +) +def test_polynomial_features_one_feature( + single_feature_degree3, + degree, + include_bias, + interaction_only, + indices, + sparse_X, +): + """Test PolynomialFeatures on single feature up to degree 3.""" + X, P = single_feature_degree3 + if sparse_X: + X = sparse_X(X) + tf = PolynomialFeatures( + degree=degree, include_bias=include_bias, interaction_only=interaction_only + ).fit(X) + out = tf.transform(X) + if sparse_X: + out = out.toarray() + assert_allclose(out, P[:, indices]) + if tf.n_output_features_ > 0: + assert tf.powers_.shape == (tf.n_output_features_, tf.n_features_in_) + + [email protected]() +def two_features_degree3(): + X = np.arange(6).reshape((3, 2)) + x1 = X[:, :1] + x2 = X[:, 1:] + P = np.hstack( + [ + x1 ** 0 * x2 ** 0, # 0 + x1 ** 1 * x2 ** 0, # 1 + x1 ** 0 * x2 ** 1, # 2 + x1 ** 2 * x2 ** 0, # 3 + x1 ** 1 * x2 ** 1, # 4 + x1 ** 0 * x2 ** 2, # 5 + x1 ** 3 * x2 ** 0, # 6 + x1 ** 2 * x2 ** 1, # 7 + x1 ** 1 * x2 ** 2, # 8 + x1 ** 0 * x2 ** 3, # 9 + ] ) + return X, P + + [email protected]( + "degree, include_bias, interaction_only, indices", + [ + (2, True, False, slice(0, 6)), + (2, False, False, slice(1, 6)), + (2, True, True, [0, 1, 2, 4]), + (2, False, True, [1, 2, 4]), + ((2, 2), True, False, [0, 3, 4, 5]), + ((2, 2), False, False, [3, 4, 5]), + ((2, 2), True, True, [0, 4]), + ((2, 2), False, True, [4]), + (3, True, False, slice(None, None)), + (3, False, False, slice(1, None)), + (3, True, True, [0, 1, 2, 4]), + (3, False, True, [1, 2, 4]), + ((2, 3), True, False, [0, 3, 4, 5, 6, 7, 8, 9]), + ((2, 3), False, False, slice(3, None)), + ((2, 3), True, True, [0, 4]), + ((2, 3), False, True, [4]), + ((3, 3), True, False, [0, 6, 7, 8, 9]), + ((3, 3), False, False, [6, 7, 8, 9]), + ((3, 3), True, True, [0]), + ((3, 3), False, True, []), # would need 3 input features + ], +) [email protected]( + "sparse_X", + [False, sparse.csr_matrix, sparse.csc_matrix], +) +def test_polynomial_features_two_features( + two_features_degree3, + degree, + include_bias, + interaction_only, + indices, + sparse_X, +): + """Test PolynomialFeatures on 2 features up to degree 3.""" + X, P = two_features_degree3 + if sparse_X: + X = sparse_X(X) + tf = PolynomialFeatures( + degree=degree, include_bias=include_bias, interaction_only=interaction_only + ).fit(X) + out = tf.transform(X) + if sparse_X: + out = out.toarray() + assert_allclose(out, P[:, indices]) + if tf.n_output_features_ > 0: + assert tf.powers_.shape == (tf.n_output_features_, tf.n_features_in_) def test_polynomial_feature_names(): @@ -478,6 +581,7 @@ def test_polynomial_feature_names(): ["1", "x0", "x1", "x2", "x0^2", "x0 x1", "x0 x2", "x1^2", "x1 x2", "x2^2"], feature_names, ) + assert len(feature_names) == poly.transform(X).shape[1] poly = PolynomialFeatures(degree=3, include_bias=False).fit(X) feature_names = poly.get_feature_names(["a", "b", "c"]) @@ -505,6 +609,40 @@ def test_polynomial_feature_names(): ], feature_names, ) + assert len(feature_names) == poly.transform(X).shape[1] + + poly = PolynomialFeatures(degree=(2, 3), include_bias=False).fit(X) + feature_names = poly.get_feature_names(["a", "b", "c"]) + assert_array_equal( + [ + "a^2", + "a b", + "a c", + "b^2", + "b c", + "c^2", + "a^3", + "a^2 b", + "a^2 c", + "a b^2", + "a b c", + "a c^2", + "b^3", + "b^2 c", + "b c^2", + "c^3", + ], + feature_names, + ) + assert len(feature_names) == poly.transform(X).shape[1] + + poly = PolynomialFeatures( + degree=(3, 3), include_bias=True, interaction_only=True + ).fit(X) + feature_names = poly.get_feature_names(["a", "b", "c"]) + assert_array_equal(["1", "a b c"], feature_names) + assert len(feature_names) == poly.transform(X).shape[1] + # test some unicode poly = PolynomialFeatures(degree=1, include_bias=True).fit(X) feature_names = poly.get_feature_names(["\u0001F40D", "\u262E", "\u05D0"]) @@ -568,22 +706,36 @@ def test_polynomial_features_csr_X(deg, include_bias, interaction_only, dtype): @pytest.mark.parametrize("n_features", [1, 4, 5]) [email protected]("degree", range(1, 5)) [email protected]( + "min_degree, max_degree", [(0, 1), (0, 2), (1, 3), (0, 4), (3, 4)] +) @pytest.mark.parametrize("interaction_only", [True, False]) @pytest.mark.parametrize("include_bias", [True, False]) -def test_num_combinations(n_features, degree, interaction_only, include_bias): +def test_num_combinations( + n_features, + min_degree, + max_degree, + interaction_only, + include_bias, +): """ Test that n_output_features_ is calculated correctly. """ x = sparse.csr_matrix(([1], ([0], [n_features - 1]))) est = PolynomialFeatures( - degree, interaction_only=interaction_only, include_bias=include_bias + degree=max_degree, + interaction_only=interaction_only, + include_bias=include_bias, ) est.fit(x) num_combos = est.n_output_features_ combos = PolynomialFeatures._combinations( - n_features, degree, interaction_only, include_bias + n_features=n_features, + min_degree=0, + max_degree=max_degree, + interaction_only=interaction_only, + include_bias=include_bias, ) assert num_combos == sum([1 for _ in combos])
[ { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex e4bff3c124dc5..536e61985a50c 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -540,6 +540,10 @@ Changelog\n :class:`preprocessing.KBinsDiscretizer` from ``auto`` to ``full``.\n :pr:`19934` by :user:`Gleb Levitskiy <GLevV>`.\n \n+- |Feature| :class:`preprocessing.PolynomialFeatures` now supports passing\n+ a tuple to `degree`, i.e. `degree=(min_degree, max_degree)`.\n+ :pr:`20250` by :user:`Christian Lorentzen <lorentzenchr>`.\n+\n - |API| The `n_input_features_` attribute of\n :class:`preprocessing.PolynomialFeatures` is deprecated in favor of\n `n_features_in_` and will be removed in 1.2. :pr:`20240` by\n" } ]
1.00
7b715111bff01e836fcd3413851381c6a1057ca4
[ "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_periodic_splines_smoothness[5]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_csr_X[1-True-False-int]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_csr_X_dim_edges[3-2-False]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[periodic-quantile-4-3]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[False-2-True-False-indices0]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_manual_knot_input", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_csc_X[2-True-False-float32]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_input_validation[params12-knots must be sorted without duplicates.]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[csr_matrix-3-True-False-indices8]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_csr_X_dim_edges[2-1-True]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_csc_X[4-False-False-float64]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_csr_X_zero_row[1-2-False]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_input_validation[params7-Expected 2D array, got scalar array instead:]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[constant-uniform-3-3]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[constant-uniform-3-4]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_n_features_out[5-False-5]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[constant-quantile-4-4]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_input_validation[params18-include_bias must be bool.]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_extrapolation[5-True-False]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[csc_matrix-2-False-False-indices1]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_input_validation[params11-knots must be sorted without duplicates.]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[periodic-quantile-4-2]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_n_features_out[5-True-10]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_input_validation[params15-extrapolation must be one of 'error', 'constant', 'linear', 'continue' or 'periodic'.]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_input_validation[params19-Periodic splines require degree < n_knots. Got n_knots=3 and degree=3.]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_integer_knots[periodic]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_csr_X_degree_4[True-False]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_csr_X_floats[2-True-False-float32]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[csc_matrix-3-False-True-indices11]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[periodic-uniform-3-1]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_input_validation[params13-extrapolation must be one of 'error', 'constant', 'linear', 'continue' or 'periodic'.]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[constant-quantile-4-2]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_csc_X[4-False-True-float64]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_one_feature[False-3-True-False-indices0]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_one_feature[csr_matrix-3-True-True-indices2]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_csr_X_dim_edges[3-2-True]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_n_features_out[3-False-5]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_csr_X_dim_edges[3-1-False]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_csr_X_dim_edges[2-1-False]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[csr_matrix-3-False-True-indices11]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_csr_X_zero_row[1-3-True]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[constant-uniform-4-4]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_input_validation[params6-n_knots must be a positive integer >= 2.]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_linear_regression[False-True]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[periodic-quantile-4-1]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_csc_X[2-True-False-int]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_input_validation[params14-extrapolation must be one of 'error', 'constant', 'linear', 'continue' or 'periodic'.]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[False-2-True-True-indices2]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_periodic_linear_regression[False-True]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[csc_matrix-2-True-True-indices2]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_input_validation[params10-knots.shape\\\\[1\\\\] == n_features is violated.]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[csr_matrix-2-False-False-indices1]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_integer_knots[continue]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_one_feature[csr_matrix-3-False-False-indices1]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[periodic-uniform-4-1]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_one_feature[csc_matrix-3-False-True-indices3]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[csr_matrix-2-True-False-indices0]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[constant-uniform-4-2]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_extrapolation[3-False-True]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_input_validation[params16-include_bias must be bool.]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_csr_X[3-False-False-float64]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_csc_X[2-True-False-float64]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_csr_X_dim_edges[3-1-True]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_input_validation[params20-Periodic splines require degree < n_knots. Got n_knots=2 and degree=2.]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_csr_X_floats[3-False-True-float64]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[periodic-quantile-3-3]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[csc_matrix-2-False-True-indices3]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_n_features_out[3-False-10]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[periodic-quantile-3-4]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[constant-uniform-3-2]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_extrapolation[3-True-False]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[periodic-uniform-3-4]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_n_features_out[3-True-10]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_csr_X_floats[2-True-False-float64]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[False-3-False-True-indices11]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_csr_X[2-True-False-float32]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_input_validation[params4-n_knots must be a positive integer >= 2.]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[False-3-False-False-indices9]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_input_validation[params5-n_knots must be a positive integer >= 2.]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[False-2-False-True-indices3]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_periodicity_of_extrapolation[uniform-5-3]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_one_feature[csc_matrix-3-False-False-indices1]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_and_spline_array_order[SplineTransformer]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_one_feature[False-3-False-False-indices1]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[constant-uniform-4-3]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[periodic-uniform-3-3]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_csr_X_zero_row[0-2-True]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_csr_X_zero_row[2-2-True]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_csr_X_zero_row[2-2-False]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[periodic-uniform-4-2]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[constant-quantile-3-2]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_periodic_splines_periodicity", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[csc_matrix-2-True-False-indices0]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[periodic-uniform-4-3]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_extrapolation[2-True-False]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_input_validation[params1-degree must be a non-negative integer]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_csr_X[2-True-False-float64]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_input_validation[params0-degree must be a non-negative integer]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_csr_X_zero_row[0-3-False]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[constant-uniform-3-1]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_input_validation[params3-n_knots must be a positive integer >= 2.]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_input_validation[params8-Expected 2D array, got 1D array instead:]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_csr_X_dim_edges[2-2-True]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_one_feature[False-3-False-True-indices3]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_csr_X_dim_edges[3-3-False]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[False-2-False-False-indices1]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_csr_X_zero_row[2-3-True]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_input_validation[params17-include_bias must be bool.]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_input_validation[params2-degree must be a non-negative integer]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[constant-quantile-3-4]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[periodic-quantile-3-2]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[csr_matrix-2-True-True-indices2]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_periodicity_of_extrapolation[knots2-None-3]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_csr_X_zero_row[1-3-False]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_csr_X_zero_row[0-2-False]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_one_feature[csc_matrix-3-True-True-indices2]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_csr_X_zero_row[2-3-False]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_deprecated_n_input_features", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_csr_X_dim_edges[3-3-True]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_extrapolation[1-False-True]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_linear_regression[True-False]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_input_validation[params9-Number of knots, knots.shape\\\\[0\\\\], must be >= 2.]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_csr_X_degree_4[False-True]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_periodic_splines_smoothness[3]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_extrapolation[2-False-True]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[csr_matrix-3-True-True-indices10]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_extrapolation[4-True-False]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_one_feature[csc_matrix-3-True-False-indices0]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_one_feature[csr_matrix-3-False-True-indices3]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_csr_X_zero_row[1-2-True]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[constant-quantile-4-1]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_csr_X_zero_row[0-3-True]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_n_features_out[5-True-5]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[csr_matrix-3-False-False-indices9]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[csc_matrix-3-True-True-indices10]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[constant-uniform-4-1]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[False-3-True-True-indices10]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[periodic-quantile-4-4]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_and_spline_array_order[PolynomialFeatures]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_csr_X[2-True-False-int]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_csr_X_degree_4[False-False]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_extrapolation[1-True-False]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_csr_X[3-False-True-float64]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[periodic-uniform-3-2]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[periodic-uniform-4-4]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[csc_matrix-3-True-False-indices8]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_csr_X_floats[3-False-False-float64]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_kbindiscretizer", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_extrapolation[5-False-True]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_csc_X[3-False-True-float64]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_periodic_spline_backport", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_csc_X[3-False-False-float64]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_csr_X_dim_edges[2-2-False]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[periodic-quantile-3-1]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_n_features_out[3-True-5]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[csc_matrix-3-False-False-indices9]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_periodicity_of_extrapolation[uniform-12-8]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[constant-quantile-3-1]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_csr_X_degree_4[True-True]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_periodic_linear_regression[True-False]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_one_feature[csr_matrix-3-True-False-indices0]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_extrapolation[4-False-True]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_one_feature[False-3-True-True-indices2]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[csr_matrix-2-False-True-indices3]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_feature_names", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[constant-quantile-3-3]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_csc_X[1-True-False-int]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_n_features_out[5-False-10]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[False-3-True-False-indices8]", "sklearn/preprocessing/tests/test_polynomial.py::test_spline_transformer_unity_decomposition[constant-quantile-4-3]" ]
[ "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[True-True-0-4-1]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[False-degree17-False-False-indices17]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[csc_matrix-degree15-False-True-indices15]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[False-degree6-True-True-indices6]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_one_feature[csc_matrix-degree5-False-False-indices5]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[csr_matrix-degree4-True-False-indices4]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_one_feature[csr_matrix-degree6-True-True-indices6]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[csr_matrix-degree18-True-True-indices18]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[True-False-0-4-1]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[False-True-0-4-1]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_feature_names", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[False-degree14-True-True-indices14]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[True-True-3-4-1]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[csc_matrix-degree4-True-False-indices4]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[True-False-0-2-1]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[False-degree12-True-False-indices12]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[True-False-3-4-1]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[True-True-0-4-5]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[csc_matrix-degree14-True-True-indices14]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[False-False-1-3-5]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[False-True-3-4-4]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[csc_matrix-degree18-True-True-indices18]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[False-True-0-2-1]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[csc_matrix-degree19-False-True-indices19]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_one_feature[csc_matrix-degree6-True-True-indices6]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_one_feature[csr_matrix-degree5-False-False-indices5]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[csr_matrix-degree19-False-True-indices19]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[csr_matrix-degree17-False-False-indices17]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_input_validation[params4-degree=\\\\(min_degree, max_degree\\\\) must]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[csr_matrix-degree16-True-False-indices16]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_one_feature[csr_matrix-degree4-True-False-indices4]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[csc_matrix-degree17-False-False-indices17]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[True-False-0-2-5]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[True-True-0-2-4]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[csr_matrix-degree15-False-True-indices15]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[True-True-0-1-5]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_one_feature[False-degree7-False-True-indices7]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[True-False-0-2-4]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[False-True-1-3-5]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[True-False-0-4-5]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[False-False-1-3-4]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[False-False-0-4-5]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_input_validation[params0-degree must be a non-negative integer]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[True-True-0-2-1]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[False-degree19-False-True-indices19]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[True-False-3-4-5]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_input_validation[params6-degree=\\\\(min_degree, max_degree\\\\) must]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[True-True-1-3-1]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[False-True-0-1-5]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[True-False-0-4-4]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[csr_matrix-degree6-True-True-indices6]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[csc_matrix-degree12-True-False-indices12]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[True-False-3-4-4]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[True-True-0-1-1]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_one_feature[False-degree5-False-False-indices5]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[True-True-0-2-5]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_one_feature[csc_matrix-degree4-True-False-indices4]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[False-degree13-False-False-indices13]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[csc_matrix-degree5-False-False-indices5]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[False-False-0-4-4]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[True-False-1-3-1]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[False-True-0-4-4]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[False-degree15-False-True-indices15]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[False-False-1-3-1]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[True-False-0-1-1]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[True-False-1-3-4]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[False-True-3-4-1]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_one_feature[False-degree4-True-False-indices4]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[False-False-0-2-5]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[True-True-0-1-4]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_input_validation[params2-degree=\\\\(min_degree, max_degree\\\\) must]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[True-False-0-1-4]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[False-False-0-2-1]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[False-True-0-2-5]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[True-True-3-4-5]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[False-True-3-4-5]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[csr_matrix-degree13-False-False-indices13]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_input_validation[params1-degree must be a non-negative int or tuple]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_input_validation[params5-degree=\\\\(min_degree, max_degree\\\\) must]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_one_feature[False-degree6-True-True-indices6]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[csc_matrix-degree6-True-True-indices6]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_one_feature[csr_matrix-degree7-False-True-indices7]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[False-False-0-4-1]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[False-False-3-4-4]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[False-degree7-False-True-indices7]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[False-True-0-4-5]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_input_validation[params3-degree must be a non-negative int or tuple]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[csr_matrix-degree14-True-True-indices14]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[True-True-1-3-5]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[True-False-0-1-5]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[csc_matrix-degree7-False-True-indices7]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[False-degree4-True-False-indices4]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[False-True-0-2-4]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[False-False-0-1-4]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[False-False-3-4-5]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[True-True-1-3-4]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[False-True-1-3-4]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[False-False-0-2-4]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[False-True-0-1-1]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[csr_matrix-degree12-True-False-indices12]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[False-True-0-1-4]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[csr_matrix-degree7-False-True-indices7]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[False-degree5-False-False-indices5]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[csc_matrix-degree13-False-False-indices13]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[False-False-0-1-1]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[True-True-3-4-4]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[True-True-0-4-4]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_one_feature[csc_matrix-degree7-False-True-indices7]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[True-False-1-3-5]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[False-False-3-4-1]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[False-True-1-3-1]", "sklearn/preprocessing/tests/test_polynomial.py::test_num_combinations[False-False-0-1-5]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[False-degree16-True-False-indices16]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[False-degree18-True-True-indices18]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[csr_matrix-degree5-False-False-indices5]", "sklearn/preprocessing/tests/test_polynomial.py::test_polynomial_features_two_features[csc_matrix-degree16-True-False-indices16]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex e4bff3c124dc5..536e61985a50c 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -540,6 +540,10 @@ Changelog\n :class:`preprocessing.KBinsDiscretizer` from ``auto`` to ``full``.\n :pr:`<PRID>` by :user:`<NAME>`.\n \n+- |Feature| :class:`preprocessing.PolynomialFeatures` now supports passing\n+ a tuple to `degree`, i.e. `degree=(min_degree, max_degree)`.\n+ :pr:`<PRID>` by :user:`<NAME>`.\n+\n - |API| The `n_input_features_` attribute of\n :class:`preprocessing.PolynomialFeatures` is deprecated in favor of\n `n_features_in_` and will be removed in 1.2. :pr:`<PRID>` by\n" } ]
diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index e4bff3c124dc5..536e61985a50c 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -540,6 +540,10 @@ Changelog :class:`preprocessing.KBinsDiscretizer` from ``auto`` to ``full``. :pr:`<PRID>` by :user:`<NAME>`. +- |Feature| :class:`preprocessing.PolynomialFeatures` now supports passing + a tuple to `degree`, i.e. `degree=(min_degree, max_degree)`. + :pr:`<PRID>` by :user:`<NAME>`. + - |API| The `n_input_features_` attribute of :class:`preprocessing.PolynomialFeatures` is deprecated in favor of `n_features_in_` and will be removed in 1.2. :pr:`<PRID>` by
scikit-learn/scikit-learn
scikit-learn__scikit-learn-12069
https://github.com/scikit-learn/scikit-learn/pull/12069
diff --git a/benchmarks/bench_kernel_pca_solvers_time_vs_n_components.py b/benchmarks/bench_kernel_pca_solvers_time_vs_n_components.py new file mode 100644 index 0000000000000..d871967ad1327 --- /dev/null +++ b/benchmarks/bench_kernel_pca_solvers_time_vs_n_components.py @@ -0,0 +1,148 @@ +""" +============================================================= +Kernel PCA Solvers comparison benchmark: time vs n_components +============================================================= + +This benchmark shows that the approximate solvers provided in Kernel PCA can +help significantly improve its execution speed when an approximate solution +(small `n_components`) is acceptable. In many real-world datasets a few +hundreds of principal components are indeed sufficient enough to capture the +underlying distribution. + +Description: +------------ +A fixed number of training (default: 2000) and test (default: 1000) samples +with 2 features is generated using the `make_circles` helper method. + +KernelPCA models are trained on the training set with an increasing number of +principal components, between 1 and `max_n_compo` (default: 1999), with +`n_compo_grid_size` positions (default: 10). For each value of `n_components` +to try, KernelPCA models are trained for the various possible `eigen_solver` +values. The execution times are displayed in a plot at the end of the +experiment. + +What you can observe: +--------------------- +When the number of requested principal components is small, the dense solver +takes more time to complete, while the randomized method returns similar +results with shorter execution times. + +Going further: +-------------- +You can adjust `max_n_compo` and `n_compo_grid_size` if you wish to explore a +different range of values for `n_components`. + +You can also set `arpack_all=True` to activate arpack solver for large number +of components (this takes more time). +""" +# Authors: Sylvain MARIE, Schneider Electric + +import time + +import numpy as np +import matplotlib.pyplot as plt + +from numpy.testing import assert_array_almost_equal +from sklearn.decomposition import KernelPCA +from sklearn.datasets import make_circles + + +print(__doc__) + + +# 1- Design the Experiment +# ------------------------ +n_train, n_test = 2000, 1000 # the sample sizes to use +max_n_compo = 1999 # max n_components to try +n_compo_grid_size = 10 # nb of positions in the grid to try +# generate the grid +n_compo_range = [np.round(np.exp((x / (n_compo_grid_size - 1)) + * np.log(max_n_compo))) + for x in range(0, n_compo_grid_size)] + +n_iter = 3 # the number of times each experiment will be repeated +arpack_all = False # set to True if you wish to run arpack for all n_compo + + +# 2- Generate random data +# ----------------------- +n_features = 2 +X, y = make_circles(n_samples=(n_train + n_test), factor=.3, noise=.05, + random_state=0) +X_train, X_test = X[:n_train, :], X[n_train:, :] + + +# 3- Benchmark +# ------------ +# init +ref_time = np.empty((len(n_compo_range), n_iter)) * np.nan +a_time = np.empty((len(n_compo_range), n_iter)) * np.nan +r_time = np.empty((len(n_compo_range), n_iter)) * np.nan +# loop +for j, n_components in enumerate(n_compo_range): + + n_components = int(n_components) + print("Performing kPCA with n_components = %i" % n_components) + + # A- reference (dense) + print(" - dense solver") + for i in range(n_iter): + start_time = time.perf_counter() + ref_pred = KernelPCA(n_components, eigen_solver="dense") \ + .fit(X_train).transform(X_test) + ref_time[j, i] = time.perf_counter() - start_time + + # B- arpack (for small number of components only, too slow otherwise) + if arpack_all or n_components < 100: + print(" - arpack solver") + for i in range(n_iter): + start_time = time.perf_counter() + a_pred = KernelPCA(n_components, eigen_solver="arpack") \ + .fit(X_train).transform(X_test) + a_time[j, i] = time.perf_counter() - start_time + # check that the result is still correct despite the approx + assert_array_almost_equal(np.abs(a_pred), np.abs(ref_pred)) + + # C- randomized + print(" - randomized solver") + for i in range(n_iter): + start_time = time.perf_counter() + r_pred = KernelPCA(n_components, eigen_solver="randomized") \ + .fit(X_train).transform(X_test) + r_time[j, i] = time.perf_counter() - start_time + # check that the result is still correct despite the approximation + assert_array_almost_equal(np.abs(r_pred), np.abs(ref_pred)) + +# Compute statistics for the 3 methods +avg_ref_time = ref_time.mean(axis=1) +std_ref_time = ref_time.std(axis=1) +avg_a_time = a_time.mean(axis=1) +std_a_time = a_time.std(axis=1) +avg_r_time = r_time.mean(axis=1) +std_r_time = r_time.std(axis=1) + + +# 4- Plots +# -------- +fig, ax = plt.subplots(figsize=(12, 8)) + +# Display 1 plot with error bars per method +ax.errorbar(n_compo_range, avg_ref_time, yerr=std_ref_time, + marker='x', linestyle='', color='r', label='full') +ax.errorbar(n_compo_range, avg_a_time, yerr=std_a_time, marker='x', + linestyle='', color='g', label='arpack') +ax.errorbar(n_compo_range, avg_r_time, yerr=std_r_time, marker='x', + linestyle='', color='b', label='randomized') +ax.legend(loc='upper left') + +# customize axes +ax.set_xscale('log') +ax.set_xlim(1, max(n_compo_range) * 1.1) +ax.set_ylabel("Execution time (s)") +ax.set_xlabel("n_components") + +ax.set_title("kPCA Execution time comparison on %i samples with %i " + "features, according to the choice of `eigen_solver`" + "" % (n_train, n_features)) + +plt.show() diff --git a/benchmarks/bench_kernel_pca_solvers_time_vs_n_samples.py b/benchmarks/bench_kernel_pca_solvers_time_vs_n_samples.py new file mode 100644 index 0000000000000..d238802a68d64 --- /dev/null +++ b/benchmarks/bench_kernel_pca_solvers_time_vs_n_samples.py @@ -0,0 +1,153 @@ +""" +========================================================== +Kernel PCA Solvers comparison benchmark: time vs n_samples +========================================================== + +This benchmark shows that the approximate solvers provided in Kernel PCA can +help significantly improve its execution speed when an approximate solution +(small `n_components`) is acceptable. In many real-world datasets the number of +samples is very large, but a few hundreds of principal components are +sufficient enough to capture the underlying distribution. + +Description: +------------ +An increasing number of examples is used to train a KernelPCA, between +`min_n_samples` (default: 101) and `max_n_samples` (default: 4000) with +`n_samples_grid_size` positions (default: 4). Samples have 2 features, and are +generated using `make_circles`. For each training sample size, KernelPCA models +are trained for the various possible `eigen_solver` values. All of them are +trained to obtain `n_components` principal components (default: 100). The +execution times are displayed in a plot at the end of the experiment. + +What you can observe: +--------------------- +When the number of samples provided gets large, the dense solver takes a lot +of time to complete, while the randomized method returns similar results in +much shorter execution times. + +Going further: +-------------- +You can increase `max_n_samples` and `nb_n_samples_to_try` if you wish to +explore a wider range of values for `n_samples`. + +You can also set `include_arpack=True` to add this other solver in the +experiments (much slower). + +Finally you can have a look at the second example of this series, "Kernel PCA +Solvers comparison benchmark: time vs n_components", where this time the number +of examples is fixed, and the desired number of components varies. +""" +# Author: Sylvain MARIE, Schneider Electric + +import time + +import numpy as np +import matplotlib.pyplot as plt + +from numpy.testing import assert_array_almost_equal +from sklearn.decomposition import KernelPCA +from sklearn.datasets import make_circles + + +print(__doc__) + + +# 1- Design the Experiment +# ------------------------ +min_n_samples, max_n_samples = 101, 4000 # min and max n_samples to try +n_samples_grid_size = 4 # nb of positions in the grid to try +# generate the grid +n_samples_range = [min_n_samples + np.floor((x / (n_samples_grid_size - 1)) + * (max_n_samples - min_n_samples)) + for x in range(0, n_samples_grid_size)] + +n_components = 100 # the number of principal components we want to use +n_iter = 3 # the number of times each experiment will be repeated +include_arpack = False # set this to True to include arpack solver (slower) + + +# 2- Generate random data +# ----------------------- +n_features = 2 +X, y = make_circles(n_samples=max_n_samples, factor=.3, noise=.05, + random_state=0) + + +# 3- Benchmark +# ------------ +# init +ref_time = np.empty((len(n_samples_range), n_iter)) * np.nan +a_time = np.empty((len(n_samples_range), n_iter)) * np.nan +r_time = np.empty((len(n_samples_range), n_iter)) * np.nan + +# loop +for j, n_samples in enumerate(n_samples_range): + + n_samples = int(n_samples) + print("Performing kPCA with n_samples = %i" % n_samples) + + X_train = X[:n_samples, :] + X_test = X_train + + # A- reference (dense) + print(" - dense") + for i in range(n_iter): + start_time = time.perf_counter() + ref_pred = KernelPCA(n_components, eigen_solver="dense") \ + .fit(X_train).transform(X_test) + ref_time[j, i] = time.perf_counter() - start_time + + # B- arpack + if include_arpack: + print(" - arpack") + for i in range(n_iter): + start_time = time.perf_counter() + a_pred = KernelPCA(n_components, eigen_solver="arpack") \ + .fit(X_train).transform(X_test) + a_time[j, i] = time.perf_counter() - start_time + # check that the result is still correct despite the approx + assert_array_almost_equal(np.abs(a_pred), np.abs(ref_pred)) + + # C- randomized + print(" - randomized") + for i in range(n_iter): + start_time = time.perf_counter() + r_pred = KernelPCA(n_components, eigen_solver="randomized") \ + .fit(X_train).transform(X_test) + r_time[j, i] = time.perf_counter() - start_time + # check that the result is still correct despite the approximation + assert_array_almost_equal(np.abs(r_pred), np.abs(ref_pred)) + +# Compute statistics for the 3 methods +avg_ref_time = ref_time.mean(axis=1) +std_ref_time = ref_time.std(axis=1) +avg_a_time = a_time.mean(axis=1) +std_a_time = a_time.std(axis=1) +avg_r_time = r_time.mean(axis=1) +std_r_time = r_time.std(axis=1) + + +# 4- Plots +# -------- +fig, ax = plt.subplots(figsize=(12, 8)) + +# Display 1 plot with error bars per method +ax.errorbar(n_samples_range, avg_ref_time, yerr=std_ref_time, + marker='x', linestyle='', color='r', label='full') +if include_arpack: + ax.errorbar(n_samples_range, avg_a_time, yerr=std_a_time, marker='x', + linestyle='', color='g', label='arpack') +ax.errorbar(n_samples_range, avg_r_time, yerr=std_r_time, marker='x', + linestyle='', color='b', label='randomized') +ax.legend(loc='upper left') + +# customize axes +ax.set_xlim(min(n_samples_range) * 0.9, max(n_samples_range) * 1.1) +ax.set_ylabel("Execution time (s)") +ax.set_xlabel("n_samples") + +ax.set_title("Execution time comparison of kPCA with %i components on samples " + "with %i features, according to the choice of `eigen_solver`" + "" % (n_components, n_features)) + +plt.show() diff --git a/doc/modules/decomposition.rst b/doc/modules/decomposition.rst index e971d784c63d6..fd51f60d8bfc6 100644 --- a/doc/modules/decomposition.rst +++ b/doc/modules/decomposition.rst @@ -166,32 +166,16 @@ Note: the implementation of ``inverse_transform`` in :class:`PCA` with .. topic:: References: - * `"Finding structure with randomness: Stochastic algorithms for + * Algorithm 4.3 in + `"Finding structure with randomness: Stochastic algorithms for constructing approximate matrix decompositions" <https://arxiv.org/abs/0909.4061>`_ Halko, et al., 2009 - -.. _kernel_PCA: - -Kernel PCA ----------- - -:class:`KernelPCA` is an extension of PCA which achieves non-linear -dimensionality reduction through the use of kernels (see :ref:`metrics`). It -has many applications including denoising, compression and structured -prediction (kernel dependency estimation). :class:`KernelPCA` supports both -``transform`` and ``inverse_transform``. - -.. figure:: ../auto_examples/decomposition/images/sphx_glr_plot_kernel_pca_001.png - :target: ../auto_examples/decomposition/plot_kernel_pca.html - :align: center - :scale: 75% - -.. topic:: Examples: - - * :ref:`sphx_glr_auto_examples_decomposition_plot_kernel_pca.py` - + * `"An implementation of a randomized algorithm for principal component + analysis" + <https://arxiv.org/pdf/1412.3510.pdf>`_ + A. Szlam et al. 2014 .. _SparsePCA: @@ -278,6 +262,100 @@ factorization, while larger values shrink many coefficients to zero. R. Jenatton, G. Obozinski, F. Bach, 2009 +.. _kernel_PCA: + +Kernel Principal Component Analysis (kPCA) +========================================== + +Exact Kernel PCA +---------------- + +:class:`KernelPCA` is an extension of PCA which achieves non-linear +dimensionality reduction through the use of kernels (see :ref:`metrics`). It +has many applications including denoising, compression and structured +prediction (kernel dependency estimation). :class:`KernelPCA` supports both +``transform`` and ``inverse_transform``. + +.. figure:: ../auto_examples/decomposition/images/sphx_glr_plot_kernel_pca_001.png + :target: ../auto_examples/decomposition/plot_kernel_pca.html + :align: center + :scale: 75% + +.. topic:: Examples: + + * :ref:`sphx_glr_auto_examples_decomposition_plot_kernel_pca.py` + +.. topic:: References: + + * Kernel PCA was introduced in "Kernel principal component analysis" + Bernhard Schoelkopf, Alexander J. Smola, and Klaus-Robert Mueller. 1999. + In Advances in kernel methods, MIT Press, Cambridge, MA, USA 327-352. + + +.. _kPCA_Solvers: + +Choice of solver for Kernel PCA +------------------------------- + +While in :class:`PCA` the number of components is bounded by the number of +features, in :class:`KernelPCA` the number of components is bounded by the +number of samples. Many real-world datasets have large number of samples! In +these cases finding *all* the components with a full kPCA is a waste of +computation time, as data is mostly described by the first few components +(e.g. ``n_components<=100``). In other words, the centered Gram matrix that +is eigendecomposed in the Kernel PCA fitting process has an effective rank that +is much smaller than its size. This is a situation where approximate +eigensolvers can provide speedup with very low precision loss. + +The optional parameter ``eigen_solver='randomized'`` can be used to +*significantly* reduce the computation time when the number of requested +``n_components`` is small compared with the number of samples. It relies on +randomized decomposition methods to find an approximate solution in a shorter +time. + +The time complexity of the randomized :class:`KernelPCA` is +:math:`O(n_{\mathrm{samples}}^2 \cdot n_{\mathrm{components}})` +instead of :math:`O(n_{\mathrm{samples}}^3)` for the exact method +implemented with ``eigen_solver='dense'``. + +The memory footprint of randomized :class:`KernelPCA` is also proportional to +:math:`2 \cdot n_{\mathrm{samples}} \cdot n_{\mathrm{components}}` instead of +:math:`n_{\mathrm{samples}}^2` for the exact method. + +Note: this technique is the same as in :ref:`RandomizedPCA`. + +In addition to the above two solvers, ``eigen_solver='arpack'`` can be used as +an alternate way to get an approximate decomposition. In practice, this method +only provides reasonable execution times when the number of components to find +is extremely small. It is enabled by default when the desired number of +components is less than 10 (strict) and the number of samples is more than 200 +(strict). See :class:`KernelPCA` for details. + +.. topic:: References: + + * *dense* solver: + `scipy.linalg.eigh documentation + <https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.eigh.html>`_ + + * *randomized* solver: + + - Algorithm 4.3 in + `"Finding structure with randomness: Stochastic algorithms for + constructing approximate matrix decompositions" + <https://arxiv.org/abs/0909.4061>`_ + Halko, et al., 2009 + + - `"An implementation of a randomized algorithm for principal component + analysis" + <https://arxiv.org/pdf/1412.3510.pdf>`_ + A. Szlam et al. 2014 + + * *arpack* solver: + `scipy.sparse.linalg.eigsh documentation + <https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.linalg.eigsh.html>`_ + R. B. Lehoucq, D. C. Sorensen, and C. Yang, 1998 + + .. _LSA: Truncated singular value decomposition and latent semantic analysis diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index 3b3884e68e185..e89eecfe0874c 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -159,14 +159,17 @@ Changelog - |Fix| Fixes incorrect multiple data-conversion warnings when clustering boolean data. :pr:`19046` by :user:`Surya Prakash <jdsurya>`. -:mod:`sklearn.decomposition` -............................ - - |Fix| Fixed :func:`dict_learning`, used by :class:`DictionaryLearning`, to ensure determinism of the output. Achieved by flipping signs of the SVD output which is used to initialize the code. :pr:`18433` by :user:`Bruno Charron <brcharron>`. +- |Enhancement| added a new approximate solver (randomized SVD, available with + `eigen_solver='randomized'`) to :class:`decomposition.KernelPCA`. This + significantly accelerates computation when the number of samples is much + larger than the desired number of components. + :pr:`12069` by :user:`Sylvain Marié <smarie>`. + - |Fix| Fixed a bug in :class:`MiniBatchDictionaryLearning`, :class:`MiniBatchSparsePCA` and :func:`dict_learning_online` where the update of the dictionary was incorrect. :pr:`19198` by @@ -389,8 +392,8 @@ Changelog supporting sparse matrix and raise the appropriate error message. :pr:`19879` by :user:`Guillaume Lemaitre <glemaitre>`. -- |Efficiency| Changed ``algorithm`` argument for :class:`cluster.KMeans` in - :class:`preprocessing.KBinsDiscretizer` from ``auto`` to ``full``. +- |Efficiency| Changed ``algorithm`` argument for :class:`cluster.KMeans` in + :class:`preprocessing.KBinsDiscretizer` from ``auto`` to ``full``. :pr:`19934` by :user:`Gleb Levitskiy <GLevV>`. :mod:`sklearn.tree` diff --git a/sklearn/decomposition/_kernel_pca.py b/sklearn/decomposition/_kernel_pca.py index 415ee034c1769..8663193a8383e 100644 --- a/sklearn/decomposition/_kernel_pca.py +++ b/sklearn/decomposition/_kernel_pca.py @@ -1,6 +1,7 @@ """Kernel Principal Components Analysis.""" # Author: Mathieu Blondel <[email protected]> +# Sylvain Marie <[email protected]> # License: BSD 3 clause import numpy as np @@ -8,7 +9,7 @@ from scipy.sparse.linalg import eigsh from ..utils._arpack import _init_arpack_v0 -from ..utils.extmath import svd_flip +from ..utils.extmath import svd_flip, _randomized_eigsh from ..utils.validation import check_is_fitted, _check_psd_eigenvalues from ..utils.deprecation import deprecated from ..exceptions import NotFittedError @@ -24,6 +25,12 @@ class KernelPCA(TransformerMixin, BaseEstimator): Non-linear dimensionality reduction through the use of kernels (see :ref:`metrics`). + It uses the `scipy.linalg.eigh` LAPACK implementation of the full SVD or + the `scipy.sparse.linalg.eigsh` ARPACK implementation of the truncated SVD, + depending on the shape of the input data and the number of components to + extract. It can also use a randomized truncated SVD by the method of + Halko et al. 2009, see `eigen_solver`. + Read more in the :ref:`User Guide <kernel_PCA>`. Parameters @@ -59,10 +66,37 @@ class KernelPCA(TransformerMixin, BaseEstimator): Learn the inverse transform for non-precomputed kernels. (i.e. learn to find the pre-image of a point) - eigen_solver : {'auto', 'dense', 'arpack'}, default='auto' - Select eigensolver to use. If n_components is much less than - the number of training samples, arpack may be more efficient - than the dense eigensolver. + eigen_solver : {'auto', 'dense', 'arpack', 'randomized'}, \ + default='auto' + Select eigensolver to use. If `n_components` is much + less than the number of training samples, randomized (or arpack to a + smaller extend) may be more efficient than the dense eigensolver. + Randomized SVD is performed according to the method of Halko et al. + + auto : + the solver is selected by a default policy based on n_samples + (the number of training samples) and `n_components`: + if the number of components to extract is less than 10 (strict) and + the number of samples is more than 200 (strict), the 'arpack' + method is enabled. Otherwise the exact full eigenvalue + decomposition is computed and optionally truncated afterwards + ('dense' method). + dense : + run exact full eigenvalue decomposition calling the standard + LAPACK solver via `scipy.linalg.eigh`, and select the components + by postprocessing + arpack : + run SVD truncated to n_components calling ARPACK solver using + `scipy.sparse.linalg.eigsh`. It requires strictly + 0 < n_components < n_samples + randomized : + run randomized SVD by the method of Halko et al. The current + implementation selects eigenvalues based on their module; therefore + using this method can lead to unexpected results if the kernel is + not positive semi-definite. + + .. versionchanged:: 1.0 + `'randomized'` was added. tol : float, default=0 Convergence tolerance for arpack. @@ -72,6 +106,13 @@ class KernelPCA(TransformerMixin, BaseEstimator): Maximum number of iterations for arpack. If None, optimal value will be chosen by arpack. + iterated_power : int >= 0, or 'auto', default='auto' + Number of iterations for the power method computed by + svd_solver == 'randomized'. When 'auto', it is set to 7 when + `n_components < 0.1 * min(X.shape)`, other it is set to 4. + + .. versionadded:: 1.0 + remove_zero_eig : bool, default=False If True, then all components with zero eigenvalues are removed, so that the number of components in the output may be < n_components @@ -80,8 +121,8 @@ class KernelPCA(TransformerMixin, BaseEstimator): with zero eigenvalues are removed regardless. random_state : int, RandomState instance or None, default=None - Used when ``eigen_solver`` == 'arpack'. Pass an int for reproducible - results across multiple function calls. + Used when ``eigen_solver`` == 'arpack' or 'randomized'. Pass an int + for reproducible results across multiple function calls. See :term:`Glossary <random_state>`. .. versionadded:: 0.18 @@ -141,12 +182,22 @@ class KernelPCA(TransformerMixin, BaseEstimator): and Klaus-Robert Mueller. 1999. Kernel principal component analysis. In Advances in kernel methods, MIT Press, Cambridge, MA, USA 327-352. + + For eigen_solver == 'arpack', refer to `scipy.sparse.linalg.eigsh`. + + For eigen_solver == 'randomized', see: + Finding structure with randomness: Stochastic algorithms + for constructing approximate matrix decompositions Halko, et al., 2009 + (arXiv:909) + A randomized algorithm for the decomposition of matrices + Per-Gunnar Martinsson, Vladimir Rokhlin and Mark Tygert """ @_deprecate_positional_args def __init__(self, n_components=None, *, kernel="linear", gamma=None, degree=3, coef0=1, kernel_params=None, alpha=1.0, fit_inverse_transform=False, eigen_solver='auto', - tol=0, max_iter=None, remove_zero_eig=False, + tol=0, max_iter=None, iterated_power='auto', + remove_zero_eig=False, random_state=None, copy_X=True, n_jobs=None): if fit_inverse_transform and kernel == 'precomputed': raise ValueError( @@ -160,9 +211,10 @@ def __init__(self, n_components=None, *, kernel="linear", self.alpha = alpha self.fit_inverse_transform = fit_inverse_transform self.eigen_solver = eigen_solver - self.remove_zero_eig = remove_zero_eig self.tol = tol self.max_iter = max_iter + self.iterated_power = iterated_power + self.remove_zero_eig = remove_zero_eig self.random_state = random_state self.n_jobs = n_jobs self.copy_X = copy_X @@ -191,9 +243,14 @@ def _fit_transform(self, K): # center kernel K = self._centerer.fit_transform(K) + # adjust n_components according to user inputs if self.n_components is None: - n_components = K.shape[0] + n_components = K.shape[0] # use all dimensions else: + if self.n_components < 1: + raise ValueError( + f"`n_components` should be >= 1, got: {self.n_component}" + ) n_components = min(K.shape[0], self.n_components) # compute eigenvectors @@ -206,6 +263,7 @@ def _fit_transform(self, K): eigen_solver = self.eigen_solver if eigen_solver == 'dense': + # Note: eigvals specifies the indices of smallest/largest to return self.lambdas_, self.alphas_ = linalg.eigh( K, eigvals=(K.shape[0] - n_components, K.shape[0] - 1)) elif eigen_solver == 'arpack': @@ -215,6 +273,14 @@ def _fit_transform(self, K): tol=self.tol, maxiter=self.max_iter, v0=v0) + elif eigen_solver == 'randomized': + self.lambdas_, self.alphas_ = _randomized_eigsh( + K, n_components=n_components, n_iter=self.iterated_power, + random_state=self.random_state, selection='module' + ) + else: + raise ValueError("Unsupported value for `eigen_solver`: %r" + % eigen_solver) # make sure that the eigenvalues are ok and fix numerical issues self.lambdas_ = _check_psd_eigenvalues(self.lambdas_, diff --git a/sklearn/utils/extmath.py b/sklearn/utils/extmath.py index add8c5883a751..c72c54bd1aa4d 100644 --- a/sklearn/utils/extmath.py +++ b/sklearn/utils/extmath.py @@ -249,6 +249,9 @@ def randomized_svd(M, n_components, *, n_oversamples=10, n_iter='auto', flip_sign=True, random_state='warn'): """Computes a truncated randomized SVD. + This method solves the fixed-rank approximation problem described in the + Halko et al paper (problem (1.5), p5). + Parameters ---------- M : {ndarray, sparse matrix} @@ -262,13 +265,23 @@ def randomized_svd(M, n_components, *, n_oversamples=10, n_iter='auto', to ensure proper conditioning. The total number of random vectors used to find the range of M is n_components + n_oversamples. Smaller number can improve speed but can negatively impact the quality of - approximation of singular vectors and singular values. + approximation of singular vectors and singular values. Users might wish + to increase this parameter up to `2*k - n_components` where k is the + effective rank, for large matrices, noisy problems, matrices with + slowly decaying spectrums, or to increase precision accuracy. See Halko + et al (pages 5, 23 and 26). n_iter : int or 'auto', default='auto' Number of power iterations. It can be used to deal with very noisy problems. When 'auto', it is set to 4, unless `n_components` is small - (< .1 * min(X.shape)) `n_iter` in which case is set to 7. - This improves precision with few components. + (< .1 * min(X.shape)) in which case `n_iter` is set to 7. + This improves precision with few components. Note that in general + users should rather increase `n_oversamples` before increasing `n_iter` + as the principle of the randomized method is to avoid usage of these + more costly power iterations steps. When `n_components` is equal + or greater to the effective matrix rank and the spectrum does not + present a slow decay, `n_iter=0` or `1` should even work fine in theory + (see Halko et al paper, page 9). .. versionchanged:: 0.18 @@ -316,12 +329,15 @@ def randomized_svd(M, n_components, *, n_oversamples=10, n_iter='auto', computations. It is particularly fast on large matrices on which you wish to extract only a small number of components. In order to obtain further speed up, `n_iter` can be set <=2 (at the cost of - loss of precision). + loss of precision). To increase the precision it is recommended to + increase `n_oversamples`, up to `2*k-n_components` where k is the + effective rank. Usually, `n_components` is chosen to be greater than k + so increasing `n_oversamples` up to `n_components` should be enough. References ---------- * Finding structure with randomness: Stochastic algorithms for constructing - approximate matrix decompositions + approximate matrix decompositions (Algorithm 4.3) Halko, et al., 2009 https://arxiv.org/abs/0909.4061 * A randomized algorithm for the decomposition of matrices @@ -393,6 +409,152 @@ def randomized_svd(M, n_components, *, n_oversamples=10, n_iter='auto', return U[:, :n_components], s[:n_components], Vt[:n_components, :] +@_deprecate_positional_args +def _randomized_eigsh(M, n_components, *, n_oversamples=10, n_iter='auto', + power_iteration_normalizer='auto', + selection='module', random_state=None): + """Computes a truncated eigendecomposition using randomized methods + + This method solves the fixed-rank approximation problem described in the + Halko et al paper. + + The choice of which components to select can be tuned with the `selection` + parameter. + + .. versionadded:: 0.24 + + Parameters + ---------- + M : ndarray or sparse matrix + Matrix to decompose, it should be real symmetric square or complex + hermitian + + n_components : int + Number of eigenvalues and vectors to extract. + + n_oversamples : int, default=10 + Additional number of random vectors to sample the range of M so as + to ensure proper conditioning. The total number of random vectors + used to find the range of M is n_components + n_oversamples. Smaller + number can improve speed but can negatively impact the quality of + approximation of eigenvectors and eigenvalues. Users might wish + to increase this parameter up to `2*k - n_components` where k is the + effective rank, for large matrices, noisy problems, matrices with + slowly decaying spectrums, or to increase precision accuracy. See Halko + et al (pages 5, 23 and 26). + + n_iter : int or 'auto', default='auto' + Number of power iterations. It can be used to deal with very noisy + problems. When 'auto', it is set to 4, unless `n_components` is small + (< .1 * min(X.shape)) in which case `n_iter` is set to 7. + This improves precision with few components. Note that in general + users should rather increase `n_oversamples` before increasing `n_iter` + as the principle of the randomized method is to avoid usage of these + more costly power iterations steps. When `n_components` is equal + or greater to the effective matrix rank and the spectrum does not + present a slow decay, `n_iter=0` or `1` should even work fine in theory + (see Halko et al paper, page 9). + + power_iteration_normalizer : {'auto', 'QR', 'LU', 'none'}, default='auto' + Whether the power iterations are normalized with step-by-step + QR factorization (the slowest but most accurate), 'none' + (the fastest but numerically unstable when `n_iter` is large, e.g. + typically 5 or larger), or 'LU' factorization (numerically stable + but can lose slightly in accuracy). The 'auto' mode applies no + normalization if `n_iter` <= 2 and switches to LU otherwise. + + selection : {'value', 'module'}, default='module' + Strategy used to select the n components. When `selection` is `'value'` + (not yet implemented, will become the default when implemented), the + components corresponding to the n largest eigenvalues are returned. + When `selection` is `'module'`, the components corresponding to the n + eigenvalues with largest modules are returned. + + random_state : int, RandomState instance, default=None + The seed of the pseudo random number generator to use when shuffling + the data, i.e. getting the random vectors to initialize the algorithm. + Pass an int for reproducible results across multiple function calls. + See :term:`Glossary <random_state>`. + + Notes + ----- + This algorithm finds a (usually very good) approximate truncated + eigendecomposition using randomized methods to speed up the computations. + + This method is particularly fast on large matrices on which + you wish to extract only a small number of components. In order to + obtain further speed up, `n_iter` can be set <=2 (at the cost of + loss of precision). To increase the precision it is recommended to + increase `n_oversamples`, up to `2*k-n_components` where k is the + effective rank. Usually, `n_components` is chosen to be greater than k + so increasing `n_oversamples` up to `n_components` should be enough. + + Strategy 'value': not implemented yet. + Algorithms 5.3, 5.4 and 5.5 in the Halko et al paper should provide good + condidates for a future implementation. + + Strategy 'module': + The principle is that for diagonalizable matrices, the singular values and + eigenvalues are related: if t is an eigenvalue of A, then :math:`|t|` is a + singular value of A. This method relies on a randomized SVD to find the n + singular components corresponding to the n singular values with largest + modules, and then uses the signs of the singular vectors to find the true + sign of t: if the sign of left and right singular vectors are different + then the corresponding eigenvalue is negative. + + Returns + ------- + eigvals : 1D array of shape (n_components,) containing the `n_components` + eigenvalues selected (see ``selection`` parameter). + eigvecs : 2D array of shape (M.shape[0], n_components) containing the + `n_components` eigenvectors corresponding to the `eigvals`, in the + corresponding order. Note that this follows the `scipy.linalg.eigh` + convention. + + See Also + -------- + :func:`randomized_svd` + + References + ---------- + * Finding structure with randomness: Stochastic algorithms for constructing + approximate matrix decompositions (Algorithm 4.3 for strategy 'module') + Halko, et al., 2009 https://arxiv.org/abs/0909.4061 + + """ + if selection == 'value': # pragma: no cover + # to do : an algorithm can be found in the Halko et al reference + raise NotImplementedError() + + elif selection == 'module': + # Note: no need for deterministic U and Vt (flip_sign=True), + # as we only use the dot product UVt afterwards + U, S, Vt = randomized_svd( + M, n_components=n_components, n_oversamples=n_oversamples, + n_iter=n_iter, + power_iteration_normalizer=power_iteration_normalizer, + flip_sign=False, random_state=random_state) + + eigvecs = U[:, :n_components] + eigvals = S[:n_components] + + # Conversion of Singular values into Eigenvalues: + # For any eigenvalue t, the corresponding singular value is |t|. + # So if there is a negative eigenvalue t, the corresponding singular + # value will be -t, and the left (U) and right (V) singular vectors + # will have opposite signs. + # Fastest way: see <https://stackoverflow.com/a/61974002/7262247> + diag_VtU = np.einsum('ji,ij->j', + Vt[:n_components, :], U[:, :n_components]) + signs = np.sign(diag_VtU) + eigvals = eigvals * signs + + else: # pragma: no cover + raise ValueError("Invalid `selection`: %r" % selection) + + return eigvals, eigvecs + + @_deprecate_positional_args def weighted_mode(a, w, *, axis=0): """Returns an array of the weighted modal (most common) value in a.
diff --git a/sklearn/decomposition/tests/test_kernel_pca.py b/sklearn/decomposition/tests/test_kernel_pca.py index adf68f1db1a6c..5c8d052a7aa14 100644 --- a/sklearn/decomposition/tests/test_kernel_pca.py +++ b/sklearn/decomposition/tests/test_kernel_pca.py @@ -3,11 +3,13 @@ import pytest from sklearn.utils._testing import (assert_array_almost_equal, - assert_allclose) + assert_array_equal, + assert_allclose) from sklearn.decomposition import PCA, KernelPCA from sklearn.datasets import make_circles from sklearn.datasets import make_blobs +from sklearn.exceptions import NotFittedError from sklearn.linear_model import Perceptron from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler @@ -17,6 +19,12 @@ def test_kernel_pca(): + """Nominal test for all solvers and all known kernels + a custom one + + It tests + - that fit_transform is equivalent to fit+transform + - that the shapes of transforms and inverse transforms are correct + """ rng = np.random.RandomState(0) X_fit = rng.random_sample((5, 4)) X_pred = rng.random_sample((2, 4)) @@ -26,7 +34,7 @@ def histogram(x, y, **kwargs): assert kwargs == {} # no kernel_params that we didn't ask for return np.minimum(x, y).sum() - for eigen_solver in ("auto", "dense", "arpack"): + for eigen_solver in ("auto", "dense", "arpack", "randomized"): for kernel in ("linear", "rbf", "poly", histogram): # histogram kernel produces singular matrix inside linalg.solve # XXX use a least-squares approximation? @@ -55,12 +63,31 @@ def histogram(x, y, **kwargs): assert X_pred2.shape == X_pred.shape +def test_kernel_pca_invalid_solver(): + """Check that kPCA raises an error if the solver parameter is invalid + + """ + with pytest.raises(ValueError): + KernelPCA(eigen_solver="unknown").fit(np.random.randn(10, 10)) + + def test_kernel_pca_invalid_parameters(): + """Check that kPCA raises an error if the parameters are invalid + + Tests fitting inverse transform with a precomputed kernel raises a + ValueError. + """ with pytest.raises(ValueError): KernelPCA(10, fit_inverse_transform=True, kernel='precomputed') def test_kernel_pca_consistent_transform(): + """Check robustness to mutations in the original training array + + Test that after fitting a kPCA model, it stays independent of any + mutation of the values of the original data object by relying on an + internal copy. + """ # X_fit_ needs to retain the old, unmodified copy of X state = np.random.RandomState(0) X = state.rand(10, 10) @@ -74,6 +101,10 @@ def test_kernel_pca_consistent_transform(): def test_kernel_pca_deterministic_output(): + """Test that Kernel PCA produces deterministic output + + Tests that the same inputs and random state produce the same output. + """ rng = np.random.RandomState(0) X = rng.rand(10, 10) eigen_solver = ('arpack', 'dense') @@ -89,15 +120,20 @@ def test_kernel_pca_deterministic_output(): def test_kernel_pca_sparse(): + """Test that kPCA works on a sparse data input. + + Same test as ``test_kernel_pca except inverse_transform`` since it's not + implemented for sparse matrices. + """ rng = np.random.RandomState(0) X_fit = sp.csr_matrix(rng.random_sample((5, 4))) X_pred = sp.csr_matrix(rng.random_sample((2, 4))) - for eigen_solver in ("auto", "arpack"): + for eigen_solver in ("auto", "arpack", "randomized"): for kernel in ("linear", "rbf", "poly"): # transform fit data kpca = KernelPCA(4, kernel=kernel, eigen_solver=eigen_solver, - fit_inverse_transform=False) + fit_inverse_transform=False, random_state=0) X_fit_transformed = kpca.fit_transform(X_fit) X_fit_transformed2 = kpca.fit(X_fit).transform(X_fit) assert_array_almost_equal(np.abs(X_fit_transformed), @@ -108,31 +144,47 @@ def test_kernel_pca_sparse(): assert (X_pred_transformed.shape[1] == X_fit_transformed.shape[1]) - # inverse transform - # X_pred2 = kpca.inverse_transform(X_pred_transformed) - # assert X_pred2.shape == X_pred.shape) + # inverse transform: not available for sparse matrices + # XXX: should we raise another exception type here? For instance: + # NotImplementedError. + with pytest.raises(NotFittedError): + kpca.inverse_transform(X_pred_transformed) -def test_kernel_pca_linear_kernel(): [email protected]("solver", ["auto", "dense", "arpack", "randomized"]) [email protected]("n_features", [4, 10]) +def test_kernel_pca_linear_kernel(solver, n_features): + """Test that kPCA with linear kernel is equivalent to PCA for all solvers. + + KernelPCA with linear kernel should produce the same output as PCA. + """ rng = np.random.RandomState(0) - X_fit = rng.random_sample((5, 4)) - X_pred = rng.random_sample((2, 4)) + X_fit = rng.random_sample((5, n_features)) + X_pred = rng.random_sample((2, n_features)) # for a linear kernel, kernel PCA should find the same projection as PCA # modulo the sign (direction) # fit only the first four components: fifth is near zero eigenvalue, so # can be trimmed due to roundoff error + n_comps = 3 if solver == "arpack" else 4 assert_array_almost_equal( - np.abs(KernelPCA(4).fit(X_fit).transform(X_pred)), - np.abs(PCA(4).fit(X_fit).transform(X_pred))) + np.abs(KernelPCA(n_comps, eigen_solver=solver).fit(X_fit) + .transform(X_pred)), + np.abs(PCA(n_comps, svd_solver=solver if solver != "dense" else "full") + .fit(X_fit).transform(X_pred))) def test_kernel_pca_n_components(): + """Test that `n_components` is correctly taken into account for projections + + For all solvers this tests that the output has the correct shape depending + on the selected number of components. + """ rng = np.random.RandomState(0) X_fit = rng.random_sample((5, 4)) X_pred = rng.random_sample((2, 4)) - for eigen_solver in ("dense", "arpack"): + for eigen_solver in ("dense", "arpack", "randomized"): for c in [1, 2, 4]: kpca = KernelPCA(n_components=c, eigen_solver=eigen_solver) shape = kpca.fit(X_fit).transform(X_pred).shape @@ -141,6 +193,11 @@ def test_kernel_pca_n_components(): def test_remove_zero_eig(): + """Check that the ``remove_zero_eig`` parameter works correctly. + + Tests that the null-space (Zero) eigenvalues are removed when + remove_zero_eig=True, whereas they are not by default. + """ X = np.array([[1 - 1e-30, 1], [1, 1], [1, 1 - 1e-20]]) # n_components=None (default) => remove_zero_eig is True @@ -158,9 +215,11 @@ def test_remove_zero_eig(): def test_leave_zero_eig(): - """This test checks that fit().transform() returns the same result as + """Non-regression test for issue #12141 (PR #12143) + + This test checks that fit().transform() returns the same result as fit_transform() in case of non-removed zero eigenvalue. - Non-regression test for issue #12141 (PR #12143)""" + """ X_fit = np.array([[1, 1], [0, 0]]) # Assert that even with all np warnings on, there is no div by zero warning @@ -184,23 +243,29 @@ def test_leave_zero_eig(): def test_kernel_pca_precomputed(): + """Test that kPCA works with a precomputed kernel, for all solvers + + """ rng = np.random.RandomState(0) X_fit = rng.random_sample((5, 4)) X_pred = rng.random_sample((2, 4)) - for eigen_solver in ("dense", "arpack"): - X_kpca = KernelPCA(4, eigen_solver=eigen_solver).\ - fit(X_fit).transform(X_pred) + for eigen_solver in ("dense", "arpack", "randomized"): + X_kpca = KernelPCA( + 4, eigen_solver=eigen_solver, random_state=0 + ).fit(X_fit).transform(X_pred) + X_kpca2 = KernelPCA( - 4, eigen_solver=eigen_solver, kernel='precomputed').fit( - np.dot(X_fit, X_fit.T)).transform(np.dot(X_pred, X_fit.T)) + 4, eigen_solver=eigen_solver, kernel='precomputed', random_state=0 + ).fit(np.dot(X_fit, X_fit.T)).transform(np.dot(X_pred, X_fit.T)) X_kpca_train = KernelPCA( - 4, eigen_solver=eigen_solver, - kernel='precomputed').fit_transform(np.dot(X_fit, X_fit.T)) + 4, eigen_solver=eigen_solver, kernel='precomputed', random_state=0 + ).fit_transform(np.dot(X_fit, X_fit.T)) + X_kpca_train2 = KernelPCA( - 4, eigen_solver=eigen_solver, kernel='precomputed').fit( - np.dot(X_fit, X_fit.T)).transform(np.dot(X_fit, X_fit.T)) + 4, eigen_solver=eigen_solver, kernel='precomputed', random_state=0 + ).fit(np.dot(X_fit, X_fit.T)).transform(np.dot(X_fit, X_fit.T)) assert_array_almost_equal(np.abs(X_kpca), np.abs(X_kpca2)) @@ -209,7 +274,42 @@ def test_kernel_pca_precomputed(): np.abs(X_kpca_train2)) [email protected]("solver", ["auto", "dense", "arpack", "randomized"]) +def test_kernel_pca_precomputed_non_symmetric(solver): + """Check that the kernel centerer works. + + Tests that a non symmetric precomputed kernel is actually accepted + because the kernel centerer does its job correctly. + """ + + # a non symmetric gram matrix + K = [ + [1, 2], + [3, 40] + ] + kpca = KernelPCA(kernel="precomputed", eigen_solver=solver, + n_components=1, random_state=0) + kpca.fit(K) # no error + + # same test with centered kernel + Kc = [ + [9, -9], + [-9, 9] + ] + kpca_c = KernelPCA(kernel="precomputed", eigen_solver=solver, + n_components=1, random_state=0) + kpca_c.fit(Kc) + + # comparison between the non-centered and centered versions + assert_array_equal(kpca.alphas_, kpca_c.alphas_) + assert_array_equal(kpca.lambdas_, kpca_c.lambdas_) + + def test_kernel_pca_invalid_kernel(): + """Tests that using an invalid kernel name raises a ValueError + + An invalid kernel name should raise a ValueError at fit time. + """ rng = np.random.RandomState(0) X_fit = rng.random_sample((2, 4)) kpca = KernelPCA(kernel="tototiti") @@ -218,8 +318,11 @@ def test_kernel_pca_invalid_kernel(): def test_gridsearch_pipeline(): - # Test if we can do a grid-search to find parameters to separate - # circles with a perceptron model. + """Check that kPCA works as expected in a grid search pipeline + + Test if we can do a grid-search to find parameters to separate + circles with a perceptron model. + """ X, y = make_circles(n_samples=400, factor=.3, noise=.05, random_state=0) kpca = KernelPCA(kernel="rbf", n_components=2) @@ -232,8 +335,11 @@ def test_gridsearch_pipeline(): def test_gridsearch_pipeline_precomputed(): - # Test if we can do a grid-search to find parameters to separate - # circles with a perceptron model using a precomputed kernel. + """Check that kPCA works as expected in a grid search pipeline (2) + + Test if we can do a grid-search to find parameters to separate + circles with a perceptron model. This test uses a precomputed kernel. + """ X, y = make_circles(n_samples=400, factor=.3, noise=.05, random_state=0) kpca = KernelPCA(kernel="precomputed", n_components=2) @@ -247,7 +353,12 @@ def test_gridsearch_pipeline_precomputed(): def test_nested_circles(): - # Test the linear separability of the first 2D KPCA transform + """Check that kPCA projects in a space where nested circles are separable + + Tests that 2D nested circles become separable with a perceptron when + projected in the first 2 kPCA using an RBF kernel, while raw samples + are not directly separable in the original space. + """ X, y = make_circles(n_samples=400, factor=.3, noise=.05, random_state=0) @@ -270,8 +381,10 @@ def test_nested_circles(): def test_kernel_conditioning(): - """ Test that ``_check_psd_eigenvalues`` is correctly called - Non-regression test for issue #12140 (PR #12145)""" + """Check that ``_check_psd_eigenvalues`` is correctly called in kPCA + + Non-regression test for issue #12140 (PR #12145). + """ # create a pathological X leading to small non-zero eigenvalue X = [[5, 1], @@ -286,11 +399,93 @@ def test_kernel_conditioning(): assert np.all(kpca.lambdas_ == _check_psd_eigenvalues(kpca.lambdas_)) [email protected]("solver", ["auto", "dense", "arpack", "randomized"]) +def test_precomputed_kernel_not_psd(solver): + """Check how KernelPCA works with non-PSD kernels depending on n_components + + Tests for all methods what happens with a non PSD gram matrix (this + can happen in an isomap scenario, or with custom kernel functions, or + maybe with ill-posed datasets). + + When ``n_component`` is large enough to capture a negative eigenvalue, an + error should be raised. Otherwise, KernelPCA should run without error + since the negative eigenvalues are not selected. + """ + + # a non PSD kernel with large eigenvalues, already centered + # it was captured from an isomap call and multiplied by 100 for compacity + K = [ + [4.48, -1., 8.07, 2.33, 2.33, 2.33, -5.76, -12.78], + [-1., -6.48, 4.5, -1.24, -1.24, -1.24, -0.81, 7.49], + [8.07, 4.5, 15.48, 2.09, 2.09, 2.09, -11.1, -23.23], + [2.33, -1.24, 2.09, 4., -3.65, -3.65, 1.02, -0.9], + [2.33, -1.24, 2.09, -3.65, 4., -3.65, 1.02, -0.9], + [2.33, -1.24, 2.09, -3.65, -3.65, 4., 1.02, -0.9], + [-5.76, -0.81, -11.1, 1.02, 1.02, 1.02, 4.86, 9.75], + [-12.78, 7.49, -23.23, -0.9, -0.9, -0.9, 9.75, 21.46] + ] + # this gram matrix has 5 positive eigenvalues and 3 negative ones + # [ 52.72, 7.65, 7.65, 5.02, 0. , -0. , -6.13, -15.11] + + # 1. ask for enough components to get a significant negative one + kpca = KernelPCA(kernel="precomputed", eigen_solver=solver, n_components=7) + # make sure that the appropriate error is raised + with pytest.raises(ValueError, + match="There are significant negative eigenvalues"): + kpca.fit(K) + + # 2. ask for a small enough n_components to get only positive ones + kpca = KernelPCA(kernel="precomputed", eigen_solver=solver, n_components=2) + if solver == 'randomized': + # the randomized method is still inconsistent with the others on this + # since it selects the eigenvalues based on the largest 2 modules, not + # on the largest 2 values. + # + # At least we can ensure that we return an error instead of returning + # the wrong eigenvalues + with pytest.raises(ValueError, + match="There are significant negative eigenvalues"): + kpca.fit(K) + else: + # general case: make sure that it works + kpca.fit(K) + + [email protected]("n_components", [4, 10, 20]) +def test_kernel_pca_solvers_equivalence(n_components): + """Check that 'dense' 'arpack' & 'randomized' solvers give similar results + """ + + # Generate random data + n_train, n_test = 2000, 100 + X, _ = make_circles(n_samples=(n_train + n_test), factor=.3, noise=.05, + random_state=0) + X_fit, X_pred = X[:n_train, :], X[n_train:, :] + + # reference (full) + ref_pred = KernelPCA(n_components, eigen_solver="dense", random_state=0 + ).fit(X_fit).transform(X_pred) + + # arpack + a_pred = KernelPCA(n_components, eigen_solver="arpack", random_state=0 + ).fit(X_fit).transform(X_pred) + # check that the result is still correct despite the approx + assert_array_almost_equal(np.abs(a_pred), np.abs(ref_pred)) + + # randomized + r_pred = KernelPCA(n_components, eigen_solver="randomized", random_state=0 + ).fit(X_fit).transform(X_pred) + # check that the result is still correct despite the approximation + assert_array_almost_equal(np.abs(r_pred), np.abs(ref_pred)) + + def test_kernel_pca_inverse_transform_reconstruction(): - # Test if the reconstruction is a good approximation. - # Note that in general it is not possible to get an arbitrarily good - # reconstruction because of kernel centering that does not - # preserve all the information of the original data. + """Test if the reconstruction is a good approximation. + + Note that in general it is not possible to get an arbitrarily good + reconstruction because of kernel centering that does not + preserve all the information of the original data. + """ X, *_ = make_blobs(n_samples=100, n_features=4, random_state=0) kpca = KernelPCA( @@ -302,8 +497,11 @@ def test_kernel_pca_inverse_transform_reconstruction(): def test_32_64_decomposition_shape(): - """ Test that the decomposition is similar for 32 and 64 bits data """ - # see https://github.com/scikit-learn/scikit-learn/issues/18146 + """Test that the decomposition is similar for 32 and 64 bits data + + Non regression test for + https://github.com/scikit-learn/scikit-learn/issues/18146 + """ X, y = make_blobs( n_samples=30, centers=[[0, 0, 0], [1, 1, 1]], @@ -321,6 +519,10 @@ def test_32_64_decomposition_shape(): # TODO: Remove in 1.1 def test_kernel_pcc_pairwise_is_deprecated(): + """Check that `_pairwise` is correctly marked with deprecation warning + + Tests that a `FutureWarning` is issued when `_pairwise` is accessed. + """ kp = KernelPCA(kernel='precomputed') msg = r"Attribute _pairwise was deprecated in version 0\.24" with pytest.warns(FutureWarning, match=msg): diff --git a/sklearn/utils/tests/test_extmath.py b/sklearn/utils/tests/test_extmath.py index 8e53d94d911f0..1a77d08b12388 100644 --- a/sklearn/utils/tests/test_extmath.py +++ b/sklearn/utils/tests/test_extmath.py @@ -8,11 +8,12 @@ from scipy import sparse from scipy import linalg from scipy import stats +from scipy.sparse.linalg import eigsh from scipy.special import expit import pytest from sklearn.utils import gen_batches - +from sklearn.utils._arpack import _init_arpack_v0 from sklearn.utils._testing import assert_almost_equal from sklearn.utils._testing import assert_allclose from sklearn.utils._testing import assert_allclose_dense_sparse @@ -23,7 +24,7 @@ from sklearn.utils._testing import skip_if_32bit from sklearn.utils.extmath import density, _safe_accumulator_op -from sklearn.utils.extmath import randomized_svd +from sklearn.utils.extmath import randomized_svd, _randomized_eigsh from sklearn.utils.extmath import row_norms from sklearn.utils.extmath import weighted_mode from sklearn.utils.extmath import cartesian @@ -34,7 +35,7 @@ from sklearn.utils.extmath import softmax from sklearn.utils.extmath import stable_cumsum from sklearn.utils.extmath import safe_sparse_dot -from sklearn.datasets import make_low_rank_matrix +from sklearn.datasets import make_low_rank_matrix, make_sparse_spd_matrix def test_density(): @@ -161,6 +162,128 @@ def test_randomized_svd_low_rank_all_dtypes(dtype): check_randomized_svd_low_rank(dtype) [email protected]('dtype', + (np.int32, np.int64, np.float32, np.float64)) +def test_randomized_eigsh(dtype): + """Test that `_randomized_eigsh` returns the appropriate components""" + + rng = np.random.RandomState(42) + X = np.diag(np.array([1., -2., 0., 3.], dtype=dtype)) + # random rotation that preserves the eigenvalues of X + rand_rot = np.linalg.qr(rng.normal(size=X.shape))[0] + X = rand_rot @ X @ rand_rot.T + + # with 'module' selection method, the negative eigenvalue shows up + eigvals, eigvecs = _randomized_eigsh(X, n_components=2, selection='module') + # eigenvalues + assert eigvals.shape == (2,) + assert_array_almost_equal(eigvals, [3., -2.]) # negative eigenvalue here + # eigenvectors + assert eigvecs.shape == (4, 2) + + # with 'value' selection method, the negative eigenvalue does not show up + with pytest.raises(NotImplementedError): + _randomized_eigsh(X, n_components=2, selection='value') + + [email protected]('k', (10, 50, 100, 199, 200)) +def test_randomized_eigsh_compared_to_others(k): + """Check that `_randomized_eigsh` is similar to other `eigsh` + + Tests that for a random PSD matrix, `_randomized_eigsh` provides results + comparable to LAPACK (scipy.linalg.eigh) and ARPACK + (scipy.sparse.linalg.eigsh). + + Note: some versions of ARPACK do not support k=n_features. + """ + + # make a random PSD matrix + n_features = 200 + X = make_sparse_spd_matrix(n_features, random_state=0) + + # compare two versions of randomized + # rough and fast + eigvals, eigvecs = _randomized_eigsh(X, n_components=k, selection='module', + n_iter=25, random_state=0) + # more accurate but slow (TODO find realistic settings here) + eigvals_qr, eigvecs_qr = _randomized_eigsh( + X, n_components=k, n_iter=25, n_oversamples=20, random_state=0, + power_iteration_normalizer="QR", selection='module' + ) + + # with LAPACK + eigvals_lapack, eigvecs_lapack = linalg.eigh(X, eigvals=(n_features - k, + n_features - 1)) + indices = eigvals_lapack.argsort()[::-1] + eigvals_lapack = eigvals_lapack[indices] + eigvecs_lapack = eigvecs_lapack[:, indices] + + # -- eigenvalues comparison + assert eigvals_lapack.shape == (k,) + # comparison precision + assert_array_almost_equal(eigvals, eigvals_lapack, decimal=6) + assert_array_almost_equal(eigvals_qr, eigvals_lapack, decimal=6) + + # -- eigenvectors comparison + assert eigvecs_lapack.shape == (n_features, k) + # flip eigenvectors' sign to enforce deterministic output + dummy_vecs = np.zeros_like(eigvecs).T + eigvecs, _ = svd_flip(eigvecs, dummy_vecs) + eigvecs_qr, _ = svd_flip(eigvecs_qr, dummy_vecs) + eigvecs_lapack, _ = svd_flip(eigvecs_lapack, dummy_vecs) + assert_array_almost_equal(eigvecs, eigvecs_lapack, decimal=4) + assert_array_almost_equal(eigvecs_qr, eigvecs_lapack, decimal=6) + + # comparison ARPACK ~ LAPACK (some ARPACK implems do not support k=n) + if k < n_features: + v0 = _init_arpack_v0(n_features, random_state=0) + # "LA" largest algebraic <=> selection="value" in randomized_eigsh + eigvals_arpack, eigvecs_arpack = eigsh(X, k, which="LA", tol=0, + maxiter=None, v0=v0) + indices = eigvals_arpack.argsort()[::-1] + # eigenvalues + eigvals_arpack = eigvals_arpack[indices] + assert_array_almost_equal(eigvals_lapack, eigvals_arpack, decimal=10) + # eigenvectors + eigvecs_arpack = eigvecs_arpack[:, indices] + eigvecs_arpack, _ = svd_flip(eigvecs_arpack, dummy_vecs) + assert_array_almost_equal(eigvecs_arpack, eigvecs_lapack, decimal=8) + + [email protected]("n,rank", [ + (10, 7), + (100, 10), + (100, 80), + (500, 10), + (500, 250), + (500, 400), +]) +def test_randomized_eigsh_reconst_low_rank(n, rank): + """Check that randomized_eigsh is able to reconstruct a low rank psd matrix + + Tests that the decomposition provided by `_randomized_eigsh` leads to + orthonormal eigenvectors, and that a low rank PSD matrix can be effectively + reconstructed with good accuracy using it. + """ + assert rank < n + + # create a low rank PSD + rng = np.random.RandomState(69) + X = rng.randn(n, rank) + A = X @ X.T + + # approximate A with the "right" number of components + S, V = _randomized_eigsh(A, n_components=rank, random_state=rng) + # orthonormality checks + assert_array_almost_equal(np.linalg.norm(V, axis=0), np.ones(S.shape)) + assert_array_almost_equal(V.T @ V, np.diag(np.ones(S.shape))) + # reconstruction + A_reconstruct = V @ np.diag(S) @ V.T + + # test that the approximation is good + assert_array_almost_equal(A_reconstruct, A, decimal=6) + + @pytest.mark.parametrize('dtype', (np.float32, np.float64)) def test_row_norms(dtype):
[ { "path": "doc/modules/decomposition.rst", "old_path": "a/doc/modules/decomposition.rst", "new_path": "b/doc/modules/decomposition.rst", "metadata": "diff --git a/doc/modules/decomposition.rst b/doc/modules/decomposition.rst\nindex e971d784c63d6..fd51f60d8bfc6 100644\n--- a/doc/modules/decomposition.rst\n+++ b/doc/modules/decomposition.rst\n@@ -166,32 +166,16 @@ Note: the implementation of ``inverse_transform`` in :class:`PCA` with\n \n .. topic:: References:\n \n- * `\"Finding structure with randomness: Stochastic algorithms for\n+ * Algorithm 4.3 in\n+ `\"Finding structure with randomness: Stochastic algorithms for\n constructing approximate matrix decompositions\"\n <https://arxiv.org/abs/0909.4061>`_\n Halko, et al., 2009\n \n-\n-.. _kernel_PCA:\n-\n-Kernel PCA\n-----------\n-\n-:class:`KernelPCA` is an extension of PCA which achieves non-linear\n-dimensionality reduction through the use of kernels (see :ref:`metrics`). It\n-has many applications including denoising, compression and structured\n-prediction (kernel dependency estimation). :class:`KernelPCA` supports both\n-``transform`` and ``inverse_transform``.\n-\n-.. figure:: ../auto_examples/decomposition/images/sphx_glr_plot_kernel_pca_001.png\n- :target: ../auto_examples/decomposition/plot_kernel_pca.html\n- :align: center\n- :scale: 75%\n-\n-.. topic:: Examples:\n-\n- * :ref:`sphx_glr_auto_examples_decomposition_plot_kernel_pca.py`\n-\n+ * `\"An implementation of a randomized algorithm for principal component\n+ analysis\"\n+ <https://arxiv.org/pdf/1412.3510.pdf>`_\n+ A. Szlam et al. 2014\n \n .. _SparsePCA:\n \n@@ -278,6 +262,100 @@ factorization, while larger values shrink many coefficients to zero.\n R. Jenatton, G. Obozinski, F. Bach, 2009\n \n \n+.. _kernel_PCA:\n+\n+Kernel Principal Component Analysis (kPCA)\n+==========================================\n+\n+Exact Kernel PCA\n+----------------\n+\n+:class:`KernelPCA` is an extension of PCA which achieves non-linear\n+dimensionality reduction through the use of kernels (see :ref:`metrics`). It\n+has many applications including denoising, compression and structured\n+prediction (kernel dependency estimation). :class:`KernelPCA` supports both\n+``transform`` and ``inverse_transform``.\n+\n+.. figure:: ../auto_examples/decomposition/images/sphx_glr_plot_kernel_pca_001.png\n+ :target: ../auto_examples/decomposition/plot_kernel_pca.html\n+ :align: center\n+ :scale: 75%\n+\n+.. topic:: Examples:\n+\n+ * :ref:`sphx_glr_auto_examples_decomposition_plot_kernel_pca.py`\n+\n+.. topic:: References:\n+\n+ * Kernel PCA was introduced in \"Kernel principal component analysis\"\n+ Bernhard Schoelkopf, Alexander J. Smola, and Klaus-Robert Mueller. 1999.\n+ In Advances in kernel methods, MIT Press, Cambridge, MA, USA 327-352.\n+\n+\n+.. _kPCA_Solvers:\n+\n+Choice of solver for Kernel PCA\n+-------------------------------\n+\n+While in :class:`PCA` the number of components is bounded by the number of\n+features, in :class:`KernelPCA` the number of components is bounded by the\n+number of samples. Many real-world datasets have large number of samples! In\n+these cases finding *all* the components with a full kPCA is a waste of\n+computation time, as data is mostly described by the first few components\n+(e.g. ``n_components<=100``). In other words, the centered Gram matrix that\n+is eigendecomposed in the Kernel PCA fitting process has an effective rank that\n+is much smaller than its size. This is a situation where approximate\n+eigensolvers can provide speedup with very low precision loss.\n+\n+The optional parameter ``eigen_solver='randomized'`` can be used to\n+*significantly* reduce the computation time when the number of requested\n+``n_components`` is small compared with the number of samples. It relies on\n+randomized decomposition methods to find an approximate solution in a shorter\n+time.\n+\n+The time complexity of the randomized :class:`KernelPCA` is\n+:math:`O(n_{\\mathrm{samples}}^2 \\cdot n_{\\mathrm{components}})`\n+instead of :math:`O(n_{\\mathrm{samples}}^3)` for the exact method\n+implemented with ``eigen_solver='dense'``.\n+\n+The memory footprint of randomized :class:`KernelPCA` is also proportional to\n+:math:`2 \\cdot n_{\\mathrm{samples}} \\cdot n_{\\mathrm{components}}` instead of\n+:math:`n_{\\mathrm{samples}}^2` for the exact method.\n+\n+Note: this technique is the same as in :ref:`RandomizedPCA`.\n+\n+In addition to the above two solvers, ``eigen_solver='arpack'`` can be used as\n+an alternate way to get an approximate decomposition. In practice, this method\n+only provides reasonable execution times when the number of components to find\n+is extremely small. It is enabled by default when the desired number of\n+components is less than 10 (strict) and the number of samples is more than 200\n+(strict). See :class:`KernelPCA` for details.\n+\n+.. topic:: References:\n+\n+ * *dense* solver:\n+ `scipy.linalg.eigh documentation\n+ <https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.eigh.html>`_\n+\n+ * *randomized* solver:\n+\n+ - Algorithm 4.3 in\n+ `\"Finding structure with randomness: Stochastic algorithms for\n+ constructing approximate matrix decompositions\"\n+ <https://arxiv.org/abs/0909.4061>`_\n+ Halko, et al., 2009\n+\n+ - `\"An implementation of a randomized algorithm for principal component\n+ analysis\"\n+ <https://arxiv.org/pdf/1412.3510.pdf>`_\n+ A. Szlam et al. 2014\n+\n+ * *arpack* solver:\n+ `scipy.sparse.linalg.eigsh documentation\n+ <https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.linalg.eigsh.html>`_\n+ R. B. Lehoucq, D. C. Sorensen, and C. Yang, 1998\n+\n+\n .. _LSA:\n \n Truncated singular value decomposition and latent semantic analysis\n" }, { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 3b3884e68e185..e89eecfe0874c 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -159,14 +159,17 @@ Changelog\n - |Fix| Fixes incorrect multiple data-conversion warnings when clustering\n boolean data. :pr:`19046` by :user:`Surya Prakash <jdsurya>`.\n \n-:mod:`sklearn.decomposition`\n-............................\n-\n - |Fix| Fixed :func:`dict_learning`, used by :class:`DictionaryLearning`, to\n ensure determinism of the output. Achieved by flipping signs of the SVD\n output which is used to initialize the code.\n :pr:`18433` by :user:`Bruno Charron <brcharron>`.\n \n+- |Enhancement| added a new approximate solver (randomized SVD, available with\n+ `eigen_solver='randomized'`) to :class:`decomposition.KernelPCA`. This\n+ significantly accelerates computation when the number of samples is much\n+ larger than the desired number of components.\n+ :pr:`12069` by :user:`Sylvain Marié <smarie>`.\n+\n - |Fix| Fixed a bug in :class:`MiniBatchDictionaryLearning`,\n :class:`MiniBatchSparsePCA` and :func:`dict_learning_online` where the\n update of the dictionary was incorrect. :pr:`19198` by\n@@ -389,8 +392,8 @@ Changelog\n supporting sparse matrix and raise the appropriate error message.\n :pr:`19879` by :user:`Guillaume Lemaitre <glemaitre>`.\n \n-- |Efficiency| Changed ``algorithm`` argument for :class:`cluster.KMeans` in \n- :class:`preprocessing.KBinsDiscretizer` from ``auto`` to ``full``. \n+- |Efficiency| Changed ``algorithm`` argument for :class:`cluster.KMeans` in\n+ :class:`preprocessing.KBinsDiscretizer` from ``auto`` to ``full``.\n :pr:`19934` by :user:`Gleb Levitskiy <GLevV>`.\n \n :mod:`sklearn.tree`\n" } ]
1.00
2641baf16d9de5191316745ec46120cc8b57a666
[ "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_deterministic_output", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_inverse_transform_reconstruction", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_linear_kernel[4-auto]", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_conditioning", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_precomputed_non_symmetric[dense]", "sklearn/decomposition/tests/test_kernel_pca.py::test_remove_zero_eig", "sklearn/decomposition/tests/test_kernel_pca.py::test_gridsearch_pipeline_precomputed", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_linear_kernel[10-arpack]", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_invalid_parameters", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pcc_pairwise_is_deprecated", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_linear_kernel[10-dense]", "sklearn/decomposition/tests/test_kernel_pca.py::test_precomputed_kernel_not_psd[auto]", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_precomputed_non_symmetric[arpack]", "sklearn/decomposition/tests/test_kernel_pca.py::test_precomputed_kernel_not_psd[dense]", "sklearn/decomposition/tests/test_kernel_pca.py::test_nested_circles", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_precomputed_non_symmetric[auto]", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_invalid_kernel", "sklearn/decomposition/tests/test_kernel_pca.py::test_gridsearch_pipeline", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_linear_kernel[4-dense]", "sklearn/decomposition/tests/test_kernel_pca.py::test_32_64_decomposition_shape", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_consistent_transform", "sklearn/decomposition/tests/test_kernel_pca.py::test_precomputed_kernel_not_psd[arpack]", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_linear_kernel[4-arpack]", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_linear_kernel[10-auto]" ]
[ "sklearn/utils/tests/test_extmath.py::test_randomized_svd_sign_flip_with_transpose", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10000000.0-1-1e-08-0]", "sklearn/utils/tests/test_extmath.py::test_uniform_weights", "sklearn/utils/tests/test_extmath.py::test_randomized_eigsh_reconst_low_rank[500-400]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1-1--10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10000000.0-1-1e-08--10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1-1e-08-0]", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_sparse", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_precomputed", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10000000.0-1-100000.0-0]", "sklearn/utils/tests/test_extmath.py::test_safe_sparse_dot_2d[sparse-dense]", "sklearn/utils/tests/test_extmath.py::test_incremental_mean_and_variance_ignore_nan", "sklearn/utils/tests/test_extmath.py::test_randomized_eigsh[float64]", "sklearn/utils/tests/test_extmath.py::test_randomized_eigsh_compared_to_others[200]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10-1-100000.0--10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1e-08-1e-08-0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance_ignore_nan[float64]", "sklearn/utils/tests/test_extmath.py::test_randomized_eigsh_compared_to_others[10]", "sklearn/utils/tests/test_extmath.py::test_randomized_svd_sparse_warnings", "sklearn/decomposition/tests/test_kernel_pca.py::test_precomputed_kernel_not_psd[randomized]", "sklearn/utils/tests/test_extmath.py::test_randomized_svd_low_rank_all_dtypes[int64]", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca", "sklearn/utils/tests/test_extmath.py::test_randomized_eigsh_compared_to_others[100]", "sklearn/utils/tests/test_extmath.py::test_softmax", "sklearn/utils/tests/test_extmath.py::test_randomized_eigsh_compared_to_others[50]", "sklearn/utils/tests/test_extmath.py::test_cartesian", "sklearn/utils/tests/test_extmath.py::test_randomized_svd_transpose_consistency", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_n_components", "sklearn/utils/tests/test_extmath.py::test_vector_sign_flip", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10000000.0-1-1-10000000.0]", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_precomputed_non_symmetric[randomized]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1e-08-1e-08-10000000.0]", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_solvers_equivalence[10]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10-1-1e-08-0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1e-08-1-0]", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_linear_kernel[4-randomized]", "sklearn/utils/tests/test_extmath.py::test_incremental_variance_update_formulas", "sklearn/utils/tests/test_extmath.py::test_svd_flip", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_invalid_solver", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10000000.0-1-100000.0--10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[1-1e-08-1-0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10-1-1e-08-10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10000000.0-1-1-0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1-1e-08--10000000.0]", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_solvers_equivalence[4]", "sklearn/utils/tests/test_extmath.py::test_randomized_eigsh[float32]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1e-08-100000.0-0]", "sklearn/utils/tests/test_extmath.py::test_randomized_svd_low_rank_all_dtypes[int32]", "sklearn/utils/tests/test_extmath.py::test_safe_sparse_dot_2d_1d[sparse]", "sklearn/utils/tests/test_extmath.py::test_randomized_svd_low_rank_all_dtypes[float64]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10000000.0-1-1e-08-10000000.0]", "sklearn/utils/tests/test_extmath.py::test_safe_sparse_dot_2d_1d[dense]", "sklearn/utils/tests/test_extmath.py::test_safe_sparse_dot_dense_output[True]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[1-1e-08-1--10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10000000.0-1-100000.0-10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[1-1e-08-100000.0-0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[1-1e-08-100000.0--10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1e-08-1e-08--10000000.0]", "sklearn/utils/tests/test_extmath.py::test_randomized_eigsh_reconst_low_rank[500-10]", "sklearn/utils/tests/test_extmath.py::test_randomized_svd_sign_flip", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_linear_kernel[10-randomized]", "sklearn/utils/tests/test_extmath.py::test_randomized_svd_low_rank_with_noise", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[1-1e-08-1e-08-10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance_simple[float64]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1-100000.0--10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1e-08-100000.0-10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[1-1e-08-1e-08--10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10-1-1-0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1e-08-1-10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance_ignore_nan[float32]", "sklearn/utils/tests/test_extmath.py::test_incremental_variance_ddof", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10000000.0-1-1--10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1e-08-1--10000000.0]", "sklearn/utils/tests/test_extmath.py::test_safe_sparse_dot_nd", "sklearn/utils/tests/test_extmath.py::test_row_norms[float64]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10-1-100000.0-10000000.0]", "sklearn/utils/tests/test_extmath.py::test_randomized_svd_infinite_rank", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10-1-100000.0-0]", "sklearn/utils/tests/test_extmath.py::test_randomized_eigsh[int32]", "sklearn/utils/tests/test_extmath.py::test_safe_sparse_dot_2d[sparse-sparse]", "sklearn/utils/tests/test_extmath.py::test_randomized_eigsh[int64]", "sklearn/utils/tests/test_extmath.py::test_safe_sparse_dot_dense_output[False]", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_solvers_equivalence[20]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance_simple[float32]", "sklearn/utils/tests/test_extmath.py::test_incremental_variance_numerical_stability", "sklearn/utils/tests/test_extmath.py::test_randomized_svd_power_iteration_normalizer", "sklearn/utils/tests/test_extmath.py::test_row_norms[float32]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[1-1e-08-1e-08-0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1-1e-08-10000000.0]", "sklearn/utils/tests/test_extmath.py::test_density", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10-1-1-10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1-1-0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10-1-1--10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10-1-1e-08--10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1-1-10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1-100000.0-0]", "sklearn/utils/tests/test_extmath.py::test_logistic_sigmoid", "sklearn/utils/tests/test_extmath.py::test_randomized_svd_low_rank_all_dtypes[float32]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1e-08-100000.0--10000000.0]", "sklearn/utils/tests/test_extmath.py::test_randomized_eigsh_compared_to_others[199]", "sklearn/utils/tests/test_extmath.py::test_safe_sparse_dot_2d[dense-dense]", "sklearn/utils/tests/test_extmath.py::test_stable_cumsum", "sklearn/utils/tests/test_extmath.py::test_randomized_eigsh_reconst_low_rank[100-80]", "sklearn/utils/tests/test_extmath.py::test_random_weights", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[1-1e-08-1-10000000.0]", "sklearn/utils/tests/test_extmath.py::test_randomized_eigsh_reconst_low_rank[500-250]", "sklearn/utils/tests/test_extmath.py::test_randomized_eigsh_reconst_low_rank[10-7]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1-100000.0-10000000.0]", "sklearn/utils/tests/test_extmath.py::test_safe_sparse_dot_2d[dense-sparse]", "sklearn/utils/tests/test_extmath.py::test_randomized_eigsh_reconst_low_rank[100-10]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[1-1e-08-100000.0-10000000.0]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [ { "type": "file", "name": "benchmarks/bench_kernel_pca_solvers_time_vs_n_samples.py" }, { "type": "file", "name": "benchmarks/bench_kernel_pca_solvers_time_vs_n_components.py" } ] }
[ { "path": "doc/modules/decomposition.rst", "old_path": "a/doc/modules/decomposition.rst", "new_path": "b/doc/modules/decomposition.rst", "metadata": "diff --git a/doc/modules/decomposition.rst b/doc/modules/decomposition.rst\nindex e971d784c63d6..fd51f60d8bfc6 100644\n--- a/doc/modules/decomposition.rst\n+++ b/doc/modules/decomposition.rst\n@@ -166,32 +166,16 @@ Note: the implementation of ``inverse_transform`` in :class:`PCA` with\n \n .. topic:: References:\n \n- * `\"Finding structure with randomness: Stochastic algorithms for\n+ * Algorithm 4.3 in\n+ `\"Finding structure with randomness: Stochastic algorithms for\n constructing approximate matrix decompositions\"\n <https://arxiv.org/abs/0909.4061>`_\n Halko, et al., 2009\n \n-\n-.. _kernel_PCA:\n-\n-Kernel PCA\n-----------\n-\n-:class:`KernelPCA` is an extension of PCA which achieves non-linear\n-dimensionality reduction through the use of kernels (see :ref:`metrics`). It\n-has many applications including denoising, compression and structured\n-prediction (kernel dependency estimation). :class:`KernelPCA` supports both\n-``transform`` and ``inverse_transform``.\n-\n-.. figure:: ../auto_examples/decomposition/images/sphx_glr_plot_kernel_pca_001.png\n- :target: ../auto_examples/decomposition/plot_kernel_pca.html\n- :align: center\n- :scale: 75%\n-\n-.. topic:: Examples:\n-\n- * :ref:`sphx_glr_auto_examples_decomposition_plot_kernel_pca.py`\n-\n+ * `\"An implementation of a randomized algorithm for principal component\n+ analysis\"\n+ <https://arxiv.org/pdf/1412.3510.pdf>`_\n+ A. Szlam et al. 2014\n \n .. _SparsePCA:\n \n@@ -278,6 +262,100 @@ factorization, while larger values shrink many coefficients to zero.\n R. Jenatton, G. Obozinski, F. Bach, 2009\n \n \n+.. _kernel_PCA:\n+\n+Kernel Principal Component Analysis (kPCA)\n+==========================================\n+\n+Exact Kernel PCA\n+----------------\n+\n+:class:`KernelPCA` is an extension of PCA which achieves non-linear\n+dimensionality reduction through the use of kernels (see :ref:`metrics`). It\n+has many applications including denoising, compression and structured\n+prediction (kernel dependency estimation). :class:`KernelPCA` supports both\n+``transform`` and ``inverse_transform``.\n+\n+.. figure:: ../auto_examples/decomposition/images/sphx_glr_plot_kernel_pca_001.png\n+ :target: ../auto_examples/decomposition/plot_kernel_pca.html\n+ :align: center\n+ :scale: 75%\n+\n+.. topic:: Examples:\n+\n+ * :ref:`sphx_glr_auto_examples_decomposition_plot_kernel_pca.py`\n+\n+.. topic:: References:\n+\n+ * Kernel PCA was introduced in \"Kernel principal component analysis\"\n+ Bernhard Schoelkopf, Alexander J. Smola, and Klaus-Robert Mueller. 1999.\n+ In Advances in kernel methods, MIT Press, Cambridge, MA, USA 327-352.\n+\n+\n+.. _kPCA_Solvers:\n+\n+Choice of solver for Kernel PCA\n+-------------------------------\n+\n+While in :class:`PCA` the number of components is bounded by the number of\n+features, in :class:`KernelPCA` the number of components is bounded by the\n+number of samples. Many real-world datasets have large number of samples! In\n+these cases finding *all* the components with a full kPCA is a waste of\n+computation time, as data is mostly described by the first few components\n+(e.g. ``n_components<=100``). In other words, the centered Gram matrix that\n+is eigendecomposed in the Kernel PCA fitting process has an effective rank that\n+is much smaller than its size. This is a situation where approximate\n+eigensolvers can provide speedup with very low precision loss.\n+\n+The optional parameter ``eigen_solver='randomized'`` can be used to\n+*significantly* reduce the computation time when the number of requested\n+``n_components`` is small compared with the number of samples. It relies on\n+randomized decomposition methods to find an approximate solution in a shorter\n+time.\n+\n+The time complexity of the randomized :class:`KernelPCA` is\n+:math:`O(n_{\\mathrm{samples}}^2 \\cdot n_{\\mathrm{components}})`\n+instead of :math:`O(n_{\\mathrm{samples}}^3)` for the exact method\n+implemented with ``eigen_solver='dense'``.\n+\n+The memory footprint of randomized :class:`KernelPCA` is also proportional to\n+:math:`2 \\cdot n_{\\mathrm{samples}} \\cdot n_{\\mathrm{components}}` instead of\n+:math:`n_{\\mathrm{samples}}^2` for the exact method.\n+\n+Note: this technique is the same as in :ref:`RandomizedPCA`.\n+\n+In addition to the above two solvers, ``eigen_solver='arpack'`` can be used as\n+an alternate way to get an approximate decomposition. In practice, this method\n+only provides reasonable execution times when the number of components to find\n+is extremely small. It is enabled by default when the desired number of\n+components is less than 10 (strict) and the number of samples is more than 200\n+(strict). See :class:`KernelPCA` for details.\n+\n+.. topic:: References:\n+\n+ * *dense* solver:\n+ `scipy.linalg.eigh documentation\n+ <https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.eigh.html>`_\n+\n+ * *randomized* solver:\n+\n+ - Algorithm 4.3 in\n+ `\"Finding structure with randomness: Stochastic algorithms for\n+ constructing approximate matrix decompositions\"\n+ <https://arxiv.org/abs/0909.4061>`_\n+ Halko, et al., 2009\n+\n+ - `\"An implementation of a randomized algorithm for principal component\n+ analysis\"\n+ <https://arxiv.org/pdf/1412.3510.pdf>`_\n+ A. Szlam et al. 2014\n+\n+ * *arpack* solver:\n+ `scipy.sparse.linalg.eigsh documentation\n+ <https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.linalg.eigsh.html>`_\n+ R. B. Lehoucq, D. C. Sorensen, and C. Yang, 1998\n+\n+\n .. _LSA:\n \n Truncated singular value decomposition and latent semantic analysis\n" }, { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 3b3884e68e185..e89eecfe0874c 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -159,14 +159,17 @@ Changelog\n - |Fix| Fixes incorrect multiple data-conversion warnings when clustering\n boolean data. :pr:`<PRID>` by :user:`<NAME>`.\n \n-:mod:`sklearn.decomposition`\n-............................\n-\n - |Fix| Fixed :func:`dict_learning`, used by :class:`DictionaryLearning`, to\n ensure determinism of the output. Achieved by flipping signs of the SVD\n output which is used to initialize the code.\n :pr:`<PRID>` by :user:`<NAME>`.\n \n+- |Enhancement| added a new approximate solver (randomized SVD, available with\n+ `eigen_solver='randomized'`) to :class:`decomposition.KernelPCA`. This\n+ significantly accelerates computation when the number of samples is much\n+ larger than the desired number of components.\n+ :pr:`<PRID>` by :user:`<NAME>`.\n+\n - |Fix| Fixed a bug in :class:`MiniBatchDictionaryLearning`,\n :class:`MiniBatchSparsePCA` and :func:`dict_learning_online` where the\n update of the dictionary was incorrect. :pr:`<PRID>` by\n@@ -389,8 +392,8 @@ Changelog\n supporting sparse matrix and raise the appropriate error message.\n :pr:`<PRID>` by :user:`<NAME>`.\n \n-- |Efficiency| Changed ``algorithm`` argument for :class:`cluster.KMeans` in \n- :class:`preprocessing.KBinsDiscretizer` from ``auto`` to ``full``. \n+- |Efficiency| Changed ``algorithm`` argument for :class:`cluster.KMeans` in\n+ :class:`preprocessing.KBinsDiscretizer` from ``auto`` to ``full``.\n :pr:`<PRID>` by :user:`<NAME>`.\n \n :mod:`sklearn.tree`\n" } ]
diff --git a/doc/modules/decomposition.rst b/doc/modules/decomposition.rst index e971d784c63d6..fd51f60d8bfc6 100644 --- a/doc/modules/decomposition.rst +++ b/doc/modules/decomposition.rst @@ -166,32 +166,16 @@ Note: the implementation of ``inverse_transform`` in :class:`PCA` with .. topic:: References: - * `"Finding structure with randomness: Stochastic algorithms for + * Algorithm 4.3 in + `"Finding structure with randomness: Stochastic algorithms for constructing approximate matrix decompositions" <https://arxiv.org/abs/0909.4061>`_ Halko, et al., 2009 - -.. _kernel_PCA: - -Kernel PCA ----------- - -:class:`KernelPCA` is an extension of PCA which achieves non-linear -dimensionality reduction through the use of kernels (see :ref:`metrics`). It -has many applications including denoising, compression and structured -prediction (kernel dependency estimation). :class:`KernelPCA` supports both -``transform`` and ``inverse_transform``. - -.. figure:: ../auto_examples/decomposition/images/sphx_glr_plot_kernel_pca_001.png - :target: ../auto_examples/decomposition/plot_kernel_pca.html - :align: center - :scale: 75% - -.. topic:: Examples: - - * :ref:`sphx_glr_auto_examples_decomposition_plot_kernel_pca.py` - + * `"An implementation of a randomized algorithm for principal component + analysis" + <https://arxiv.org/pdf/1412.3510.pdf>`_ + A. Szlam et al. 2014 .. _SparsePCA: @@ -278,6 +262,100 @@ factorization, while larger values shrink many coefficients to zero. R. Jenatton, G. Obozinski, F. Bach, 2009 +.. _kernel_PCA: + +Kernel Principal Component Analysis (kPCA) +========================================== + +Exact Kernel PCA +---------------- + +:class:`KernelPCA` is an extension of PCA which achieves non-linear +dimensionality reduction through the use of kernels (see :ref:`metrics`). It +has many applications including denoising, compression and structured +prediction (kernel dependency estimation). :class:`KernelPCA` supports both +``transform`` and ``inverse_transform``. + +.. figure:: ../auto_examples/decomposition/images/sphx_glr_plot_kernel_pca_001.png + :target: ../auto_examples/decomposition/plot_kernel_pca.html + :align: center + :scale: 75% + +.. topic:: Examples: + + * :ref:`sphx_glr_auto_examples_decomposition_plot_kernel_pca.py` + +.. topic:: References: + + * Kernel PCA was introduced in "Kernel principal component analysis" + Bernhard Schoelkopf, Alexander J. Smola, and Klaus-Robert Mueller. 1999. + In Advances in kernel methods, MIT Press, Cambridge, MA, USA 327-352. + + +.. _kPCA_Solvers: + +Choice of solver for Kernel PCA +------------------------------- + +While in :class:`PCA` the number of components is bounded by the number of +features, in :class:`KernelPCA` the number of components is bounded by the +number of samples. Many real-world datasets have large number of samples! In +these cases finding *all* the components with a full kPCA is a waste of +computation time, as data is mostly described by the first few components +(e.g. ``n_components<=100``). In other words, the centered Gram matrix that +is eigendecomposed in the Kernel PCA fitting process has an effective rank that +is much smaller than its size. This is a situation where approximate +eigensolvers can provide speedup with very low precision loss. + +The optional parameter ``eigen_solver='randomized'`` can be used to +*significantly* reduce the computation time when the number of requested +``n_components`` is small compared with the number of samples. It relies on +randomized decomposition methods to find an approximate solution in a shorter +time. + +The time complexity of the randomized :class:`KernelPCA` is +:math:`O(n_{\mathrm{samples}}^2 \cdot n_{\mathrm{components}})` +instead of :math:`O(n_{\mathrm{samples}}^3)` for the exact method +implemented with ``eigen_solver='dense'``. + +The memory footprint of randomized :class:`KernelPCA` is also proportional to +:math:`2 \cdot n_{\mathrm{samples}} \cdot n_{\mathrm{components}}` instead of +:math:`n_{\mathrm{samples}}^2` for the exact method. + +Note: this technique is the same as in :ref:`RandomizedPCA`. + +In addition to the above two solvers, ``eigen_solver='arpack'`` can be used as +an alternate way to get an approximate decomposition. In practice, this method +only provides reasonable execution times when the number of components to find +is extremely small. It is enabled by default when the desired number of +components is less than 10 (strict) and the number of samples is more than 200 +(strict). See :class:`KernelPCA` for details. + +.. topic:: References: + + * *dense* solver: + `scipy.linalg.eigh documentation + <https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.eigh.html>`_ + + * *randomized* solver: + + - Algorithm 4.3 in + `"Finding structure with randomness: Stochastic algorithms for + constructing approximate matrix decompositions" + <https://arxiv.org/abs/0909.4061>`_ + Halko, et al., 2009 + + - `"An implementation of a randomized algorithm for principal component + analysis" + <https://arxiv.org/pdf/1412.3510.pdf>`_ + A. Szlam et al. 2014 + + * *arpack* solver: + `scipy.sparse.linalg.eigsh documentation + <https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.linalg.eigsh.html>`_ + R. B. Lehoucq, D. C. Sorensen, and C. Yang, 1998 + + .. _LSA: Truncated singular value decomposition and latent semantic analysis diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index 3b3884e68e185..e89eecfe0874c 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -159,14 +159,17 @@ Changelog - |Fix| Fixes incorrect multiple data-conversion warnings when clustering boolean data. :pr:`<PRID>` by :user:`<NAME>`. -:mod:`sklearn.decomposition` -............................ - - |Fix| Fixed :func:`dict_learning`, used by :class:`DictionaryLearning`, to ensure determinism of the output. Achieved by flipping signs of the SVD output which is used to initialize the code. :pr:`<PRID>` by :user:`<NAME>`. +- |Enhancement| added a new approximate solver (randomized SVD, available with + `eigen_solver='randomized'`) to :class:`decomposition.KernelPCA`. This + significantly accelerates computation when the number of samples is much + larger than the desired number of components. + :pr:`<PRID>` by :user:`<NAME>`. + - |Fix| Fixed a bug in :class:`MiniBatchDictionaryLearning`, :class:`MiniBatchSparsePCA` and :func:`dict_learning_online` where the update of the dictionary was incorrect. :pr:`<PRID>` by @@ -389,8 +392,8 @@ Changelog supporting sparse matrix and raise the appropriate error message. :pr:`<PRID>` by :user:`<NAME>`. -- |Efficiency| Changed ``algorithm`` argument for :class:`cluster.KMeans` in - :class:`preprocessing.KBinsDiscretizer` from ``auto`` to ``full``. +- |Efficiency| Changed ``algorithm`` argument for :class:`cluster.KMeans` in + :class:`preprocessing.KBinsDiscretizer` from ``auto`` to ``full``. :pr:`<PRID>` by :user:`<NAME>`. :mod:`sklearn.tree` If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names: [{'type': 'file', 'name': 'benchmarks/bench_kernel_pca_solvers_time_vs_n_samples.py'}, {'type': 'file', 'name': 'benchmarks/bench_kernel_pca_solvers_time_vs_n_components.py'}]
scikit-learn/scikit-learn
scikit-learn__scikit-learn-19948
https://github.com/scikit-learn/scikit-learn/pull/19948
diff --git a/doc/glossary.rst b/doc/glossary.rst index ba924387bc5eb..21d0c947f3e64 100644 --- a/doc/glossary.rst +++ b/doc/glossary.rst @@ -923,7 +923,7 @@ Class APIs and Estimator Types possible to identify which methods are provided by the underlying estimator until the meta-estimator has been :term:`fitted` (see also :term:`duck typing`), for which - :func:`utils.metaestimators.if_delegate_has_method` may help. It + :func:`utils.metaestimators.available_if` may help. It should also provide (or modify) the :term:`estimator tags` and :term:`classes_` attribute provided by the base estimator. diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst index cdeb6f0523422..ddcbe36bb1b33 100644 --- a/doc/modules/classes.rst +++ b/doc/modules/classes.rst @@ -1605,6 +1605,7 @@ Plotting utils.graph_shortest_path.graph_shortest_path utils.indexable utils.metaestimators.if_delegate_has_method + utils.metaestimators.available_if utils.multiclass.type_of_target utils.multiclass.is_multilabel utils.multiclass.unique_labels diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index 9689cd8789a7a..6a9f0cb55d2f5 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -591,6 +591,11 @@ Changelog :pr:`19459` by :user:`Cindy Bezuidenhout <cinbez>` and :user:`Clifford Akai-Nettey<cliffordEmmanuel>`. +- |Enhancement| Added helper decorator :func:`utils.metaestimators.available_if` + to provide flexiblity in metaestimators making methods available or + unavailable on the basis of state, in a more readable way. + :pr:`19948` by `Joel Nothman`_. + - |Fix| Fixed a bug in :func:`utils.sparsefuncs.mean_variance_axis` where the precision of the computed variance was very poor when the real variance is exactly zero. :pr:`19766` by :user:`Jérémie du Boisberranger <jeremiedbb>`. diff --git a/sklearn/multioutput.py b/sklearn/multioutput.py index 335dc5410b9ce..f6be8cd8011c3 100644 --- a/sklearn/multioutput.py +++ b/sklearn/multioutput.py @@ -22,8 +22,8 @@ from .base import BaseEstimator, clone, MetaEstimatorMixin from .base import RegressorMixin, ClassifierMixin, is_classifier from .model_selection import cross_val_predict +from .utils.metaestimators import available_if from .utils import check_random_state -from .utils.metaestimators import if_delegate_has_method from .utils.validation import check_is_fitted, has_fit_parameter, _check_fit_params from .utils.multiclass import check_classification_targets from .utils.fixes import delayed @@ -64,13 +64,27 @@ def _partial_fit_estimator( return estimator +def _available_if_estimator_has(attr): + """Returns a function to check if estimator or estimators_ has attr + + Helper for Chain implementations + """ + def _check(self): + return ( + hasattr(self.estimator, attr) + or all(hasattr(est, attr) for est in self.estimators_) + ) + + return available_if(_check) + + class _MultiOutputEstimator(MetaEstimatorMixin, BaseEstimator, metaclass=ABCMeta): @abstractmethod def __init__(self, estimator, *, n_jobs=None): self.estimator = estimator self.n_jobs = n_jobs - @if_delegate_has_method("estimator") + @_available_if_estimator_has("partial_fit") def partial_fit(self, X, y, classes=None, sample_weight=None): """Incrementally fit the model to data. Fit a separate model for each output variable. @@ -280,7 +294,7 @@ class MultiOutputRegressor(RegressorMixin, _MultiOutputEstimator): def __init__(self, estimator, *, n_jobs=None): super().__init__(estimator, n_jobs=n_jobs) - @if_delegate_has_method("estimator") + @_available_if_estimator_has("partial_fit") def partial_fit(self, X, y, sample_weight=None): """Incrementally fit the model to data. Fit a separate model for each output variable. @@ -464,6 +478,20 @@ def _more_tags(self): return {"_skip_test": True} +def _available_if_base_estimator_has(attr): + """Returns a function to check if base_estimator or estimators_ has attr + + Helper for Chain implementations + """ + def _check(self): + return ( + hasattr(self.base_estimator, attr) + or all(hasattr(est, attr) for est in self.estimators_) + ) + + return available_if(_check) + + class _BaseChain(BaseEstimator, metaclass=ABCMeta): def __init__(self, base_estimator, *, order=None, cv=None, random_state=None): self.base_estimator = base_estimator @@ -700,7 +728,7 @@ def fit(self, X, Y): ] return self - @if_delegate_has_method("base_estimator") + @_available_if_base_estimator_has("predict_proba") def predict_proba(self, X): """Predict probability estimates. @@ -729,7 +757,7 @@ def predict_proba(self, X): return Y_prob - @if_delegate_has_method("base_estimator") + @_available_if_base_estimator_has("decision_function") def decision_function(self, X): """Evaluate the decision_function of the models in the chain. diff --git a/sklearn/pipeline.py b/sklearn/pipeline.py index 54670bc4086cd..e91349a6ed484 100644 --- a/sklearn/pipeline.py +++ b/sklearn/pipeline.py @@ -18,7 +18,7 @@ from .base import clone, TransformerMixin from .utils._estimator_html_repr import _VisualBlock -from .utils.metaestimators import if_delegate_has_method +from .utils.metaestimators import if_delegate_has_method, available_if from .utils import ( Bunch, _print_elapsed_time, @@ -550,8 +550,13 @@ def predict_log_proba(self, X, **predict_log_proba_params): Xt = transform.transform(Xt) return self.steps[-1][1].predict_log_proba(Xt, **predict_log_proba_params) - @property - def transform(self): + def _can_transform(self): + return self._final_estimator == "passthrough" or hasattr( + self._final_estimator, "transform" + ) + + @available_if(_can_transform) + def transform(self, X): """Apply transforms, and transform with the final estimator This also works where final estimator is ``None``: all prior @@ -567,20 +572,16 @@ def transform(self): ------- Xt : array-like of shape (n_samples, n_transformed_features) """ - # _final_estimator is None or has transform, otherwise attribute error - # XXX: Handling the None case means we can't use if_delegate_has_method - if self._final_estimator != "passthrough": - self._final_estimator.transform - return self._transform - - def _transform(self, X): Xt = X for _, _, transform in self._iter(): Xt = transform.transform(Xt) return Xt - @property - def inverse_transform(self): + def _can_inverse_transform(self): + return all(hasattr(t, "inverse_transform") for _, _, t in self._iter()) + + @available_if(_can_inverse_transform) + def inverse_transform(self, Xt): """Apply inverse transformations in reverse order All estimators in the pipeline must support ``inverse_transform``. @@ -597,14 +598,6 @@ def inverse_transform(self): ------- Xt : array-like of shape (n_samples, n_features) """ - # raise AttributeError if necessary for hasattr behaviour - # XXX: Handling the None case means we can't use if_delegate_has_method - for _, _, transform in self._iter(): - transform.inverse_transform - return self._inverse_transform - - def _inverse_transform(self, X): - Xt = X reverse_iter = reversed(list(self._iter())) for _, _, transform in reverse_iter: Xt = transform.inverse_transform(Xt) diff --git a/sklearn/utils/metaestimators.py b/sklearn/utils/metaestimators.py index fd017c158cbe5..20bd514a1bba8 100644 --- a/sklearn/utils/metaestimators.py +++ b/sklearn/utils/metaestimators.py @@ -13,7 +13,7 @@ from ..base import BaseEstimator from ..base import _is_pairwise -__all__ = ["if_delegate_has_method"] +__all__ = ["available_if", "if_delegate_has_method"] class _BaseComposition(BaseEstimator, metaclass=ABCMeta): @@ -80,53 +80,114 @@ def _validate_names(self, names): ) -class _IffHasAttrDescriptor: +class _AvailableIfDescriptor: """Implements a conditional property using the descriptor protocol. Using this class to create a decorator will raise an ``AttributeError`` - if none of the delegates (specified in ``delegate_names``) is an attribute - of the base object or the first found delegate does not have an attribute - ``attribute_name``. - - This allows ducktyping of the decorated method based on - ``delegate.attribute_name``. Here ``delegate`` is the first item in - ``delegate_names`` for which ``hasattr(object, delegate) is True``. + if check(self) returns a falsey value. Note that if check raises an error + this will also result in hasattr returning false. See https://docs.python.org/3/howto/descriptor.html for an explanation of descriptors. """ - def __init__(self, fn, delegate_names, attribute_name): + def __init__(self, fn, check, attribute_name): self.fn = fn - self.delegate_names = delegate_names + self.check = check self.attribute_name = attribute_name # update the docstring of the descriptor update_wrapper(self, fn) - def __get__(self, obj, type=None): - # raise an AttributeError if the attribute is not present on the object + def __get__(self, obj, owner=None): if obj is not None: # delegate only on instances, not the classes. # this is to allow access to the docstrings. - for delegate_name in self.delegate_names: - try: - delegate = attrgetter(delegate_name)(obj) - except AttributeError: - continue - else: - getattr(delegate, self.attribute_name) - break - else: - attrgetter(self.delegate_names[-1])(obj) + if not self.check(obj): + raise AttributeError( + f"This {repr(owner.__name__)}" + " has no attribute" + f" {repr(self.attribute_name)}" + ) # lambda, but not partial, allows help() to work with update_wrapper - out = lambda *args, **kwargs: self.fn(obj, *args, **kwargs) + out = lambda *args, **kwargs: self.fn(obj, *args, **kwargs) # noqa # update the docstring of the returned function update_wrapper(out, self.fn) return out +def available_if(check): + """An attribute that is available only if check returns a truthy value + + Parameters + ---------- + check : callable + When passed the object with the decorated method, this should return + a truthy value if the attribute is available, and either return False + or raise an AttributeError if not available. + + Examples + -------- + >>> from sklearn.utils.metaestimators import available_if + >>> class HelloIfEven: + ... def __init__(self, x): + ... self.x = x + ... + ... def _x_is_even(self): + ... return self.x % 2 == 0 + ... + ... @available_if(_x_is_even) + ... def say_hello(self): + ... print("Hello") + ... + >>> obj = HelloIfEven(1) + >>> hasattr(obj, "say_hello") + False + >>> obj.x = 2 + >>> hasattr(obj, "say_hello") + True + >>> obj.say_hello() + Hello + """ + return lambda fn: _AvailableIfDescriptor(fn, check, attribute_name=fn.__name__) + + +class _IffHasAttrDescriptor(_AvailableIfDescriptor): + """Implements a conditional property using the descriptor protocol. + + Using this class to create a decorator will raise an ``AttributeError`` + if none of the delegates (specified in ``delegate_names``) is an attribute + of the base object or the first found delegate does not have an attribute + ``attribute_name``. + + This allows ducktyping of the decorated method based on + ``delegate.attribute_name``. Here ``delegate`` is the first item in + ``delegate_names`` for which ``hasattr(object, delegate) is True``. + + See https://docs.python.org/3/howto/descriptor.html for an explanation of + descriptors. + """ + + def __init__(self, fn, delegate_names, attribute_name): + super().__init__(fn, self._check, attribute_name) + self.delegate_names = delegate_names + + def _check(self, obj): + delegate = None + for delegate_name in self.delegate_names: + try: + delegate = attrgetter(delegate_name)(obj) + break + except AttributeError: + continue + + if delegate is None: + return False + # raise original AttributeError + return getattr(delegate, self.attribute_name) or True + + def if_delegate_has_method(delegate): """Create a decorator for methods that are delegated to a sub-estimator
diff --git a/sklearn/utils/tests/test_metaestimators.py b/sklearn/utils/tests/test_metaestimators.py index e6c1ca592e94f..35a459e949e29 100644 --- a/sklearn/utils/tests/test_metaestimators.py +++ b/sklearn/utils/tests/test_metaestimators.py @@ -1,4 +1,5 @@ from sklearn.utils.metaestimators import if_delegate_has_method +from sklearn.utils.metaestimators import available_if class Prefix: @@ -74,3 +75,32 @@ def test_if_delegate_has_method(): assert not hasattr(MetaEstTestTuple(HasNoPredict(), HasPredict()), "predict") assert not hasattr(MetaEstTestList(HasNoPredict(), HasPredict()), "predict") assert hasattr(MetaEstTestList(HasPredict(), HasPredict()), "predict") + + +class AvailableParameterEstimator: + """This estimator's `available` parameter toggles the presence of a method""" + + def __init__(self, available=True): + self.available = available + + @available_if(lambda est: est.available) + def available_func(self): + """This is a mock available_if function""" + pass + + +def test_available_if_docstring(): + assert "This is a mock available_if function" in str( + AvailableParameterEstimator.__dict__["available_func"].__doc__ + ) + assert "This is a mock available_if function" in str( + AvailableParameterEstimator.available_func.__doc__ + ) + assert "This is a mock available_if function" in str( + AvailableParameterEstimator().available_func.__doc__ + ) + + +def test_available_if(): + assert hasattr(AvailableParameterEstimator(), "available_func") + assert not hasattr(AvailableParameterEstimator(available=False), "available_func")
[ { "path": "doc/glossary.rst", "old_path": "a/doc/glossary.rst", "new_path": "b/doc/glossary.rst", "metadata": "diff --git a/doc/glossary.rst b/doc/glossary.rst\nindex ba924387bc5eb..21d0c947f3e64 100644\n--- a/doc/glossary.rst\n+++ b/doc/glossary.rst\n@@ -923,7 +923,7 @@ Class APIs and Estimator Types\n possible to identify which methods are provided by the underlying\n estimator until the meta-estimator has been :term:`fitted` (see also\n :term:`duck typing`), for which\n- :func:`utils.metaestimators.if_delegate_has_method` may help. It\n+ :func:`utils.metaestimators.available_if` may help. It\n should also provide (or modify) the :term:`estimator tags` and\n :term:`classes_` attribute provided by the base estimator.\n \n" }, { "path": "doc/modules/classes.rst", "old_path": "a/doc/modules/classes.rst", "new_path": "b/doc/modules/classes.rst", "metadata": "diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst\nindex cdeb6f0523422..ddcbe36bb1b33 100644\n--- a/doc/modules/classes.rst\n+++ b/doc/modules/classes.rst\n@@ -1605,6 +1605,7 @@ Plotting\n utils.graph_shortest_path.graph_shortest_path\n utils.indexable\n utils.metaestimators.if_delegate_has_method\n+ utils.metaestimators.available_if\n utils.multiclass.type_of_target\n utils.multiclass.is_multilabel\n utils.multiclass.unique_labels\n" }, { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 9689cd8789a7a..6a9f0cb55d2f5 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -591,6 +591,11 @@ Changelog\n :pr:`19459` by :user:`Cindy Bezuidenhout <cinbez>` and\n :user:`Clifford Akai-Nettey<cliffordEmmanuel>`.\n \n+- |Enhancement| Added helper decorator :func:`utils.metaestimators.available_if`\n+ to provide flexiblity in metaestimators making methods available or\n+ unavailable on the basis of state, in a more readable way.\n+ :pr:`19948` by `Joel Nothman`_.\n+\n - |Fix| Fixed a bug in :func:`utils.sparsefuncs.mean_variance_axis` where the\n precision of the computed variance was very poor when the real variance is\n exactly zero. :pr:`19766` by :user:`Jérémie du Boisberranger <jeremiedbb>`.\n" } ]
1.00
c79bed337c6eeea3b181d1e2054308197090b036
[]
[ "sklearn/utils/tests/test_metaestimators.py::test_available_if", "sklearn/utils/tests/test_metaestimators.py::test_if_delegate_has_method", "sklearn/utils/tests/test_metaestimators.py::test_delegated_docstring", "sklearn/utils/tests/test_metaestimators.py::test_available_if_docstring" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/glossary.rst", "old_path": "a/doc/glossary.rst", "new_path": "b/doc/glossary.rst", "metadata": "diff --git a/doc/glossary.rst b/doc/glossary.rst\nindex ba924387bc5eb..21d0c947f3e64 100644\n--- a/doc/glossary.rst\n+++ b/doc/glossary.rst\n@@ -923,7 +923,7 @@ Class APIs and Estimator Types\n possible to identify which methods are provided by the underlying\n estimator until the meta-estimator has been :term:`fitted` (see also\n :term:`duck typing`), for which\n- :func:`utils.metaestimators.if_delegate_has_method` may help. It\n+ :func:`utils.metaestimators.available_if` may help. It\n should also provide (or modify) the :term:`estimator tags` and\n :term:`classes_` attribute provided by the base estimator.\n \n" }, { "path": "doc/modules/classes.rst", "old_path": "a/doc/modules/classes.rst", "new_path": "b/doc/modules/classes.rst", "metadata": "diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst\nindex cdeb6f0523422..ddcbe36bb1b33 100644\n--- a/doc/modules/classes.rst\n+++ b/doc/modules/classes.rst\n@@ -1605,6 +1605,7 @@ Plotting\n utils.graph_shortest_path.graph_shortest_path\n utils.indexable\n utils.metaestimators.if_delegate_has_method\n+ utils.metaestimators.available_if\n utils.multiclass.type_of_target\n utils.multiclass.is_multilabel\n utils.multiclass.unique_labels\n" }, { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 9689cd8789a7a..6a9f0cb55d2f5 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -591,6 +591,11 @@ Changelog\n :pr:`<PRID>` by :user:`<NAME>` and\n :user:`<NAME>`.\n \n+- |Enhancement| Added helper decorator :func:`utils.metaestimators.available_if`\n+ to provide flexiblity in metaestimators making methods available or\n+ unavailable on the basis of state, in a more readable way.\n+ :pr:`<PRID>` by `<NAME>`_.\n+\n - |Fix| Fixed a bug in :func:`utils.sparsefuncs.mean_variance_axis` where the\n precision of the computed variance was very poor when the real variance is\n exactly zero. :pr:`<PRID>` by :user:`<NAME>`.\n" } ]
diff --git a/doc/glossary.rst b/doc/glossary.rst index ba924387bc5eb..21d0c947f3e64 100644 --- a/doc/glossary.rst +++ b/doc/glossary.rst @@ -923,7 +923,7 @@ Class APIs and Estimator Types possible to identify which methods are provided by the underlying estimator until the meta-estimator has been :term:`fitted` (see also :term:`duck typing`), for which - :func:`utils.metaestimators.if_delegate_has_method` may help. It + :func:`utils.metaestimators.available_if` may help. It should also provide (or modify) the :term:`estimator tags` and :term:`classes_` attribute provided by the base estimator. diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst index cdeb6f0523422..ddcbe36bb1b33 100644 --- a/doc/modules/classes.rst +++ b/doc/modules/classes.rst @@ -1605,6 +1605,7 @@ Plotting utils.graph_shortest_path.graph_shortest_path utils.indexable utils.metaestimators.if_delegate_has_method + utils.metaestimators.available_if utils.multiclass.type_of_target utils.multiclass.is_multilabel utils.multiclass.unique_labels diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index 9689cd8789a7a..6a9f0cb55d2f5 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -591,6 +591,11 @@ Changelog :pr:`<PRID>` by :user:`<NAME>` and :user:`<NAME>`. +- |Enhancement| Added helper decorator :func:`utils.metaestimators.available_if` + to provide flexiblity in metaestimators making methods available or + unavailable on the basis of state, in a more readable way. + :pr:`<PRID>` by `<NAME>`_. + - |Fix| Fixed a bug in :func:`utils.sparsefuncs.mean_variance_axis` where the precision of the computed variance was very poor when the real variance is exactly zero. :pr:`<PRID>` by :user:`<NAME>`.
scikit-learn/scikit-learn
scikit-learn__scikit-learn-19004
https://github.com/scikit-learn/scikit-learn/pull/19004
diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index 0372dcdd1fd4e..ecdb38440bf0b 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -62,6 +62,9 @@ Changelog - |Fix| :meth:`ElasticNet.fit` no longer modifies `sample_weight` in place. :pr:`19055` by `Thomas Fan`_. +- |Enhancement| Validate user-supplied gram matrix passed to linear models + via the `precompute` argument. :pr:`19004` by :user:`Adam Midvidy <amidvidy>`. + Code and Documentation Contributors ----------------------------------- diff --git a/examples/linear_model/plot_elastic_net_precomputed_gram_matrix_with_weighted_samples.py b/examples/linear_model/plot_elastic_net_precomputed_gram_matrix_with_weighted_samples.py new file mode 100644 index 0000000000000..852ea545c5fd6 --- /dev/null +++ b/examples/linear_model/plot_elastic_net_precomputed_gram_matrix_with_weighted_samples.py @@ -0,0 +1,53 @@ +""" +========================================================================== +Fitting an Elastic Net with a precomputed Gram Matrix and Weighted Samples +========================================================================== + +The following example shows how to precompute the gram matrix +while using weighted samples with an ElasticNet. + +If weighted samples are used, the design matrix must be centered and then +rescaled by the square root of the weight vector before the gram matrix +is computed. + +.. note:: + `sample_weight` vector is also rescaled to sum to `n_samples`, see the + documentation for the `sample_weight` parameter to + :func:`linear_model.ElasticNet.fit`. + +""" + +print(__doc__) + +# %% +# Let's start by loading the dataset and creating some sample weights. +import numpy as np +from sklearn.datasets import make_regression + +rng = np.random.RandomState(0) + +n_samples = int(1e5) +X, y = make_regression(n_samples=n_samples, noise=0.5, random_state=rng) + +sample_weight = rng.lognormal(size=n_samples) +# normalize the sample weights +normalized_weights = sample_weight * (n_samples / (sample_weight.sum())) + +# %% +# To fit the elastic net using the `precompute` option together with the sample +# weights, we must first center the design matrix, and rescale it by the +# normalized weights prior to computing the gram matrix. +X_offset = np.average(X, axis=0, weights=normalized_weights) +X_centered = (X - np.average(X, axis=0, weights=normalized_weights)) +X_scaled = X_centered * np.sqrt(normalized_weights)[:, np.newaxis] +gram = np.dot(X_scaled.T, X_scaled) + +# %% +# We can now proceed with fitting. We must passed the centered design matrix to +# `fit` otherwise the elastic net estimator will detect that it is uncentered +# and discard the gram matrix we passed. However, if we pass the scaled design +# matrix, the preprocessing code will incorrectly rescale it a second time. +from sklearn.linear_model import ElasticNet + +lm = ElasticNet(alpha=0.01, precompute=gram) +lm.fit(X_centered, y, sample_weight=normalized_weights) diff --git a/sklearn/linear_model/_base.py b/sklearn/linear_model/_base.py index 2399e1216238f..907d4960264f8 100644 --- a/sklearn/linear_model/_base.py +++ b/sklearn/linear_model/_base.py @@ -37,6 +37,7 @@ from ..utils._seq_dataset import ArrayDataset32, CSRDataset32 from ..utils._seq_dataset import ArrayDataset64, CSRDataset64 from ..utils.validation import check_is_fitted, _check_sample_weight + from ..utils.fixes import delayed from ..preprocessing import normalize as f_normalize @@ -575,6 +576,61 @@ def rmatvec(b): return self +def _check_precomputed_gram_matrix(X, precompute, X_offset, X_scale, + rtol=1e-7, + atol=1e-5): + """Computes a single element of the gram matrix and compares it to + the corresponding element of the user supplied gram matrix. + + If the values do not match a ValueError will be thrown. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + Data array. + + precompute : array-like of shape (n_features, n_features) + User-supplied gram matrix. + + X_offset : ndarray of shape (n_features,) + Array of feature means used to center design matrix. + + X_scale : ndarray of shape (n_features,) + Array of feature scale factors used to normalize design matrix. + + rtol : float, default=1e-7 + Relative tolerance; see numpy.allclose. + + atol : float, default=1e-5 + absolute tolerance; see :func`numpy.allclose`. Note that the default + here is more tolerant than the default for + :func:`numpy.testing.assert_allclose`, where `atol=0`. + + Raises + ------ + ValueError + Raised when the provided Gram matrix is not consistent. + """ + + n_features = X.shape[1] + f1 = n_features // 2 + f2 = min(f1+1, n_features-1) + + v1 = (X[:, f1] - X_offset[f1]) * X_scale[f1] + v2 = (X[:, f2] - X_offset[f2]) * X_scale[f2] + + expected = np.dot(v1, v2) + actual = precompute[f1, f2] + + if not np.isclose(expected, actual, rtol=rtol, atol=atol): + raise ValueError("Gram matrix passed in via 'precompute' parameter " + "did not pass validation when a single element was " + "checked - please check that it was computed " + f"properly. For element ({f1},{f2}) we computed " + f"{expected} but the user-supplied value was " + f"{actual}.") + + def _pre_fit(X, y, Xy, precompute, normalize, fit_intercept, copy, check_input=True, sample_weight=None): """Aux function used at beginning of fit in linear models @@ -600,16 +656,22 @@ def _pre_fit(X, y, Xy, precompute, normalize, fit_intercept, copy, check_input=check_input, sample_weight=sample_weight) if sample_weight is not None: X, y = _rescale_data(X, y, sample_weight=sample_weight) - if hasattr(precompute, '__array__') and ( - fit_intercept and not np.allclose(X_offset, np.zeros(n_features)) or - normalize and not np.allclose(X_scale, np.ones(n_features))): - warnings.warn("Gram matrix was provided but X was centered" - " to fit intercept, " - "or X was normalized : recomputing Gram matrix.", - UserWarning) - # recompute Gram - precompute = 'auto' - Xy = None + if hasattr(precompute, '__array__'): + if (fit_intercept and not np.allclose(X_offset, np.zeros(n_features)) + or normalize and not np.allclose(X_scale, + np.ones(n_features))): + warnings.warn( + "Gram matrix was provided but X was centered to fit " + "intercept, or X was normalized : recomputing Gram matrix.", + UserWarning + ) + # recompute Gram + precompute = 'auto' + Xy = None + elif check_input: + # If we're going to use the user's precomputed gram matrix, we + # do a quick check to make sure its not totally bogus. + _check_precomputed_gram_matrix(X, precompute, X_offset, X_scale) # precompute if n_samples > n_features if isinstance(precompute, str) and precompute == 'auto': diff --git a/sklearn/linear_model/_coordinate_descent.py b/sklearn/linear_model/_coordinate_descent.py index 6dcaa5043b414..f2a004be81048 100644 --- a/sklearn/linear_model/_coordinate_descent.py +++ b/sklearn/linear_model/_coordinate_descent.py @@ -729,7 +729,8 @@ def fit(self, X, y, sample_weight=None, check_input=True): Target. Will be cast to X's dtype if necessary. sample_weight : float or array-like of shape (n_samples,), default=None - Sample weight. + Sample weight. Internally, the `sample_weight` vector will be + rescaled to sum to `n_samples`. .. versionadded:: 0.23
diff --git a/sklearn/linear_model/tests/test_coordinate_descent.py b/sklearn/linear_model/tests/test_coordinate_descent.py index f0095b235ac2b..232a59e846ff7 100644 --- a/sklearn/linear_model/tests/test_coordinate_descent.py +++ b/sklearn/linear_model/tests/test_coordinate_descent.py @@ -743,6 +743,45 @@ def test_precompute_invalid_argument(): "Got 'auto'", ElasticNet(precompute='auto').fit, X, y) +def test_elasticnet_precompute_incorrect_gram(): + # check that passing an invalid precomputed Gram matrix will raise an + # error. + X, y, _, _ = build_dataset() + + rng = np.random.RandomState(0) + + X_centered = X - np.average(X, axis=0) + garbage = rng.standard_normal(X.shape) + precompute = np.dot(garbage.T, garbage) + + clf = ElasticNet(alpha=0.01, precompute=precompute) + msg = "Gram matrix.*did not pass validation.*" + with pytest.raises(ValueError, match=msg): + clf.fit(X_centered, y) + + +def test_elasticnet_precompute_gram_weighted_samples(): + # check the equivalence between passing a precomputed Gram matrix and + # internal computation using sample weights. + X, y, _, _ = build_dataset() + + rng = np.random.RandomState(0) + sample_weight = rng.lognormal(size=y.shape) + + w_norm = sample_weight * (y.shape / np.sum(sample_weight)) + X_c = (X - np.average(X, axis=0, weights=w_norm)) + X_r = X_c * np.sqrt(w_norm)[:, np.newaxis] + gram = np.dot(X_r.T, X_r) + + clf1 = ElasticNet(alpha=0.01, precompute=gram) + clf1.fit(X_c, y, sample_weight=sample_weight) + + clf2 = ElasticNet(alpha=0.01, precompute=False) + clf2.fit(X, y, sample_weight=sample_weight) + + assert_allclose(clf1.coef_, clf2.coef_) + + def test_warm_start_convergence(): X, y, _, _ = build_dataset() model = ElasticNet(alpha=1e-3, tol=1e-3).fit(X, y)
[ { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 0372dcdd1fd4e..ecdb38440bf0b 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -62,6 +62,9 @@ Changelog\n - |Fix| :meth:`ElasticNet.fit` no longer modifies `sample_weight` in place.\n :pr:`19055` by `Thomas Fan`_.\n \n+- |Enhancement| Validate user-supplied gram matrix passed to linear models\n+ via the `precompute` argument. :pr:`19004` by :user:`Adam Midvidy <amidvidy>`.\n+\n Code and Documentation Contributors\n -----------------------------------\n \n" } ]
1.00
6b4f82433dc2f219dbff7fe8fa42c10b72379be6
[ "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_positive_constraint", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_zero", "sklearn/linear_model/tests/test_coordinate_descent.py::test_multitask_enet_and_lasso_cv", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_alpha_warning", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[Lasso-params0]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[ElasticNet-params3]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_float_precision", "sklearn/linear_model/tests/test_coordinate_descent.py::test_l1_ratio_param_invalid[-1]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[LinearRegression-params13]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_warm_start_multitask_lasso", "sklearn/linear_model/tests/test_coordinate_descent.py::test_set_order_dense[F-C]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[MultiTaskLasso-params11]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_l1_ratio", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[RidgeCV-params8]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_cv_with_some_model_selection", "sklearn/linear_model/tests/test_coordinate_descent.py::test_multi_task_lasso_and_enet", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_models_cv_fit_for_all_backends[MultiTaskElasticNetCV-threading]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_consistency[True-True-0.01-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_models_cv_fit_for_all_backends[ElasticNetCV-loky]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[Ridge-params6]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_sparse_input_dtype_enet_and_lassocv", "sklearn/linear_model/tests/test_coordinate_descent.py::test_elasticnet_precompute_gram_weighted_samples", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[LassoCV-params1]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_non_float_y[Lasso]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_set_order_dense[C-C]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_l1_ratio_param_invalid[something_wrong]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_l1_ratio_param_invalid[2]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_set_order_dense[C-F]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_path", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_models_cv_fit_for_all_backends[LassoCV-threading]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_warm_start_convergence", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_copy_X_True[True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_set_order_sparse[C-C]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_coordinate_descent[MultiTaskLasso-2-kwargs2]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[LinearRegression-params7]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_cv", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_models_cv_fit_for_all_backends[MultiTaskLassoCV-loky]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_set_order_dense[F-F]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_1d_multioutput_enet_and_multitask_enet_cv", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[Lars-params12]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[Lasso-params0]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_models_cv_fit_for_all_backends[LassoCV-loky]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_multi_task_lasso_readonly_data", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lassoCV_does_not_set_precompute[auto-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[LassoLars-params1]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_multioutput_enetcv_error", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_path_return_models_vs_new_return_gives_same_coefficients", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_non_float_y[ElasticNet]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lassoCV_does_not_set_precompute[False-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_toy", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_readonly_data", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_consistency[False-False-0.01-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_uniform_targets", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_consistency[False-True-0.01-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lassoCV_does_not_set_precompute[True-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_consistency[True-False-0.01-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[ElasticNetCV-params2]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_sparse_dense_descent_paths", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_copy_X_False_check_input_False", "sklearn/linear_model/tests/test_coordinate_descent.py::test_coef_shape_not_zero", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_consistency[True-False-0.01-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_l1_ratio_param_invalid[None]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_consistency[True-True-0.01-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_coordinate_descent[Lasso-1-kwargs0]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_consistency[False-False-0.01-True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_toy", "sklearn/linear_model/tests/test_coordinate_descent.py::test_1d_multioutput_lasso_and_multitask_lasso_cv", "sklearn/linear_model/tests/test_coordinate_descent.py::test_precompute_invalid_argument", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[ARDRegression-params7]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_consistency[False-True-0.01-False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_random_descent", "sklearn/linear_model/tests/test_coordinate_descent.py::test_set_order_sparse[F-C]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[LassoLarsIC-params14]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_models_cv_fit_for_all_backends[MultiTaskElasticNetCV-loky]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_warm_start", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[ElasticNet-params4]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_set_order_sparse[C-F]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_set_order_sparse[F-F]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[OrthogonalMatchingPursuit-params8]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_does_not_overwrite_sample_weight[False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_l1_ratio_param_invalid[10]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_copy_X_True[False]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[MultiTaskElasticNet-params10]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_coordinate_descent[Lasso-1-kwargs1]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_multi_task_lasso_cv_dtype", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[ElasticNet-params4]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[ElasticNet-params5]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_models_cv_fit_for_all_backends[MultiTaskLassoCV-threading]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[MultiTaskElasticNet-params9]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_overrided_gram_matrix", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_cv_positive_constraint", "sklearn/linear_model/tests/test_coordinate_descent.py::test_linear_models_cv_fit_for_all_backends[ElasticNetCV-threading]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_check_input_false", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_does_not_overwrite_sample_weight[True]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[RidgeClassifier-params2]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_dense_and_sparse[RidgeClassifier-params3]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_positive_constraint", "sklearn/linear_model/tests/test_coordinate_descent.py::test_warm_start_convergence_with_regularizer_decrement", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_multitarget", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_path_positive", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[BayesianRidge-params6]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_lasso_cv_positive_constraint", "sklearn/linear_model/tests/test_coordinate_descent.py::test_model_pipeline_same_as_normalize_true[Ridge-params5]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_path_parameters", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_coordinate_descent[MultiTaskLasso-2-kwargs3]", "sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_sample_weight_sparse" ]
[ "sklearn/linear_model/tests/test_coordinate_descent.py::test_elasticnet_precompute_incorrect_gram" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [ { "type": "file", "name": "examples/linear_model/plot_elastic_net_precomputed_gram_matrix_with_weighted_samples.py" } ] }
[ { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 0372dcdd1fd4e..ecdb38440bf0b 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -62,6 +62,9 @@ Changelog\n - |Fix| :meth:`ElasticNet.fit` no longer modifies `sample_weight` in place.\n :pr:`<PRID>` by `<NAME>`_.\n \n+- |Enhancement| Validate user-supplied gram matrix passed to linear models\n+ via the `precompute` argument. :pr:`<PRID>` by :user:`<NAME>`.\n+\n Code and Documentation Contributors\n -----------------------------------\n \n" } ]
diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index 0372dcdd1fd4e..ecdb38440bf0b 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -62,6 +62,9 @@ Changelog - |Fix| :meth:`ElasticNet.fit` no longer modifies `sample_weight` in place. :pr:`<PRID>` by `<NAME>`_. +- |Enhancement| Validate user-supplied gram matrix passed to linear models + via the `precompute` argument. :pr:`<PRID>` by :user:`<NAME>`. + Code and Documentation Contributors ----------------------------------- If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names: [{'type': 'file', 'name': 'examples/linear_model/plot_elastic_net_precomputed_gram_matrix_with_weighted_samples.py'}]
scikit-learn/scikit-learn
scikit-learn__scikit-learn-20297
https://github.com/scikit-learn/scikit-learn/pull/20297
diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index ecb4b5972a669..f3885f852591a 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -231,6 +231,13 @@ Changelog installing on Windows and its default 260 character limit on file names. :pr:`20209` by `Thomas Fan`_. +- |Enhancement| Replace usages of ``__file__`` related to resource file I/O + with ``importlib.resources`` to avoid the assumption that these resource + files (e.g. ``iris.csv``) already exist on a filesystem, and by extension + to enable compatibility with tools such as ``PyOxidizer``. + :pr:`20297` by :user:`Jack Liu <jackzyliu>` + + :mod:`sklearn.decomposition` ............................ diff --git a/sklearn/datasets/_base.py b/sklearn/datasets/_base.py index f31e7cd58f551..246e20d8c3f6e 100644 --- a/sklearn/datasets/_base.py +++ b/sklearn/datasets/_base.py @@ -8,11 +8,12 @@ # License: BSD 3 clause import csv import hashlib -import os +import gzip import shutil from collections import namedtuple from os import environ, listdir, makedirs -from os.path import dirname, expanduser, isdir, join, splitext +from os.path import expanduser, isdir, join, splitext +from importlib import resources from ..utils import Bunch from ..utils import check_random_state @@ -22,6 +23,10 @@ from urllib.request import urlretrieve +DATA_MODULE = "sklearn.datasets.data" +DESCR_MODULE = "sklearn.datasets.descr" +IMAGES_MODULE = "sklearn.datasets.images" + RemoteFileMetadata = namedtuple("RemoteFileMetadata", ["filename", "url", "checksum"]) @@ -238,33 +243,53 @@ def load_files( ) -def load_data(module_path, data_file_name): - """Loads data from module_path/data/data_file_name. +def load_csv_data( + data_file_name, + *, + data_module=DATA_MODULE, + descr_file_name=None, + descr_module=DESCR_MODULE, +): + """Loads `data_file_name` from `data_module with `importlib.resources`. Parameters ---------- - module_path : string - The module path. + data_file_name : str + Name of csv file to be loaded from `data_module/data_file_name`. + For example `'wine_data.csv'`. + + data_module : str or module, default='sklearn.datasets.data' + Module where data lives. The default is `'sklearn.datasets.data'`. - data_file_name : string - Name of csv file to be loaded from - module_path/data/data_file_name. For example 'wine_data.csv'. + descr_file_name : str, default=None + Name of rst file to be loaded from `descr_module/descr_file_name`. + For example `'wine_data.rst'`. See also :func:`load_descr`. + If not None, also returns the corresponding description of + the dataset. + + descr_module : str or module, default='sklearn.datasets.descr' + Module where `descr_file_name` lives. See also :func:`load_descr`. + The default is `'sklearn.datasets.descr'`. Returns ------- - data : Numpy array + data : ndarray of shape (n_samples, n_features) A 2D array with each row representing one sample and each column representing the features of a given sample. - target : Numpy array - A 1D array holding target variables for all the samples in `data. - For example target[0] is the target varible for data[0]. + target : ndarry of shape (n_samples,) + A 1D array holding target variables for all the samples in `data`. + For example target[0] is the target variable for data[0]. - target_names : Numpy array + target_names : ndarry of shape (n_samples,) A 1D array containing the names of the classifications. For example target_names[0] is the name of the target[0] class. + + descr : str, optional + Description of the dataset (the content of `descr_file_name`). + Only returned if `descr_file_name` is not None. """ - with open(join(module_path, "data", data_file_name)) as csv_file: + with resources.open_text(data_module, data_file_name) as csv_file: data_file = csv.reader(csv_file) temp = next(data_file) n_samples = int(temp[0]) @@ -277,7 +302,101 @@ def load_data(module_path, data_file_name): data[i] = np.asarray(ir[:-1], dtype=np.float64) target[i] = np.asarray(ir[-1], dtype=int) - return data, target, target_names + if descr_file_name is None: + return data, target, target_names + else: + assert descr_module is not None + descr = load_descr(descr_module=descr_module, descr_file_name=descr_file_name) + return data, target, target_names, descr + + +def load_gzip_compressed_csv_data( + data_file_name, + *, + data_module=DATA_MODULE, + descr_file_name=None, + descr_module=DESCR_MODULE, + encoding="utf-8", + **kwargs, +): + """Loads gzip-compressed `data_file_name` from `data_module` with `importlib.resources`. + + 1) Open resource file with `importlib.resources.open_binary` + 2) Decompress file obj with `gzip.open` + 3) Load decompressed data with `np.loadtxt` + + Parameters + ---------- + data_file_name : str + Name of gzip-compressed csv file (`'*.csv.gz'`) to be loaded from + `data_module/data_file_name`. For example `'diabetes_data.csv.gz'`. + + data_module : str or module, default='sklearn.datasets.data' + Module where data lives. The default is `'sklearn.datasets.data'`. + + descr_file_name : str, default=None + Name of rst file to be loaded from `descr_module/descr_file_name`. + For example `'wine_data.rst'`. See also :func:`load_descr`. + If not None, also returns the corresponding description of + the dataset. + + descr_module : str or module, default='sklearn.datasets.descr' + Module where `descr_file_name` lives. See also :func:`load_descr`. + The default is `'sklearn.datasets.descr'`. + + encoding : str, default="utf-8" + Name of the encoding that the gzip-decompressed file will be + decoded with. The default is 'utf-8'. + + **kwargs : dict, optional + Keyword arguments to be passed to `np.loadtxt`; + e.g. delimiter=','. + + Returns + ------- + data : ndarray of shape (n_samples, n_features) + A 2D array with each row representing one sample and each column + representing the features and/or target of a given sample. + + descr : str, optional + Description of the dataset (the content of `descr_file_name`). + Only returned if `descr_file_name` is not None. + """ + with resources.open_binary(data_module, data_file_name) as compressed_file: + compressed_file = gzip.open(compressed_file, mode="rt", encoding=encoding) + data = np.loadtxt(compressed_file, **kwargs) + + if descr_file_name is None: + return data + else: + assert descr_module is not None + descr = load_descr(descr_module=descr_module, descr_file_name=descr_file_name) + return data, descr + + +def load_descr(descr_file_name, *, descr_module=DESCR_MODULE): + """Load `descr_file_name` from `descr_module` with `importlib.resources`. + + Parameters + ---------- + descr_file_name : str, default=None + Name of rst file to be loaded from `descr_module/descr_file_name`. + For example `'wine_data.rst'`. See also :func:`load_descr`. + If not None, also returns the corresponding description of + the dataset. + + descr_module : str or module, default='sklearn.datasets.descr' + Module where `descr_file_name` lives. See also :func:`load_descr`. + The default is `'sklearn.datasets.descr'`. + + Returns + ------- + fdescr : str + Content of `descr_file_name`. + """ + fdescr = resources.read_text(descr_module, descr_file_name) + + return fdescr def load_wine(*, return_X_y=False, as_frame=False): @@ -354,11 +473,10 @@ def load_wine(*, return_X_y=False, as_frame=False): >>> list(data.target_names) ['class_0', 'class_1', 'class_2'] """ - module_path = dirname(__file__) - data, target, target_names = load_data(module_path, "wine_data.csv") - with open(join(module_path, "descr", "wine_data.rst")) as rst_file: - fdescr = rst_file.read() + data, target, target_names, fdescr = load_csv_data( + data_file_name="wine_data.csv", descr_file_name="wine_data.rst" + ) feature_names = [ "alcohol", @@ -481,12 +599,10 @@ def load_iris(*, return_X_y=False, as_frame=False): >>> list(data.target_names) ['setosa', 'versicolor', 'virginica'] """ - module_path = dirname(__file__) - data, target, target_names = load_data(module_path, "iris.csv") - iris_csv_filename = join(module_path, "data", "iris.csv") - - with open(join(module_path, "descr", "iris.rst")) as rst_file: - fdescr = rst_file.read() + data_file_name = "iris.csv" + data, target, target_names, fdescr = load_csv_data( + data_file_name=data_file_name, descr_file_name="iris.rst" + ) feature_names = [ "sepal length (cm)", @@ -514,7 +630,8 @@ def load_iris(*, return_X_y=False, as_frame=False): target_names=target_names, DESCR=fdescr, feature_names=feature_names, - filename=iris_csv_filename, + filename=data_file_name, + data_module=DATA_MODULE, ) @@ -598,12 +715,10 @@ def load_breast_cancer(*, return_X_y=False, as_frame=False): >>> list(data.target_names) ['malignant', 'benign'] """ - module_path = dirname(__file__) - data, target, target_names = load_data(module_path, "breast_cancer.csv") - csv_filename = join(module_path, "data", "breast_cancer.csv") - - with open(join(module_path, "descr", "breast_cancer.rst")) as rst_file: - fdescr = rst_file.read() + data_file_name = "breast_cancer.csv" + data, target, target_names, fdescr = load_csv_data( + data_file_name=data_file_name, descr_file_name="breast_cancer.rst" + ) feature_names = np.array( [ @@ -659,7 +774,8 @@ def load_breast_cancer(*, return_X_y=False, as_frame=False): target_names=target_names, DESCR=fdescr, feature_names=feature_names, - filename=csv_filename, + filename=data_file_name, + data_module=DATA_MODULE, ) @@ -747,10 +863,11 @@ def load_digits(*, n_class=10, return_X_y=False, as_frame=False): <...> >>> plt.show() """ - module_path = dirname(__file__) - data = np.loadtxt(join(module_path, "data", "digits.csv.gz"), delimiter=",") - with open(join(module_path, "descr", "digits.rst")) as f: - descr = f.read() + + data, fdescr = load_gzip_compressed_csv_data( + data_file_name="digits.csv.gz", descr_file_name="digits.rst", delimiter="," + ) + target = data[:, -1].astype(int, copy=False) flat_data = data[:, :-1] images = flat_data.view() @@ -786,7 +903,7 @@ def load_digits(*, n_class=10, return_X_y=False, as_frame=False): feature_names=feature_names, target_names=np.arange(10), images=images, - DESCR=descr, + DESCR=fdescr, ) @@ -854,15 +971,12 @@ def load_diabetes(*, return_X_y=False, as_frame=False): .. versionadded:: 0.18 """ - module_path = dirname(__file__) - base_dir = join(module_path, "data") - data_filename = join(base_dir, "diabetes_data.csv.gz") - data = np.loadtxt(data_filename) - target_filename = join(base_dir, "diabetes_target.csv.gz") - target = np.loadtxt(target_filename) + data_filename = "diabetes_data.csv.gz" + target_filename = "diabetes_target.csv.gz" + data = load_gzip_compressed_csv_data(data_filename) + target = load_gzip_compressed_csv_data(target_filename) - with open(join(module_path, "descr", "diabetes.rst")) as rst_file: - fdescr = rst_file.read() + fdescr = load_descr("diabetes.rst") feature_names = ["age", "sex", "bmi", "bp", "s1", "s2", "s3", "s4", "s5", "s6"] @@ -886,6 +1000,7 @@ def load_diabetes(*, return_X_y=False, as_frame=False): feature_names=feature_names, data_filename=data_filename, target_filename=target_filename, + data_module=DATA_MODULE, ) @@ -953,22 +1068,21 @@ def load_linnerud(*, return_X_y=False, as_frame=False): .. versionadded:: 0.18 """ - base_dir = join(dirname(__file__), "data/") - data_filename = join(base_dir, "linnerud_exercise.csv") - target_filename = join(base_dir, "linnerud_physiological.csv") - - # Read data - data_exercise = np.loadtxt(data_filename, skiprows=1) - data_physiological = np.loadtxt(target_filename, skiprows=1) + data_filename = "linnerud_exercise.csv" + target_filename = "linnerud_physiological.csv" - # Read header - with open(data_filename) as f: + # Read header and data + with resources.open_text(DATA_MODULE, data_filename) as f: header_exercise = f.readline().split() - with open(target_filename) as f: + f.seek(0) # reset file obj + data_exercise = np.loadtxt(f, skiprows=1) + + with resources.open_text(DATA_MODULE, target_filename) as f: header_physiological = f.readline().split() + f.seek(0) # reset file obj + data_physiological = np.loadtxt(f, skiprows=1) - with open(dirname(__file__) + "/descr/linnerud.rst") as f: - descr = f.read() + fdescr = load_descr("linnerud.rst") frame = None if as_frame: @@ -988,9 +1102,10 @@ def load_linnerud(*, return_X_y=False, as_frame=False): target=data_physiological, target_names=header_physiological, frame=frame, - DESCR=descr, + DESCR=fdescr, data_filename=data_filename, target_filename=target_filename, + data_module=DATA_MODULE, ) @@ -1049,14 +1164,11 @@ def load_boston(*, return_X_y=False): >>> print(X.shape) (506, 13) """ - module_path = dirname(__file__) - fdescr_name = join(module_path, "descr", "boston_house_prices.rst") - with open(fdescr_name) as f: - descr_text = f.read() + descr_text = load_descr("boston_house_prices.rst") - data_file_name = join(module_path, "data", "boston_house_prices.csv") - with open(data_file_name) as f: + data_file_name = "boston_house_prices.csv" + with resources.open_text(DATA_MODULE, data_file_name) as f: data_file = csv.reader(f) temp = next(data_file) n_samples = int(temp[0]) @@ -1080,6 +1192,7 @@ def load_boston(*, return_X_y=False): feature_names=feature_names[:-1], DESCR=descr_text, filename=data_file_name, + data_module=DATA_MODULE, ) @@ -1119,16 +1232,15 @@ def load_sample_images(): # import PIL only when needed from ..externals._pilutil import imread - module_path = join(dirname(__file__), "images") - with open(join(module_path, "README.txt")) as f: - descr = f.read() - filenames = [ - join(module_path, filename) - for filename in sorted(os.listdir(module_path)) - if filename.endswith(".jpg") - ] - # Load image data for each image in the source folder. - images = [imread(filename) for filename in filenames] + descr = load_descr("README.txt", descr_module=IMAGES_MODULE) + + filenames, images = [], [] + for filename in sorted(resources.contents(IMAGES_MODULE)): + if filename.endswith(".jpg"): + filenames.append(filename) + with resources.open_binary(IMAGES_MODULE, filename) as image_file: + image = imread(image_file) + images.append(image) return Bunch(images=images, filenames=filenames, DESCR=descr) @@ -1217,12 +1329,12 @@ def _fetch_remote(remote, dirname=None): Named tuple containing remote dataset meta information: url, filename and checksum - dirname : string + dirname : str Directory to save the file to. Returns ------- - file_path: string + file_path: str Full path of the created file. """ diff --git a/sklearn/datasets/_california_housing.py b/sklearn/datasets/_california_housing.py index e5396a5f3ef50..34a936e51cbb2 100644 --- a/sklearn/datasets/_california_housing.py +++ b/sklearn/datasets/_california_housing.py @@ -21,7 +21,7 @@ # Authors: Peter Prettenhofer # License: BSD 3 clause -from os.path import dirname, exists, join +from os.path import exists from os import makedirs, remove import tarfile @@ -35,6 +35,7 @@ from ._base import _fetch_remote from ._base import _pkl_filepath from ._base import RemoteFileMetadata +from ._base import load_descr from ..utils import Bunch @@ -173,9 +174,7 @@ def fetch_california_housing( # target in units of 100,000 target = target / 100000.0 - module_path = dirname(__file__) - with open(join(module_path, "descr", "california_housing.rst")) as dfile: - descr = dfile.read() + descr = load_descr("california_housing.rst") X = data y = target diff --git a/sklearn/datasets/_covtype.py b/sklearn/datasets/_covtype.py index 7179ac8e655d3..14af26bde0463 100644 --- a/sklearn/datasets/_covtype.py +++ b/sklearn/datasets/_covtype.py @@ -16,7 +16,7 @@ from gzip import GzipFile import logging -from os.path import dirname, exists, join +from os.path import exists, join from os import remove, makedirs import numpy as np @@ -26,6 +26,7 @@ from ._base import _convert_data_dataframe from ._base import _fetch_remote from ._base import RemoteFileMetadata +from ._base import load_descr from ..utils import Bunch from ._base import _pkl_filepath from ..utils import check_random_state @@ -178,9 +179,7 @@ def fetch_covtype( X = X[ind] y = y[ind] - module_path = dirname(__file__) - with open(join(module_path, "descr", "covtype.rst")) as rst_file: - fdescr = rst_file.read() + fdescr = load_descr("covtype.rst") frame = None if as_frame: diff --git a/sklearn/datasets/_kddcup99.py b/sklearn/datasets/_kddcup99.py index a898658e16820..b698d299b7c8d 100644 --- a/sklearn/datasets/_kddcup99.py +++ b/sklearn/datasets/_kddcup99.py @@ -12,7 +12,7 @@ from gzip import GzipFile import logging import os -from os.path import dirname, exists, join +from os.path import exists, join import numpy as np import joblib @@ -21,6 +21,7 @@ from ._base import _convert_data_dataframe from . import get_data_home from ._base import RemoteFileMetadata +from ._base import load_descr from ..utils import Bunch from ..utils import check_random_state from ..utils import shuffle as shuffle_method @@ -202,9 +203,7 @@ def fetch_kddcup99( if shuffle: data, target = shuffle_method(data, target, random_state=random_state) - module_path = dirname(__file__) - with open(join(module_path, "descr", "kddcup99.rst")) as rst_file: - fdescr = rst_file.read() + fdescr = load_descr("kddcup99.rst") frame = None if as_frame: diff --git a/sklearn/datasets/_lfw.py b/sklearn/datasets/_lfw.py index 3048bb87a2c4f..fb7d603bfc0ff 100644 --- a/sklearn/datasets/_lfw.py +++ b/sklearn/datasets/_lfw.py @@ -9,7 +9,7 @@ # License: BSD 3 clause from os import listdir, makedirs, remove -from os.path import dirname, join, exists, isdir +from os.path import join, exists, isdir import logging @@ -17,7 +17,12 @@ import joblib from joblib import Memory -from ._base import get_data_home, _fetch_remote, RemoteFileMetadata +from ._base import ( + get_data_home, + _fetch_remote, + RemoteFileMetadata, + load_descr, +) from ..utils import Bunch from ..utils.fixes import parse_version @@ -329,9 +334,7 @@ def fetch_lfw_people( X = faces.reshape(len(faces), -1) - module_path = dirname(__file__) - with open(join(module_path, "descr", "lfw.rst")) as rst_file: - fdescr = rst_file.read() + fdescr = load_descr("lfw.rst") if return_X_y: return X, target @@ -519,9 +522,7 @@ def fetch_lfw_pairs( index_file_path, data_folder_path, resize=resize, color=color, slice_=slice_ ) - module_path = dirname(__file__) - with open(join(module_path, "descr", "lfw.rst")) as rst_file: - fdescr = rst_file.read() + fdescr = load_descr("lfw.rst") # pack the results as a Bunch instance return Bunch( diff --git a/sklearn/datasets/_olivetti_faces.py b/sklearn/datasets/_olivetti_faces.py index 41279778eea11..038acb12ea15b 100644 --- a/sklearn/datasets/_olivetti_faces.py +++ b/sklearn/datasets/_olivetti_faces.py @@ -13,7 +13,7 @@ # Copyright (c) 2011 David Warde-Farley <wardefar at iro dot umontreal dot ca> # License: BSD 3 clause -from os.path import dirname, exists, join +from os.path import exists from os import makedirs, remove import numpy as np @@ -24,6 +24,7 @@ from ._base import _fetch_remote from ._base import RemoteFileMetadata from ._base import _pkl_filepath +from ._base import load_descr from ..utils import check_random_state, Bunch # The original data can be found at: @@ -137,9 +138,7 @@ def fetch_olivetti_faces( target = target[order] faces_vectorized = faces.reshape(len(faces), -1) - module_path = dirname(__file__) - with open(join(module_path, "descr", "olivetti_faces.rst")) as rst_file: - fdescr = rst_file.read() + fdescr = load_descr("olivetti_faces.rst") if return_X_y: return faces_vectorized, target diff --git a/sklearn/datasets/_rcv1.py b/sklearn/datasets/_rcv1.py index f815bcc2e253d..8669eec721453 100644 --- a/sklearn/datasets/_rcv1.py +++ b/sklearn/datasets/_rcv1.py @@ -11,7 +11,7 @@ import logging from os import remove, makedirs -from os.path import dirname, exists, join +from os.path import exists, join from gzip import GzipFile import numpy as np @@ -22,6 +22,7 @@ from ._base import _pkl_filepath from ._base import _fetch_remote from ._base import RemoteFileMetadata +from ._base import load_descr from ._svmlight_format_io import load_svmlight_files from ..utils import shuffle as shuffle_ from ..utils import Bunch @@ -268,9 +269,7 @@ def fetch_rcv1( if shuffle: X, y, sample_id = shuffle_(X, y, sample_id, random_state=random_state) - module_path = dirname(__file__) - with open(join(module_path, "descr", "rcv1.rst")) as rst_file: - fdescr = rst_file.read() + fdescr = load_descr("rcv1.rst") if return_X_y: return X, y diff --git a/sklearn/datasets/_twenty_newsgroups.py b/sklearn/datasets/_twenty_newsgroups.py index 53f3e5317001f..7fe17cbcb0a7a 100644 --- a/sklearn/datasets/_twenty_newsgroups.py +++ b/sklearn/datasets/_twenty_newsgroups.py @@ -25,7 +25,6 @@ # License: BSD 3 clause import os -from os.path import dirname, join import logging import tarfile import pickle @@ -43,6 +42,7 @@ from ._base import _pkl_filepath from ._base import _fetch_remote from ._base import RemoteFileMetadata +from ._base import load_descr from ..feature_extraction.text import CountVectorizer from .. import preprocessing from ..utils import check_random_state, Bunch @@ -287,9 +287,7 @@ def fetch_20newsgroups( "subset can only be 'train', 'test' or 'all', got '%s'" % subset ) - module_path = dirname(__file__) - with open(join(module_path, "descr", "twenty_newsgroups.rst")) as rst_file: - fdescr = rst_file.read() + fdescr = load_descr("twenty_newsgroups.rst") data.DESCR = fdescr @@ -510,9 +508,7 @@ def fetch_20newsgroups_vectorized( % subset ) - module_path = dirname(__file__) - with open(join(module_path, "descr", "twenty_newsgroups.rst")) as rst_file: - fdescr = rst_file.read() + fdescr = load_descr("twenty_newsgroups.rst") frame = None target_name = ["category_class"] diff --git a/sklearn/datasets/data/__init__.py b/sklearn/datasets/data/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/sklearn/datasets/descr/__init__.py b/sklearn/datasets/descr/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/sklearn/datasets/images/__init__.py b/sklearn/datasets/images/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d
diff --git a/sklearn/datasets/tests/data/__init__.py b/sklearn/datasets/tests/data/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/sklearn/datasets/tests/data/openml/__init__.py b/sklearn/datasets/tests/data/openml/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/sklearn/datasets/tests/data/openml/id_1/__init__.py b/sklearn/datasets/tests/data/openml/id_1/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/sklearn/datasets/tests/data/openml/1/api-v1-jd-1.json.gz b/sklearn/datasets/tests/data/openml/id_1/api-v1-jd-1.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/1/api-v1-jd-1.json.gz rename to sklearn/datasets/tests/data/openml/id_1/api-v1-jd-1.json.gz diff --git a/sklearn/datasets/tests/data/openml/1/api-v1-jdf-1.json.gz b/sklearn/datasets/tests/data/openml/id_1/api-v1-jdf-1.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/1/api-v1-jdf-1.json.gz rename to sklearn/datasets/tests/data/openml/id_1/api-v1-jdf-1.json.gz diff --git a/sklearn/datasets/tests/data/openml/1/api-v1-jdq-1.json.gz b/sklearn/datasets/tests/data/openml/id_1/api-v1-jdq-1.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/1/api-v1-jdq-1.json.gz rename to sklearn/datasets/tests/data/openml/id_1/api-v1-jdq-1.json.gz diff --git a/sklearn/datasets/tests/data/openml/1/data-v1-dl-1.arff.gz b/sklearn/datasets/tests/data/openml/id_1/data-v1-dl-1.arff.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/1/data-v1-dl-1.arff.gz rename to sklearn/datasets/tests/data/openml/id_1/data-v1-dl-1.arff.gz diff --git a/sklearn/datasets/tests/data/openml/id_1119/__init__.py b/sklearn/datasets/tests/data/openml/id_1119/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/sklearn/datasets/tests/data/openml/1119/api-v1-jd-1119.json.gz b/sklearn/datasets/tests/data/openml/id_1119/api-v1-jd-1119.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/1119/api-v1-jd-1119.json.gz rename to sklearn/datasets/tests/data/openml/id_1119/api-v1-jd-1119.json.gz diff --git a/sklearn/datasets/tests/data/openml/1119/api-v1-jdf-1119.json.gz b/sklearn/datasets/tests/data/openml/id_1119/api-v1-jdf-1119.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/1119/api-v1-jdf-1119.json.gz rename to sklearn/datasets/tests/data/openml/id_1119/api-v1-jdf-1119.json.gz diff --git a/sklearn/datasets/tests/data/openml/1119/api-v1-jdl-dn-adult-census-l-2-dv-1.json.gz b/sklearn/datasets/tests/data/openml/id_1119/api-v1-jdl-dn-adult-census-l-2-dv-1.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/1119/api-v1-jdl-dn-adult-census-l-2-dv-1.json.gz rename to sklearn/datasets/tests/data/openml/id_1119/api-v1-jdl-dn-adult-census-l-2-dv-1.json.gz diff --git a/sklearn/datasets/tests/data/openml/1119/api-v1-jdl-dn-adult-census-l-2-s-act-.json.gz b/sklearn/datasets/tests/data/openml/id_1119/api-v1-jdl-dn-adult-census-l-2-s-act-.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/1119/api-v1-jdl-dn-adult-census-l-2-s-act-.json.gz rename to sklearn/datasets/tests/data/openml/id_1119/api-v1-jdl-dn-adult-census-l-2-s-act-.json.gz diff --git a/sklearn/datasets/tests/data/openml/1119/api-v1-jdq-1119.json.gz b/sklearn/datasets/tests/data/openml/id_1119/api-v1-jdq-1119.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/1119/api-v1-jdq-1119.json.gz rename to sklearn/datasets/tests/data/openml/id_1119/api-v1-jdq-1119.json.gz diff --git a/sklearn/datasets/tests/data/openml/1119/data-v1-dl-54002.arff.gz b/sklearn/datasets/tests/data/openml/id_1119/data-v1-dl-54002.arff.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/1119/data-v1-dl-54002.arff.gz rename to sklearn/datasets/tests/data/openml/id_1119/data-v1-dl-54002.arff.gz diff --git a/sklearn/datasets/tests/data/openml/id_2/__init__.py b/sklearn/datasets/tests/data/openml/id_2/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/sklearn/datasets/tests/data/openml/2/api-v1-jd-2.json.gz b/sklearn/datasets/tests/data/openml/id_2/api-v1-jd-2.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/2/api-v1-jd-2.json.gz rename to sklearn/datasets/tests/data/openml/id_2/api-v1-jd-2.json.gz diff --git a/sklearn/datasets/tests/data/openml/2/api-v1-jdf-2.json.gz b/sklearn/datasets/tests/data/openml/id_2/api-v1-jdf-2.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/2/api-v1-jdf-2.json.gz rename to sklearn/datasets/tests/data/openml/id_2/api-v1-jdf-2.json.gz diff --git a/sklearn/datasets/tests/data/openml/2/api-v1-jdl-dn-anneal-l-2-dv-1.json.gz b/sklearn/datasets/tests/data/openml/id_2/api-v1-jdl-dn-anneal-l-2-dv-1.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/2/api-v1-jdl-dn-anneal-l-2-dv-1.json.gz rename to sklearn/datasets/tests/data/openml/id_2/api-v1-jdl-dn-anneal-l-2-dv-1.json.gz diff --git a/sklearn/datasets/tests/data/openml/2/api-v1-jdl-dn-anneal-l-2-s-act-.json.gz b/sklearn/datasets/tests/data/openml/id_2/api-v1-jdl-dn-anneal-l-2-s-act-.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/2/api-v1-jdl-dn-anneal-l-2-s-act-.json.gz rename to sklearn/datasets/tests/data/openml/id_2/api-v1-jdl-dn-anneal-l-2-s-act-.json.gz diff --git a/sklearn/datasets/tests/data/openml/2/api-v1-jdq-2.json.gz b/sklearn/datasets/tests/data/openml/id_2/api-v1-jdq-2.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/2/api-v1-jdq-2.json.gz rename to sklearn/datasets/tests/data/openml/id_2/api-v1-jdq-2.json.gz diff --git a/sklearn/datasets/tests/data/openml/2/data-v1-dl-1666876.arff.gz b/sklearn/datasets/tests/data/openml/id_2/data-v1-dl-1666876.arff.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/2/data-v1-dl-1666876.arff.gz rename to sklearn/datasets/tests/data/openml/id_2/data-v1-dl-1666876.arff.gz diff --git a/sklearn/datasets/tests/data/openml/id_292/__init__.py b/sklearn/datasets/tests/data/openml/id_292/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/sklearn/datasets/tests/data/openml/292/api-v1-jd-292.json.gz b/sklearn/datasets/tests/data/openml/id_292/api-v1-jd-292.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/292/api-v1-jd-292.json.gz rename to sklearn/datasets/tests/data/openml/id_292/api-v1-jd-292.json.gz diff --git a/sklearn/datasets/tests/data/openml/292/api-v1-jd-40981.json.gz b/sklearn/datasets/tests/data/openml/id_292/api-v1-jd-40981.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/292/api-v1-jd-40981.json.gz rename to sklearn/datasets/tests/data/openml/id_292/api-v1-jd-40981.json.gz diff --git a/sklearn/datasets/tests/data/openml/292/api-v1-jdf-292.json.gz b/sklearn/datasets/tests/data/openml/id_292/api-v1-jdf-292.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/292/api-v1-jdf-292.json.gz rename to sklearn/datasets/tests/data/openml/id_292/api-v1-jdf-292.json.gz diff --git a/sklearn/datasets/tests/data/openml/292/api-v1-jdf-40981.json.gz b/sklearn/datasets/tests/data/openml/id_292/api-v1-jdf-40981.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/292/api-v1-jdf-40981.json.gz rename to sklearn/datasets/tests/data/openml/id_292/api-v1-jdf-40981.json.gz diff --git a/sklearn/datasets/tests/data/openml/292/api-v1-jdl-dn-australian-l-2-dv-1-s-dact.json.gz b/sklearn/datasets/tests/data/openml/id_292/api-v1-jdl-dn-australian-l-2-dv-1-s-dact.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/292/api-v1-jdl-dn-australian-l-2-dv-1-s-dact.json.gz rename to sklearn/datasets/tests/data/openml/id_292/api-v1-jdl-dn-australian-l-2-dv-1-s-dact.json.gz diff --git a/sklearn/datasets/tests/data/openml/292/api-v1-jdl-dn-australian-l-2-dv-1.json.gz b/sklearn/datasets/tests/data/openml/id_292/api-v1-jdl-dn-australian-l-2-dv-1.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/292/api-v1-jdl-dn-australian-l-2-dv-1.json.gz rename to sklearn/datasets/tests/data/openml/id_292/api-v1-jdl-dn-australian-l-2-dv-1.json.gz diff --git a/sklearn/datasets/tests/data/openml/292/api-v1-jdl-dn-australian-l-2-s-act-.json.gz b/sklearn/datasets/tests/data/openml/id_292/api-v1-jdl-dn-australian-l-2-s-act-.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/292/api-v1-jdl-dn-australian-l-2-s-act-.json.gz rename to sklearn/datasets/tests/data/openml/id_292/api-v1-jdl-dn-australian-l-2-s-act-.json.gz diff --git a/sklearn/datasets/tests/data/openml/292/data-v1-dl-49822.arff.gz b/sklearn/datasets/tests/data/openml/id_292/data-v1-dl-49822.arff.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/292/data-v1-dl-49822.arff.gz rename to sklearn/datasets/tests/data/openml/id_292/data-v1-dl-49822.arff.gz diff --git a/sklearn/datasets/tests/data/openml/id_3/__init__.py b/sklearn/datasets/tests/data/openml/id_3/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/sklearn/datasets/tests/data/openml/3/api-v1-jd-3.json.gz b/sklearn/datasets/tests/data/openml/id_3/api-v1-jd-3.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/3/api-v1-jd-3.json.gz rename to sklearn/datasets/tests/data/openml/id_3/api-v1-jd-3.json.gz diff --git a/sklearn/datasets/tests/data/openml/3/api-v1-jdf-3.json.gz b/sklearn/datasets/tests/data/openml/id_3/api-v1-jdf-3.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/3/api-v1-jdf-3.json.gz rename to sklearn/datasets/tests/data/openml/id_3/api-v1-jdf-3.json.gz diff --git a/sklearn/datasets/tests/data/openml/3/api-v1-jdq-3.json.gz b/sklearn/datasets/tests/data/openml/id_3/api-v1-jdq-3.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/3/api-v1-jdq-3.json.gz rename to sklearn/datasets/tests/data/openml/id_3/api-v1-jdq-3.json.gz diff --git a/sklearn/datasets/tests/data/openml/3/data-v1-dl-3.arff.gz b/sklearn/datasets/tests/data/openml/id_3/data-v1-dl-3.arff.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/3/data-v1-dl-3.arff.gz rename to sklearn/datasets/tests/data/openml/id_3/data-v1-dl-3.arff.gz diff --git a/sklearn/datasets/tests/data/openml/id_40589/__init__.py b/sklearn/datasets/tests/data/openml/id_40589/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/sklearn/datasets/tests/data/openml/40589/api-v1-jd-40589.json.gz b/sklearn/datasets/tests/data/openml/id_40589/api-v1-jd-40589.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/40589/api-v1-jd-40589.json.gz rename to sklearn/datasets/tests/data/openml/id_40589/api-v1-jd-40589.json.gz diff --git a/sklearn/datasets/tests/data/openml/40589/api-v1-jdf-40589.json.gz b/sklearn/datasets/tests/data/openml/id_40589/api-v1-jdf-40589.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/40589/api-v1-jdf-40589.json.gz rename to sklearn/datasets/tests/data/openml/id_40589/api-v1-jdf-40589.json.gz diff --git a/sklearn/datasets/tests/data/openml/40589/api-v1-jdl-dn-emotions-l-2-dv-3.json.gz b/sklearn/datasets/tests/data/openml/id_40589/api-v1-jdl-dn-emotions-l-2-dv-3.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/40589/api-v1-jdl-dn-emotions-l-2-dv-3.json.gz rename to sklearn/datasets/tests/data/openml/id_40589/api-v1-jdl-dn-emotions-l-2-dv-3.json.gz diff --git a/sklearn/datasets/tests/data/openml/40589/api-v1-jdl-dn-emotions-l-2-s-act-.json.gz b/sklearn/datasets/tests/data/openml/id_40589/api-v1-jdl-dn-emotions-l-2-s-act-.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/40589/api-v1-jdl-dn-emotions-l-2-s-act-.json.gz rename to sklearn/datasets/tests/data/openml/id_40589/api-v1-jdl-dn-emotions-l-2-s-act-.json.gz diff --git a/sklearn/datasets/tests/data/openml/40589/api-v1-jdq-40589.json.gz b/sklearn/datasets/tests/data/openml/id_40589/api-v1-jdq-40589.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/40589/api-v1-jdq-40589.json.gz rename to sklearn/datasets/tests/data/openml/id_40589/api-v1-jdq-40589.json.gz diff --git a/sklearn/datasets/tests/data/openml/40589/data-v1-dl-4644182.arff.gz b/sklearn/datasets/tests/data/openml/id_40589/data-v1-dl-4644182.arff.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/40589/data-v1-dl-4644182.arff.gz rename to sklearn/datasets/tests/data/openml/id_40589/data-v1-dl-4644182.arff.gz diff --git a/sklearn/datasets/tests/data/openml/id_40675/__init__.py b/sklearn/datasets/tests/data/openml/id_40675/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/sklearn/datasets/tests/data/openml/40675/api-v1-jd-40675.json.gz b/sklearn/datasets/tests/data/openml/id_40675/api-v1-jd-40675.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/40675/api-v1-jd-40675.json.gz rename to sklearn/datasets/tests/data/openml/id_40675/api-v1-jd-40675.json.gz diff --git a/sklearn/datasets/tests/data/openml/40675/api-v1-jdf-40675.json.gz b/sklearn/datasets/tests/data/openml/id_40675/api-v1-jdf-40675.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/40675/api-v1-jdf-40675.json.gz rename to sklearn/datasets/tests/data/openml/id_40675/api-v1-jdf-40675.json.gz diff --git a/sklearn/datasets/tests/data/openml/40675/api-v1-jdl-dn-glass2-l-2-dv-1-s-dact.json.gz b/sklearn/datasets/tests/data/openml/id_40675/api-v1-jdl-dn-glass2-l-2-dv-1-s-dact.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/40675/api-v1-jdl-dn-glass2-l-2-dv-1-s-dact.json.gz rename to sklearn/datasets/tests/data/openml/id_40675/api-v1-jdl-dn-glass2-l-2-dv-1-s-dact.json.gz diff --git a/sklearn/datasets/tests/data/openml/40675/api-v1-jdl-dn-glass2-l-2-dv-1.json.gz b/sklearn/datasets/tests/data/openml/id_40675/api-v1-jdl-dn-glass2-l-2-dv-1.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/40675/api-v1-jdl-dn-glass2-l-2-dv-1.json.gz rename to sklearn/datasets/tests/data/openml/id_40675/api-v1-jdl-dn-glass2-l-2-dv-1.json.gz diff --git a/sklearn/datasets/tests/data/openml/40675/api-v1-jdl-dn-glass2-l-2-s-act-.json.gz b/sklearn/datasets/tests/data/openml/id_40675/api-v1-jdl-dn-glass2-l-2-s-act-.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/40675/api-v1-jdl-dn-glass2-l-2-s-act-.json.gz rename to sklearn/datasets/tests/data/openml/id_40675/api-v1-jdl-dn-glass2-l-2-s-act-.json.gz diff --git a/sklearn/datasets/tests/data/openml/40675/api-v1-jdq-40675.json.gz b/sklearn/datasets/tests/data/openml/id_40675/api-v1-jdq-40675.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/40675/api-v1-jdq-40675.json.gz rename to sklearn/datasets/tests/data/openml/id_40675/api-v1-jdq-40675.json.gz diff --git a/sklearn/datasets/tests/data/openml/40675/data-v1-dl-4965250.arff.gz b/sklearn/datasets/tests/data/openml/id_40675/data-v1-dl-4965250.arff.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/40675/data-v1-dl-4965250.arff.gz rename to sklearn/datasets/tests/data/openml/id_40675/data-v1-dl-4965250.arff.gz diff --git a/sklearn/datasets/tests/data/openml/id_40945/__init__.py b/sklearn/datasets/tests/data/openml/id_40945/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/sklearn/datasets/tests/data/openml/40945/api-v1-jd-40945.json.gz b/sklearn/datasets/tests/data/openml/id_40945/api-v1-jd-40945.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/40945/api-v1-jd-40945.json.gz rename to sklearn/datasets/tests/data/openml/id_40945/api-v1-jd-40945.json.gz diff --git a/sklearn/datasets/tests/data/openml/40945/api-v1-jdf-40945.json.gz b/sklearn/datasets/tests/data/openml/id_40945/api-v1-jdf-40945.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/40945/api-v1-jdf-40945.json.gz rename to sklearn/datasets/tests/data/openml/id_40945/api-v1-jdf-40945.json.gz diff --git a/sklearn/datasets/tests/data/openml/40945/api-v1-jdq-40945.json.gz b/sklearn/datasets/tests/data/openml/id_40945/api-v1-jdq-40945.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/40945/api-v1-jdq-40945.json.gz rename to sklearn/datasets/tests/data/openml/id_40945/api-v1-jdq-40945.json.gz diff --git a/sklearn/datasets/tests/data/openml/40945/data-v1-dl-16826755.arff.gz b/sklearn/datasets/tests/data/openml/id_40945/data-v1-dl-16826755.arff.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/40945/data-v1-dl-16826755.arff.gz rename to sklearn/datasets/tests/data/openml/id_40945/data-v1-dl-16826755.arff.gz diff --git a/sklearn/datasets/tests/data/openml/id_40966/__init__.py b/sklearn/datasets/tests/data/openml/id_40966/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/sklearn/datasets/tests/data/openml/40966/api-v1-jd-40966.json.gz b/sklearn/datasets/tests/data/openml/id_40966/api-v1-jd-40966.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/40966/api-v1-jd-40966.json.gz rename to sklearn/datasets/tests/data/openml/id_40966/api-v1-jd-40966.json.gz diff --git a/sklearn/datasets/tests/data/openml/40966/api-v1-jdf-40966.json.gz b/sklearn/datasets/tests/data/openml/id_40966/api-v1-jdf-40966.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/40966/api-v1-jdf-40966.json.gz rename to sklearn/datasets/tests/data/openml/id_40966/api-v1-jdf-40966.json.gz diff --git a/sklearn/datasets/tests/data/openml/40966/api-v1-jdl-dn-miceprotein-l-2-dv-4.json.gz b/sklearn/datasets/tests/data/openml/id_40966/api-v1-jdl-dn-miceprotein-l-2-dv-4.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/40966/api-v1-jdl-dn-miceprotein-l-2-dv-4.json.gz rename to sklearn/datasets/tests/data/openml/id_40966/api-v1-jdl-dn-miceprotein-l-2-dv-4.json.gz diff --git a/sklearn/datasets/tests/data/openml/40966/api-v1-jdl-dn-miceprotein-l-2-s-act-.json.gz b/sklearn/datasets/tests/data/openml/id_40966/api-v1-jdl-dn-miceprotein-l-2-s-act-.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/40966/api-v1-jdl-dn-miceprotein-l-2-s-act-.json.gz rename to sklearn/datasets/tests/data/openml/id_40966/api-v1-jdl-dn-miceprotein-l-2-s-act-.json.gz diff --git a/sklearn/datasets/tests/data/openml/40966/api-v1-jdq-40966.json.gz b/sklearn/datasets/tests/data/openml/id_40966/api-v1-jdq-40966.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/40966/api-v1-jdq-40966.json.gz rename to sklearn/datasets/tests/data/openml/id_40966/api-v1-jdq-40966.json.gz diff --git a/sklearn/datasets/tests/data/openml/40966/data-v1-dl-17928620.arff.gz b/sklearn/datasets/tests/data/openml/id_40966/data-v1-dl-17928620.arff.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/40966/data-v1-dl-17928620.arff.gz rename to sklearn/datasets/tests/data/openml/id_40966/data-v1-dl-17928620.arff.gz diff --git a/sklearn/datasets/tests/data/openml/id_42585/__init__.py b/sklearn/datasets/tests/data/openml/id_42585/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/sklearn/datasets/tests/data/openml/42585/api-v1-jd-42585.json.gz b/sklearn/datasets/tests/data/openml/id_42585/api-v1-jd-42585.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/42585/api-v1-jd-42585.json.gz rename to sklearn/datasets/tests/data/openml/id_42585/api-v1-jd-42585.json.gz diff --git a/sklearn/datasets/tests/data/openml/42585/api-v1-jdf-42585.json.gz b/sklearn/datasets/tests/data/openml/id_42585/api-v1-jdf-42585.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/42585/api-v1-jdf-42585.json.gz rename to sklearn/datasets/tests/data/openml/id_42585/api-v1-jdf-42585.json.gz diff --git a/sklearn/datasets/tests/data/openml/42585/api-v1-jdq-42585.json.gz b/sklearn/datasets/tests/data/openml/id_42585/api-v1-jdq-42585.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/42585/api-v1-jdq-42585.json.gz rename to sklearn/datasets/tests/data/openml/id_42585/api-v1-jdq-42585.json.gz diff --git a/sklearn/datasets/tests/data/openml/42585/data-v1-dl-21854866.arff.gz b/sklearn/datasets/tests/data/openml/id_42585/data-v1-dl-21854866.arff.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/42585/data-v1-dl-21854866.arff.gz rename to sklearn/datasets/tests/data/openml/id_42585/data-v1-dl-21854866.arff.gz diff --git a/sklearn/datasets/tests/data/openml/id_561/__init__.py b/sklearn/datasets/tests/data/openml/id_561/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/sklearn/datasets/tests/data/openml/561/api-v1-jd-561.json.gz b/sklearn/datasets/tests/data/openml/id_561/api-v1-jd-561.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/561/api-v1-jd-561.json.gz rename to sklearn/datasets/tests/data/openml/id_561/api-v1-jd-561.json.gz diff --git a/sklearn/datasets/tests/data/openml/561/api-v1-jdf-561.json.gz b/sklearn/datasets/tests/data/openml/id_561/api-v1-jdf-561.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/561/api-v1-jdf-561.json.gz rename to sklearn/datasets/tests/data/openml/id_561/api-v1-jdf-561.json.gz diff --git a/sklearn/datasets/tests/data/openml/561/api-v1-jdl-dn-cpu-l-2-dv-1.json.gz b/sklearn/datasets/tests/data/openml/id_561/api-v1-jdl-dn-cpu-l-2-dv-1.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/561/api-v1-jdl-dn-cpu-l-2-dv-1.json.gz rename to sklearn/datasets/tests/data/openml/id_561/api-v1-jdl-dn-cpu-l-2-dv-1.json.gz diff --git a/sklearn/datasets/tests/data/openml/561/api-v1-jdl-dn-cpu-l-2-s-act-.json.gz b/sklearn/datasets/tests/data/openml/id_561/api-v1-jdl-dn-cpu-l-2-s-act-.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/561/api-v1-jdl-dn-cpu-l-2-s-act-.json.gz rename to sklearn/datasets/tests/data/openml/id_561/api-v1-jdl-dn-cpu-l-2-s-act-.json.gz diff --git a/sklearn/datasets/tests/data/openml/561/api-v1-jdq-561.json.gz b/sklearn/datasets/tests/data/openml/id_561/api-v1-jdq-561.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/561/api-v1-jdq-561.json.gz rename to sklearn/datasets/tests/data/openml/id_561/api-v1-jdq-561.json.gz diff --git a/sklearn/datasets/tests/data/openml/561/data-v1-dl-52739.arff.gz b/sklearn/datasets/tests/data/openml/id_561/data-v1-dl-52739.arff.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/561/data-v1-dl-52739.arff.gz rename to sklearn/datasets/tests/data/openml/id_561/data-v1-dl-52739.arff.gz diff --git a/sklearn/datasets/tests/data/openml/id_61/__init__.py b/sklearn/datasets/tests/data/openml/id_61/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/sklearn/datasets/tests/data/openml/61/api-v1-jd-61.json.gz b/sklearn/datasets/tests/data/openml/id_61/api-v1-jd-61.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/61/api-v1-jd-61.json.gz rename to sklearn/datasets/tests/data/openml/id_61/api-v1-jd-61.json.gz diff --git a/sklearn/datasets/tests/data/openml/61/api-v1-jdf-61.json.gz b/sklearn/datasets/tests/data/openml/id_61/api-v1-jdf-61.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/61/api-v1-jdf-61.json.gz rename to sklearn/datasets/tests/data/openml/id_61/api-v1-jdf-61.json.gz diff --git a/sklearn/datasets/tests/data/openml/61/api-v1-jdl-dn-iris-l-2-dv-1.json.gz b/sklearn/datasets/tests/data/openml/id_61/api-v1-jdl-dn-iris-l-2-dv-1.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/61/api-v1-jdl-dn-iris-l-2-dv-1.json.gz rename to sklearn/datasets/tests/data/openml/id_61/api-v1-jdl-dn-iris-l-2-dv-1.json.gz diff --git a/sklearn/datasets/tests/data/openml/61/api-v1-jdl-dn-iris-l-2-s-act-.json.gz b/sklearn/datasets/tests/data/openml/id_61/api-v1-jdl-dn-iris-l-2-s-act-.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/61/api-v1-jdl-dn-iris-l-2-s-act-.json.gz rename to sklearn/datasets/tests/data/openml/id_61/api-v1-jdl-dn-iris-l-2-s-act-.json.gz diff --git a/sklearn/datasets/tests/data/openml/61/api-v1-jdq-61.json.gz b/sklearn/datasets/tests/data/openml/id_61/api-v1-jdq-61.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/61/api-v1-jdq-61.json.gz rename to sklearn/datasets/tests/data/openml/id_61/api-v1-jdq-61.json.gz diff --git a/sklearn/datasets/tests/data/openml/61/data-v1-dl-61.arff.gz b/sklearn/datasets/tests/data/openml/id_61/data-v1-dl-61.arff.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/61/data-v1-dl-61.arff.gz rename to sklearn/datasets/tests/data/openml/id_61/data-v1-dl-61.arff.gz diff --git a/sklearn/datasets/tests/data/openml/id_62/__init__.py b/sklearn/datasets/tests/data/openml/id_62/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/sklearn/datasets/tests/data/openml/62/api-v1-jd-62.json.gz b/sklearn/datasets/tests/data/openml/id_62/api-v1-jd-62.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/62/api-v1-jd-62.json.gz rename to sklearn/datasets/tests/data/openml/id_62/api-v1-jd-62.json.gz diff --git a/sklearn/datasets/tests/data/openml/62/api-v1-jdf-62.json.gz b/sklearn/datasets/tests/data/openml/id_62/api-v1-jdf-62.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/62/api-v1-jdf-62.json.gz rename to sklearn/datasets/tests/data/openml/id_62/api-v1-jdf-62.json.gz diff --git a/sklearn/datasets/tests/data/openml/62/api-v1-jdq-62.json.gz b/sklearn/datasets/tests/data/openml/id_62/api-v1-jdq-62.json.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/62/api-v1-jdq-62.json.gz rename to sklearn/datasets/tests/data/openml/id_62/api-v1-jdq-62.json.gz diff --git a/sklearn/datasets/tests/data/openml/62/data-v1-dl-52352.arff.gz b/sklearn/datasets/tests/data/openml/id_62/data-v1-dl-52352.arff.gz similarity index 100% rename from sklearn/datasets/tests/data/openml/62/data-v1-dl-52352.arff.gz rename to sklearn/datasets/tests/data/openml/id_62/data-v1-dl-52352.arff.gz diff --git a/sklearn/datasets/tests/test_20news.py b/sklearn/datasets/tests/test_20news.py index 437ced7aa8ee8..4244dd7865945 100644 --- a/sklearn/datasets/tests/test_20news.py +++ b/sklearn/datasets/tests/test_20news.py @@ -18,6 +18,7 @@ def test_20news(fetch_20newsgroups_fxt): data = fetch_20newsgroups_fxt(subset="all", shuffle=False) + assert data.DESCR.startswith(".. _20newsgroups_dataset:") # Extract a reduced dataset data2cats = fetch_20newsgroups_fxt( @@ -66,6 +67,7 @@ def test_20news_vectorized(fetch_20newsgroups_vectorized_fxt): assert bunch.data.shape == (11314, 130107) assert bunch.target.shape[0] == 11314 assert bunch.data.dtype == np.float64 + assert bunch.DESCR.startswith(".. _20newsgroups_dataset:") # test subset = test bunch = fetch_20newsgroups_vectorized_fxt(subset="test") @@ -73,6 +75,7 @@ def test_20news_vectorized(fetch_20newsgroups_vectorized_fxt): assert bunch.data.shape == (7532, 130107) assert bunch.target.shape[0] == 7532 assert bunch.data.dtype == np.float64 + assert bunch.DESCR.startswith(".. _20newsgroups_dataset:") # test return_X_y option fetch_func = partial(fetch_20newsgroups_vectorized_fxt, subset="test") @@ -84,6 +87,7 @@ def test_20news_vectorized(fetch_20newsgroups_vectorized_fxt): assert bunch.data.shape == (11314 + 7532, 130107) assert bunch.target.shape[0] == 11314 + 7532 assert bunch.data.dtype == np.float64 + assert bunch.DESCR.startswith(".. _20newsgroups_dataset:") def test_20news_normalization(fetch_20newsgroups_vectorized_fxt): diff --git a/sklearn/datasets/tests/test_base.py b/sklearn/datasets/tests/test_base.py index 47283d63a4ec5..dcab588757205 100644 --- a/sklearn/datasets/tests/test_base.py +++ b/sklearn/datasets/tests/test_base.py @@ -5,6 +5,7 @@ from pickle import loads from pickle import dumps from functools import partial +from importlib import resources import pytest @@ -21,6 +22,10 @@ from sklearn.datasets import load_breast_cancer from sklearn.datasets import load_boston from sklearn.datasets import load_wine +from sklearn.datasets._base import ( + load_csv_data, + load_gzip_compressed_csv_data, +) from sklearn.utils import Bunch from sklearn.datasets.tests.test_common import check_as_frame @@ -122,6 +127,69 @@ def test_load_files_wo_load_content( assert res.get("data") is None [email protected]( + "filename, expected_n_samples, expected_n_features, expected_target_names", + [ + ("wine_data.csv", 178, 13, ["class_0", "class_1", "class_2"]), + ("iris.csv", 150, 4, ["setosa", "versicolor", "virginica"]), + ("breast_cancer.csv", 569, 30, ["malignant", "benign"]), + ], +) +def test_load_csv_data( + filename, expected_n_samples, expected_n_features, expected_target_names +): + actual_data, actual_target, actual_target_names = load_csv_data(filename) + assert actual_data.shape[0] == expected_n_samples + assert actual_data.shape[1] == expected_n_features + assert actual_target.shape[0] == expected_n_samples + np.testing.assert_array_equal(actual_target_names, expected_target_names) + + +def test_load_csv_data_with_descr(): + data_file_name = "iris.csv" + descr_file_name = "iris.rst" + + res_without_descr = load_csv_data(data_file_name=data_file_name) + res_with_descr = load_csv_data( + data_file_name=data_file_name, descr_file_name=descr_file_name + ) + assert len(res_with_descr) == 4 + assert len(res_without_descr) == 3 + + np.testing.assert_array_equal(res_with_descr[0], res_without_descr[0]) + np.testing.assert_array_equal(res_with_descr[1], res_without_descr[1]) + np.testing.assert_array_equal(res_with_descr[2], res_without_descr[2]) + + assert res_with_descr[-1].startswith(".. _iris_dataset:") + + [email protected]( + "filename, kwargs, expected_shape", + [ + ("diabetes_data.csv.gz", {}, [442, 10]), + ("diabetes_target.csv.gz", {}, [442]), + ("digits.csv.gz", {"delimiter": ","}, [1797, 65]), + ], +) +def test_load_gzip_compressed_csv_data(filename, kwargs, expected_shape): + actual_data = load_gzip_compressed_csv_data(filename, **kwargs) + assert actual_data.shape == tuple(expected_shape) + + +def test_load_gzip_compressed_csv_data_with_descr(): + data_file_name = "diabetes_target.csv.gz" + descr_file_name = "diabetes.rst" + + expected_data = load_gzip_compressed_csv_data(data_file_name=data_file_name) + actual_data, descr = load_gzip_compressed_csv_data( + data_file_name=data_file_name, + descr_file_name=descr_file_name, + ) + + np.testing.assert_array_equal(actual_data, expected_data) + assert descr.startswith(".. _diabetes_dataset:") + + def test_load_sample_images(): try: res = load_sample_images() @@ -188,7 +256,13 @@ def test_loader(loader_func, data_shape, target_shape, n_target, has_descr, file if has_descr: assert bunch.DESCR if filenames: - assert all([os.path.exists(bunch.get(f, False)) for f in filenames]) + assert "data_module" in bunch + assert all( + [ + f in bunch and resources.is_resource(bunch["data_module"], bunch[f]) + for f in filenames + ] + ) @pytest.mark.parametrize( diff --git a/sklearn/datasets/tests/test_california_housing.py b/sklearn/datasets/tests/test_california_housing.py index ff979b954e98f..82a321e96a8d6 100644 --- a/sklearn/datasets/tests/test_california_housing.py +++ b/sklearn/datasets/tests/test_california_housing.py @@ -11,6 +11,7 @@ def test_fetch(fetch_california_housing_fxt): data = fetch_california_housing_fxt() assert (20640, 8) == data.data.shape assert (20640,) == data.target.shape + assert data.DESCR.startswith(".. _california_housing_dataset:") # test return_X_y option fetch_func = partial(fetch_california_housing_fxt) diff --git a/sklearn/datasets/tests/test_covtype.py b/sklearn/datasets/tests/test_covtype.py index 0824539a2bc2a..bbdd395a847f4 100644 --- a/sklearn/datasets/tests/test_covtype.py +++ b/sklearn/datasets/tests/test_covtype.py @@ -20,6 +20,10 @@ def test_fetch(fetch_covtype_fxt): assert (X1.shape[0],) == y1.shape assert (X1.shape[0],) == y2.shape + descr_prefix = ".. _covtype_dataset:" + assert data1.DESCR.startswith(descr_prefix) + assert data2.DESCR.startswith(descr_prefix) + # test return_X_y option fetch_func = partial(fetch_covtype_fxt) check_return_X_y(data1, fetch_func) diff --git a/sklearn/datasets/tests/test_kddcup99.py b/sklearn/datasets/tests/test_kddcup99.py index f6018c208da4e..b935da3a26add 100644 --- a/sklearn/datasets/tests/test_kddcup99.py +++ b/sklearn/datasets/tests/test_kddcup99.py @@ -33,6 +33,7 @@ def test_fetch_kddcup99_percent10( assert data.target.shape == (n_samples,) if as_frame: assert data.frame.shape == (n_samples, n_features + 1) + assert data.DESCR.startswith(".. _kddcup99_dataset:") def test_fetch_kddcup99_return_X_y(fetch_kddcup99_fxt): diff --git a/sklearn/datasets/tests/test_lfw.py b/sklearn/datasets/tests/test_lfw.py index 362129859fcdf..d7852ab99361a 100644 --- a/sklearn/datasets/tests/test_lfw.py +++ b/sklearn/datasets/tests/test_lfw.py @@ -145,6 +145,7 @@ def test_load_fake_lfw_people(): download_if_missing=False, ) assert lfw_people.images.shape == (17, 250, 250, 3) + assert lfw_people.DESCR.startswith(".. _labeled_faces_in_the_wild_dataset:") # the ids and class names are the same as previously assert_array_equal( @@ -219,3 +220,5 @@ def test_load_fake_lfw_pairs(): # the ids and class names are the same as previously assert_array_equal(lfw_pairs_train.target, [1, 1, 1, 1, 1, 0, 0, 0, 0, 0]) assert_array_equal(lfw_pairs_train.target_names, expected_classes) + + assert lfw_pairs_train.DESCR.startswith(".. _labeled_faces_in_the_wild_dataset:") diff --git a/sklearn/datasets/tests/test_olivetti_faces.py b/sklearn/datasets/tests/test_olivetti_faces.py index 996afa6e7e0f5..7d11516b0426c 100644 --- a/sklearn/datasets/tests/test_olivetti_faces.py +++ b/sklearn/datasets/tests/test_olivetti_faces.py @@ -21,6 +21,7 @@ def test_olivetti_faces(fetch_olivetti_faces_fxt): assert data.images.shape == (400, 64, 64) assert data.target.shape == (400,) assert_array_equal(np.unique(np.sort(data.target)), np.arange(40)) + assert data.DESCR.startswith(".. _olivetti_faces_dataset:") # test the return_X_y option check_return_X_y(data, fetch_olivetti_faces_fxt) diff --git a/sklearn/datasets/tests/test_openml.py b/sklearn/datasets/tests/test_openml.py index d99cc65bb9561..221e9362f4819 100644 --- a/sklearn/datasets/tests/test_openml.py +++ b/sklearn/datasets/tests/test_openml.py @@ -5,6 +5,7 @@ import json import os import re +from importlib import resources from io import BytesIO import numpy as np @@ -33,7 +34,7 @@ from sklearn.utils._testing import fails_if_pypy -currdir = os.path.dirname(os.path.abspath(__file__)) +OPENML_TEST_DATA_MODULE = "sklearn.datasets.tests.data.openml" # if True, urlopen will be monkey patched to only use local files test_offline = True @@ -220,6 +221,8 @@ def _monkey_patch_webbased_functions(context, data_id, gzip_response): path_suffix = ".gz" read_fn = gzip.open + data_module = OPENML_TEST_DATA_MODULE + "." + f"id_{data_id}" + def _file_name(url, suffix): output = ( re.sub(r"\W", "-", url[len("https://openml.org/") :]) + suffix + path_suffix @@ -240,74 +243,67 @@ def _file_name(url, suffix): .replace("-active", "-act") ) - def _mock_urlopen_data_description(url, has_gzip_header): - assert url.startswith(url_prefix_data_description) + def _mock_urlopen_shared(url, has_gzip_header, expected_prefix, suffix): + assert url.startswith(expected_prefix) - path = os.path.join( - currdir, "data", "openml", str(data_id), _file_name(url, ".json") - ) + data_file_name = _file_name(url, suffix) - if has_gzip_header and gzip_response: - with open(path, "rb") as f: + with resources.open_binary(data_module, data_file_name) as f: + if has_gzip_header and gzip_response: fp = BytesIO(f.read()) - return _MockHTTPResponse(fp, True) - else: - with read_fn(path, "rb") as f: - fp = BytesIO(f.read()) - return _MockHTTPResponse(fp, False) + return _MockHTTPResponse(fp, True) + else: + decompressed_f = read_fn(f, "rb") + fp = BytesIO(decompressed_f.read()) + return _MockHTTPResponse(fp, False) - def _mock_urlopen_data_features(url, has_gzip_header): - assert url.startswith(url_prefix_data_features) - path = os.path.join( - currdir, "data", "openml", str(data_id), _file_name(url, ".json") + def _mock_urlopen_data_description(url, has_gzip_header): + return _mock_urlopen_shared( + url=url, + has_gzip_header=has_gzip_header, + expected_prefix=url_prefix_data_description, + suffix=".json", ) - if has_gzip_header and gzip_response: - with open(path, "rb") as f: - fp = BytesIO(f.read()) - return _MockHTTPResponse(fp, True) - else: - with read_fn(path, "rb") as f: - fp = BytesIO(f.read()) - return _MockHTTPResponse(fp, False) + def _mock_urlopen_data_features(url, has_gzip_header): + return _mock_urlopen_shared( + url=url, + has_gzip_header=has_gzip_header, + expected_prefix=url_prefix_data_features, + suffix=".json", + ) def _mock_urlopen_download_data(url, has_gzip_header): - assert url.startswith(url_prefix_download_data) - - path = os.path.join( - currdir, "data", "openml", str(data_id), _file_name(url, ".arff") + return _mock_urlopen_shared( + url=url, + has_gzip_header=has_gzip_header, + expected_prefix=url_prefix_download_data, + suffix=".arff", ) - if has_gzip_header and gzip_response: - with open(path, "rb") as f: - fp = BytesIO(f.read()) - return _MockHTTPResponse(fp, True) - else: - with read_fn(path, "rb") as f: - fp = BytesIO(f.read()) - return _MockHTTPResponse(fp, False) - def _mock_urlopen_data_list(url, has_gzip_header): assert url.startswith(url_prefix_data_list) - json_file_path = os.path.join( - currdir, "data", "openml", str(data_id), _file_name(url, ".json") - ) + data_file_name = _file_name(url, ".json") + # load the file itself, to simulate a http error - json_data = json.loads(read_fn(json_file_path, "rb").read().decode("utf-8")) + with resources.open_binary(data_module, data_file_name) as f: + decompressed_f = read_fn(f, "rb") + decoded_s = decompressed_f.read().decode("utf-8") + json_data = json.loads(decoded_s) if "error" in json_data: raise HTTPError( url=None, code=412, msg="Simulated mock error", hdrs=None, fp=None ) - if has_gzip_header: - with open(json_file_path, "rb") as f: + with resources.open_binary(data_module, data_file_name) as f: + if has_gzip_header: fp = BytesIO(f.read()) - return _MockHTTPResponse(fp, True) - else: - with read_fn(json_file_path, "rb") as f: - fp = BytesIO(f.read()) - return _MockHTTPResponse(fp, False) + return _MockHTTPResponse(fp, True) + else: + decompressed_f = read_fn(f, "rb") + fp = BytesIO(decompressed_f.read()) + return _MockHTTPResponse(fp, False) def _mock_urlopen(request): url = request.get_full_url() @@ -1451,14 +1447,17 @@ def test_fetch_openml_verify_checksum(monkeypatch, as_frame, cache, tmpdir): _monkey_patch_webbased_functions(monkeypatch, data_id, True) # create a temporary modified arff file - dataset_dir = os.path.join(currdir, "data", "openml", str(data_id)) - original_data_path = os.path.join(dataset_dir, "data-v1-dl-1666876.arff.gz") - corrupt_copy = os.path.join(tmpdir, "test_invalid_checksum.arff") - with gzip.GzipFile(original_data_path, "rb") as orig_gzip, gzip.GzipFile( - corrupt_copy, "wb" - ) as modified_gzip: + original_data_module = OPENML_TEST_DATA_MODULE + "." + f"id_{data_id}" + original_data_file_name = "data-v1-dl-1666876.arff.gz" + corrupt_copy_path = tmpdir / "test_invalid_checksum.arff" + with resources.open_binary( + original_data_module, original_data_file_name + ) as orig_file: + orig_gzip = gzip.open(orig_file, "rb") data = bytearray(orig_gzip.read()) data[len(data) - 1] = 37 + + with gzip.GzipFile(corrupt_copy_path, "wb") as modified_gzip: modified_gzip.write(data) # Requests are already mocked by monkey_patch_webbased_functions. @@ -1469,7 +1468,7 @@ def test_fetch_openml_verify_checksum(monkeypatch, as_frame, cache, tmpdir): def swap_file_mock(request): url = request.get_full_url() if url.endswith("data/v1/download/1666876"): - return _MockHTTPResponse(open(corrupt_copy, "rb"), is_gzip=True) + return _MockHTTPResponse(open(corrupt_copy_path, "rb"), is_gzip=True) else: return mocked_openml_url(request) diff --git a/sklearn/datasets/tests/test_rcv1.py b/sklearn/datasets/tests/test_rcv1.py index c913a7a135c8b..cdc9f02c010c5 100644 --- a/sklearn/datasets/tests/test_rcv1.py +++ b/sklearn/datasets/tests/test_rcv1.py @@ -27,6 +27,9 @@ def test_fetch_rcv1(fetch_rcv1_fxt): assert (804414,) == s1.shape assert 103 == len(cat_list) + # test descr + assert data1.DESCR.startswith(".. _rcv1_dataset:") + # test ordering of categories first_categories = ["C11", "C12", "C13", "C14", "C15", "C151"] assert_array_equal(first_categories, cat_list[:6]) diff --git a/sklearn/datasets/tests/test_svmlight_format.py b/sklearn/datasets/tests/test_svmlight_format.py index 1b97fe26b6467..892b6d0d43ba6 100644 --- a/sklearn/datasets/tests/test_svmlight_format.py +++ b/sklearn/datasets/tests/test_svmlight_format.py @@ -5,6 +5,7 @@ import scipy.sparse as sp import os import shutil +from importlib import resources from tempfile import NamedTemporaryFile import pytest @@ -16,17 +17,26 @@ import sklearn from sklearn.datasets import load_svmlight_file, load_svmlight_files, dump_svmlight_file -currdir = os.path.dirname(os.path.abspath(__file__)) -datafile = os.path.join(currdir, "data", "svmlight_classification.txt") -multifile = os.path.join(currdir, "data", "svmlight_multilabel.txt") -invalidfile = os.path.join(currdir, "data", "svmlight_invalid.txt") -invalidfile2 = os.path.join(currdir, "data", "svmlight_invalid_order.txt") + +TEST_DATA_MODULE = "sklearn.datasets.tests.data" +datafile = "svmlight_classification.txt" +multifile = "svmlight_multilabel.txt" +invalidfile = "svmlight_invalid.txt" +invalidfile2 = "svmlight_invalid_order.txt" pytestmark = fails_if_pypy +def _load_svmlight_local_test_file(filename, **kwargs): + """ + Helper to load resource `filename` with `importlib.resources` + """ + with resources.open_binary(TEST_DATA_MODULE, filename) as f: + return load_svmlight_file(f, **kwargs) + + def test_load_svmlight_file(): - X, y = load_svmlight_file(datafile) + X, y = _load_svmlight_local_test_file(datafile) # test X's shape assert X.indptr.shape[0] == 7 @@ -63,39 +73,48 @@ def test_load_svmlight_file(): def test_load_svmlight_file_fd(): # test loading from file descriptor - X1, y1 = load_svmlight_file(datafile) - fd = os.open(datafile, os.O_RDONLY) - try: - X2, y2 = load_svmlight_file(fd) - assert_array_almost_equal(X1.data, X2.data) - assert_array_almost_equal(y1, y2) - finally: - os.close(fd) + # GH20081: testing equality between path-based and + # fd-based load_svmlight_file + with resources.path(TEST_DATA_MODULE, datafile) as data_path: + data_path = str(data_path) + X1, y1 = load_svmlight_file(data_path) + + fd = os.open(data_path, os.O_RDONLY) + try: + X2, y2 = load_svmlight_file(fd) + assert_array_almost_equal(X1.data, X2.data) + assert_array_almost_equal(y1, y2) + finally: + os.close(fd) def test_load_svmlight_file_multilabel(): - X, y = load_svmlight_file(multifile, multilabel=True) + X, y = _load_svmlight_local_test_file(multifile, multilabel=True) assert y == [(0, 1), (2,), (), (1, 2)] def test_load_svmlight_files(): - X_train, y_train, X_test, y_test = load_svmlight_files( - [datafile] * 2, dtype=np.float32 - ) + with resources.path(TEST_DATA_MODULE, datafile) as data_path: + X_train, y_train, X_test, y_test = load_svmlight_files( + [str(data_path)] * 2, dtype=np.float32 + ) assert_array_equal(X_train.toarray(), X_test.toarray()) assert_array_almost_equal(y_train, y_test) assert X_train.dtype == np.float32 assert X_test.dtype == np.float32 - X1, y1, X2, y2, X3, y3 = load_svmlight_files([datafile] * 3, dtype=np.float64) + with resources.path(TEST_DATA_MODULE, datafile) as data_path: + X1, y1, X2, y2, X3, y3 = load_svmlight_files( + [str(data_path)] * 3, dtype=np.float64 + ) assert X1.dtype == X2.dtype assert X2.dtype == X3.dtype assert X3.dtype == np.float64 def test_load_svmlight_file_n_features(): - X, y = load_svmlight_file(datafile, n_features=22) + X, y = _load_svmlight_local_test_file(datafile, n_features=22) # test X'shape assert X.indptr.shape[0] == 7 @@ -109,15 +128,15 @@ def test_load_svmlight_file_n_features(): # 21 features in file with pytest.raises(ValueError): - load_svmlight_file(datafile, n_features=20) + _load_svmlight_local_test_file(datafile, n_features=20) def test_load_compressed(): - X, y = load_svmlight_file(datafile) + X, y = _load_svmlight_local_test_file(datafile) with NamedTemporaryFile(prefix="sklearn-test", suffix=".gz") as tmp: tmp.close() # necessary under windows - with open(datafile, "rb") as f: + with resources.open_binary(TEST_DATA_MODULE, datafile) as f: with gzip.open(tmp.name, "wb") as fh_out: shutil.copyfileobj(f, fh_out) Xgz, ygz = load_svmlight_file(tmp.name) @@ -129,7 +148,7 @@ def test_load_compressed(): with NamedTemporaryFile(prefix="sklearn-test", suffix=".bz2") as tmp: tmp.close() # necessary under windows - with open(datafile, "rb") as f: + with resources.open_binary(TEST_DATA_MODULE, datafile) as f: with BZ2File(tmp.name, "wb") as fh_out: shutil.copyfileobj(f, fh_out) Xbz, ybz = load_svmlight_file(tmp.name) @@ -142,12 +161,12 @@ def test_load_compressed(): def test_load_invalid_file(): with pytest.raises(ValueError): - load_svmlight_file(invalidfile) + _load_svmlight_local_test_file(invalidfile) def test_load_invalid_order_file(): with pytest.raises(ValueError): - load_svmlight_file(invalidfile2) + _load_svmlight_local_test_file(invalidfile2) def test_load_zero_based(): @@ -208,7 +227,10 @@ def test_load_large_qid(): def test_load_invalid_file2(): with pytest.raises(ValueError): - load_svmlight_files([datafile, invalidfile, datafile]) + with resources.path(TEST_DATA_MODULE, datafile) as data_path, resources.path( + TEST_DATA_MODULE, invalidfile + ) as invalid_path: + load_svmlight_files([str(data_path), str(invalid_path), str(data_path)]) def test_not_a_filename(): @@ -224,7 +246,7 @@ def test_invalid_filename(): def test_dump(): - X_sparse, y_dense = load_svmlight_file(datafile) + X_sparse, y_dense = _load_svmlight_local_test_file(datafile) X_dense = X_sparse.toarray() y_sparse = sp.csr_matrix(y_dense) @@ -338,7 +360,7 @@ def test_dump_concise(): def test_dump_comment(): - X, y = load_svmlight_file(datafile) + X, y = _load_svmlight_local_test_file(datafile) X = X.toarray() f = BytesIO() @@ -371,7 +393,7 @@ def test_dump_comment(): def test_dump_invalid(): - X, y = load_svmlight_file(datafile) + X, y = _load_svmlight_local_test_file(datafile) f = BytesIO() y2d = [y] @@ -385,7 +407,7 @@ def test_dump_invalid(): def test_dump_query_id(): # test dumping a file with query_id - X, y = load_svmlight_file(datafile) + X, y = _load_svmlight_local_test_file(datafile) X = X.toarray() query_id = np.arange(X.shape[0]) // 2 f = BytesIO() @@ -530,4 +552,4 @@ def test_load_offset_exhaustive_splits(): def test_load_with_offsets_error(): with pytest.raises(ValueError, match="n_features is required"): - load_svmlight_file(datafile, offset=3, length=3) + _load_svmlight_local_test_file(datafile, offset=3, length=3) diff --git a/sklearn/tests/test_common.py b/sklearn/tests/test_common.py index 244da311fb036..1d6700cf46ded 100644 --- a/sklearn/tests/test_common.py +++ b/sklearn/tests/test_common.py @@ -208,6 +208,11 @@ def test_all_tests_are_importable(): \._ """ ) + resource_modules = { + "sklearn.datasets.data", + "sklearn.datasets.descr", + "sklearn.datasets.images", + } lookup = { name: ispkg for _, name, ispkg in pkgutil.walk_packages(sklearn.__path__, prefix="sklearn.") @@ -216,6 +221,7 @@ def test_all_tests_are_importable(): name for name, ispkg in lookup.items() if ispkg + and name not in resource_modules and not HAS_TESTS_EXCEPTIONS.search(name) and name + ".tests" not in lookup ]
[ { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex ecb4b5972a669..f3885f852591a 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -231,6 +231,13 @@ Changelog\n installing on Windows and its default 260 character limit on file names.\n :pr:`20209` by `Thomas Fan`_.\n \n+- |Enhancement| Replace usages of ``__file__`` related to resource file I/O\n+ with ``importlib.resources`` to avoid the assumption that these resource\n+ files (e.g. ``iris.csv``) already exist on a filesystem, and by extension\n+ to enable compatibility with tools such as ``PyOxidizer``.\n+ :pr:`20297` by :user:`Jack Liu <jackzyliu>`\n+\n+\n :mod:`sklearn.decomposition`\n ............................\n \n" } ]
1.00
238451d55ed57c3d16bc42f6a74f5f0126a7c700
[ "sklearn/datasets/tests/test_openml.py::test_fetch_openml_cpu[False]", "sklearn/datasets/tests/test_openml.py::test_open_openml_url_unlinks_local_path[False-True]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_with_ignored_feature[False]", "sklearn/datasets/tests/test_svmlight_format.py::test_load_with_offsets[41-101-0.5]", "sklearn/datasets/tests/test_lfw.py::test_load_empty_lfw_pairs", "sklearn/datasets/tests/test_openml.py::test_warn_ignore_attribute[True]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_as_frame_auto", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_cache[True]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_raises_missing_values_target[False]", "sklearn/datasets/tests/test_svmlight_format.py::test_load_with_offsets[41-13-0.99]", "sklearn/datasets/tests/test_openml.py::test_feature_to_dtype[feature5-float64]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_adultcensus[False]", "sklearn/datasets/tests/test_openml.py::test_fetch_nonexiting[True]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_miceprotein_pandas", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_cpu_pandas", "sklearn/datasets/tests/test_svmlight_format.py::test_load_svmlight_file_n_features", "sklearn/datasets/tests/test_svmlight_format.py::test_dump_query_id", "sklearn/datasets/tests/test_svmlight_format.py::test_load_with_offsets[7-101-0]", "sklearn/datasets/tests/test_svmlight_format.py::test_not_a_filename", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_with_ignored_feature[True]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_iris[True]", "sklearn/datasets/tests/test_lfw.py::test_load_fake_lfw_people_too_restrictive", "sklearn/datasets/tests/test_openml.py::test_open_openml_url_cache[False]", "sklearn/datasets/tests/test_svmlight_format.py::test_load_with_offsets[7-101-1]", "sklearn/datasets/tests/test_svmlight_format.py::test_load_with_offsets[2-13-1]", "sklearn/datasets/tests/test_openml.py::test_dataset_with_openml_error[True]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_anneal[True]", "sklearn/datasets/tests/test_svmlight_format.py::test_load_with_offsets[2-101-0]", "sklearn/datasets/tests/test_svmlight_format.py::test_load_compressed", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_iris_multitarget[False]", "sklearn/datasets/tests/test_openml.py::test_raises_illegal_multitarget[True]", "sklearn/datasets/tests/test_svmlight_format.py::test_load_with_offsets[41-101-0.1]", "sklearn/datasets/tests/test_openml.py::test_dataset_with_openml_error[False]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_verify_checksum[True]", "sklearn/datasets/tests/test_openml.py::test_decode_anneal", "sklearn/datasets/tests/test_svmlight_format.py::test_load_with_offsets[2-13-0]", "sklearn/datasets/tests/test_svmlight_format.py::test_load_with_offsets[2-13-0.5]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_anneal[False]", "sklearn/datasets/tests/test_svmlight_format.py::test_load_with_offsets[7-13-0.99]", "sklearn/datasets/tests/test_svmlight_format.py::test_load_with_offsets[7-13-0.5]", "sklearn/datasets/tests/test_openml.py::test_dataset_with_openml_warning[True]", "sklearn/datasets/tests/test_svmlight_format.py::test_load_with_offsets[41-13-0.1]", "sklearn/datasets/tests/test_openml.py::test_feature_to_dtype[feature7-float64]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_notarget[False]", "sklearn/datasets/tests/test_svmlight_format.py::test_load_zero_based_auto", "sklearn/datasets/tests/test_openml.py::test_string_attribute_without_dataframe[False]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_verify_checksum[False]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_emotions_pandas", "sklearn/datasets/tests/test_openml.py::test_illegal_column[False]", "sklearn/datasets/tests/test_svmlight_format.py::test_load_svmlight_files", "sklearn/datasets/tests/test_svmlight_format.py::test_load_with_offsets[7-101-0.99]", "sklearn/datasets/tests/test_svmlight_format.py::test_load_with_offsets[41-101-0]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_cache[False]", "sklearn/datasets/tests/test_svmlight_format.py::test_load_svmlight_file", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_anneal_pandas", "sklearn/datasets/tests/test_svmlight_format.py::test_dump_comment", "sklearn/datasets/tests/test_svmlight_format.py::test_load_with_offsets[7-13-0]", "sklearn/datasets/tests/test_svmlight_format.py::test_load_with_offsets[2-13-0.99]", "sklearn/datasets/tests/test_svmlight_format.py::test_load_with_offsets[7-101-0.5]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_iris_multitarget_pandas", "sklearn/datasets/tests/test_openml.py::test_decode_cpu", "sklearn/datasets/tests/test_openml.py::test_feature_to_dtype[feature3-float64]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_emotions[True]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_iris_pandas_equal_to_no_frame", "sklearn/datasets/tests/test_svmlight_format.py::test_dump_multilabel", "sklearn/datasets/tests/test_svmlight_format.py::test_load_zeros", "sklearn/datasets/tests/test_svmlight_format.py::test_load_svmlight_file_fd", "sklearn/datasets/tests/test_svmlight_format.py::test_load_with_offsets[7-13-1]", "sklearn/datasets/tests/test_svmlight_format.py::test_invalid_filename", "sklearn/datasets/tests/test_openml.py::test_decode_emotions", "sklearn/datasets/tests/test_openml.py::test_string_attribute_without_dataframe[True]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_iris_pandas", "sklearn/datasets/tests/test_svmlight_format.py::test_load_invalid_file2", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_emotions[False]", "sklearn/datasets/tests/test_openml.py::test_open_openml_url_unlinks_local_path[False-False]", "sklearn/datasets/tests/test_openml.py::test_open_openml_url_cache[True]", "sklearn/datasets/tests/test_openml.py::test_retry_with_clean_cache_http_error", "sklearn/datasets/tests/test_svmlight_format.py::test_load_with_offsets[7-13-0.1]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_anneal_multitarget[True]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_australian[False]", "sklearn/datasets/tests/test_openml.py::test_dataset_with_openml_warning[False]", "sklearn/datasets/tests/test_openml.py::test_missing_values_pandas", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_iris[False]", "sklearn/datasets/tests/test_openml.py::test_feature_to_dtype[feature2-float64]", "sklearn/datasets/tests/test_openml.py::test_feature_to_dtype[feature8-category]", "sklearn/datasets/tests/test_openml.py::test_fetch_nonexiting[False]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_raises_illegal_argument", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_notarget[True]", "sklearn/datasets/tests/test_svmlight_format.py::test_load_with_offsets[41-13-0.5]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_adultcensus_pandas_return_X_y", "sklearn/datasets/tests/test_svmlight_format.py::test_load_with_offsets[41-13-0]", "sklearn/datasets/tests/test_svmlight_format.py::test_load_with_offsets[7-101-0.1]", "sklearn/datasets/tests/test_openml.py::test_decode_iris", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_cpu[True]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_miceprotein[True]", "sklearn/datasets/tests/test_lfw.py::test_load_fake_lfw_pairs", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_miceprotein[False]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_raises_missing_values_target[True]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_inactive[False]", "sklearn/datasets/tests/test_openml.py::test_convert_arff_data_type", "sklearn/datasets/tests/test_svmlight_format.py::test_load_svmlight_file_multilabel", "sklearn/datasets/tests/test_svmlight_format.py::test_load_with_offsets_error", "sklearn/datasets/tests/test_svmlight_format.py::test_load_offset_exhaustive_splits", "sklearn/datasets/tests/test_svmlight_format.py::test_load_with_offsets[41-101-1]", "sklearn/datasets/tests/test_openml.py::test_retry_with_clean_cache", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_adultcensus[True]", "sklearn/datasets/tests/test_openml.py::test_open_openml_url_unlinks_local_path[True-False]", "sklearn/datasets/tests/test_openml.py::test_raises_illegal_multitarget[False]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_adultcensus_pandas", "sklearn/datasets/tests/test_openml.py::test_illegal_column[True]", "sklearn/datasets/tests/test_lfw.py::test_load_empty_lfw_people", "sklearn/datasets/tests/test_openml.py::test_feature_to_dtype[feature6-int64]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_australian_pandas_error_sparse", "sklearn/datasets/tests/test_svmlight_format.py::test_load_with_offsets[41-101-0.99]", "sklearn/datasets/tests/test_openml.py::test_feature_to_dtype[feature4-float64]", "sklearn/datasets/tests/test_openml.py::test_convert_arff_data_dataframe_warning_low_memory_pandas", "sklearn/datasets/tests/test_openml.py::test_open_openml_url_unlinks_local_path[True-True]", "sklearn/datasets/tests/test_openml.py::test_feature_to_dtype[feature9-category]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_inactive[True]", "sklearn/datasets/tests/test_svmlight_format.py::test_dump", "sklearn/datasets/tests/test_openml.py::test_feature_to_dtype_error[feature0]", "sklearn/datasets/tests/test_openml.py::test_feature_to_dtype[feature1-object]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_iris_multitarget[True]", "sklearn/datasets/tests/test_svmlight_format.py::test_load_with_offsets[2-101-0.5]", "sklearn/datasets/tests/test_svmlight_format.py::test_load_with_long_qid", "sklearn/datasets/tests/test_lfw.py::test_load_fake_lfw_people", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_australian[True]", "sklearn/datasets/tests/test_svmlight_format.py::test_load_with_offsets[41-13-1]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_titanic_pandas", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_anneal_multitarget[False]", "sklearn/datasets/tests/test_svmlight_format.py::test_load_with_offsets[2-101-0.99]", "sklearn/datasets/tests/test_openml.py::test_warn_ignore_attribute[False]", "sklearn/datasets/tests/test_svmlight_format.py::test_load_with_offsets[2-13-0.1]", "sklearn/datasets/tests/test_openml.py::test_feature_to_dtype[feature0-object]", "sklearn/datasets/tests/test_svmlight_format.py::test_load_with_qid", "sklearn/datasets/tests/test_svmlight_format.py::test_load_with_offsets[2-101-1]", "sklearn/datasets/tests/test_svmlight_format.py::test_load_invalid_order_file", "sklearn/datasets/tests/test_svmlight_format.py::test_dump_concise", "sklearn/datasets/tests/test_svmlight_format.py::test_load_invalid_file", "sklearn/datasets/tests/test_svmlight_format.py::test_dump_invalid", "sklearn/datasets/tests/test_svmlight_format.py::test_load_with_offsets[2-101-0.1]", "sklearn/datasets/tests/test_svmlight_format.py::test_load_zero_based" ]
[ "sklearn/datasets/tests/test_base.py::test_toy_dataset_frame_dtype[load_breast_cancer-float64-int]", "sklearn/datasets/tests/test_base.py::test_loader[load_breast_cancer-data_shape0-target_shape0-2-True-filenames0]", "sklearn/datasets/tests/test_base.py::test_loads_dumps_bunch", "sklearn/datasets/tests/test_base.py::test_data_home", "sklearn/datasets/tests/test_base.py::test_bunch_dir", "sklearn/datasets/tests/test_base.py::test_load_files_w_categories_desc_and_encoding", "sklearn/datasets/tests/test_base.py::test_loader[load_diabetes-data_shape4-target_shape4-None-True-filenames4]", "sklearn/datasets/tests/test_base.py::test_load_gzip_compressed_csv_data[digits.csv.gz-kwargs2-expected_shape2]", "sklearn/datasets/tests/test_base.py::test_toy_dataset_frame_dtype[load_diabetes-float64-float64]", "sklearn/datasets/tests/test_base.py::test_toy_dataset_frame_dtype[load_digits-float64-int]", "sklearn/datasets/tests/test_base.py::test_load_gzip_compressed_csv_data[diabetes_data.csv.gz-kwargs0-expected_shape0]", "sklearn/datasets/tests/test_base.py::test_load_csv_data_with_descr", "sklearn/datasets/tests/test_base.py::test_loader[load_digits-data_shape5-target_shape5-10-True-filenames5]", "sklearn/datasets/tests/test_base.py::test_loader[loader_func6-data_shape6-target_shape6-10-True-filenames6]", "sklearn/datasets/tests/test_base.py::test_load_files_wo_load_content", "sklearn/datasets/tests/test_base.py::test_loader[load_linnerud-data_shape3-target_shape3-3-True-filenames3]", "sklearn/datasets/tests/test_base.py::test_default_load_files", "sklearn/datasets/tests/test_base.py::test_loader[load_wine-data_shape1-target_shape1-3-True-filenames1]", "sklearn/datasets/tests/test_base.py::test_default_empty_load_files", "sklearn/datasets/tests/test_base.py::test_load_csv_data[breast_cancer.csv-569-30-expected_target_names2]", "sklearn/datasets/tests/test_base.py::test_load_sample_images", "sklearn/datasets/tests/test_base.py::test_load_sample_image", "sklearn/datasets/tests/test_base.py::test_loader[load_boston-data_shape7-target_shape7-None-True-filenames7]", "sklearn/datasets/tests/test_base.py::test_load_csv_data[wine_data.csv-178-13-expected_target_names0]", "sklearn/datasets/tests/test_base.py::test_load_csv_data[iris.csv-150-4-expected_target_names1]", "sklearn/datasets/tests/test_base.py::test_bunch_pickle_generated_with_0_16_and_read_with_0_17", "sklearn/datasets/tests/test_base.py::test_load_gzip_compressed_csv_data[diabetes_target.csv.gz-kwargs1-expected_shape1]", "sklearn/datasets/tests/test_base.py::test_load_gzip_compressed_csv_data_with_descr", "sklearn/datasets/tests/test_base.py::test_loader[load_iris-data_shape2-target_shape2-3-True-filenames2]", "sklearn/datasets/tests/test_base.py::test_toy_dataset_frame_dtype[load_iris-float64-int]", "sklearn/datasets/tests/test_base.py::test_toy_dataset_frame_dtype[load_linnerud-float64-float64]", "sklearn/datasets/tests/test_base.py::test_toy_dataset_frame_dtype[load_wine-float64-int]", "sklearn/datasets/tests/test_base.py::test_load_missing_sample_image_error" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [ { "type": "file", "name": "sklearn/datasets/data/__init__.py" }, { "type": "file", "name": "sklearn/datasets/images/__init__.py" }, { "type": "file", "name": "sklearn/datasets/descr/__init__.py" } ] }
[ { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex ecb4b5972a669..f3885f852591a 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -231,6 +231,13 @@ Changelog\n installing on Windows and its default 260 character limit on file names.\n :pr:`<PRID>` by `<NAME>`_.\n \n+- |Enhancement| Replace usages of ``__file__`` related to resource file I/O\n+ with ``importlib.resources`` to avoid the assumption that these resource\n+ files (e.g. ``iris.csv``) already exist on a filesystem, and by extension\n+ to enable compatibility with tools such as ``PyOxidizer``.\n+ :pr:`<PRID>` by :user:`<NAME>`\n+\n+\n :mod:`sklearn.decomposition`\n ............................\n \n" } ]
diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index ecb4b5972a669..f3885f852591a 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -231,6 +231,13 @@ Changelog installing on Windows and its default 260 character limit on file names. :pr:`<PRID>` by `<NAME>`_. +- |Enhancement| Replace usages of ``__file__`` related to resource file I/O + with ``importlib.resources`` to avoid the assumption that these resource + files (e.g. ``iris.csv``) already exist on a filesystem, and by extension + to enable compatibility with tools such as ``PyOxidizer``. + :pr:`<PRID>` by :user:`<NAME>` + + :mod:`sklearn.decomposition` ............................ If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names: [{'type': 'file', 'name': 'sklearn/datasets/data/__init__.py'}, {'type': 'file', 'name': 'sklearn/datasets/images/__init__.py'}, {'type': 'file', 'name': 'sklearn/datasets/descr/__init__.py'}]
scikit-learn/scikit-learn
scikit-learn__scikit-learn-17856
https://github.com/scikit-learn/scikit-learn/pull/17856
diff --git a/doc/modules/calibration.rst b/doc/modules/calibration.rst index cb157a9d78c93..146601d70765e 100644 --- a/doc/modules/calibration.rst +++ b/doc/modules/calibration.rst @@ -96,9 +96,9 @@ in [0, 1]. Denoting the output of the classifier for a given sample by :math:`f_ the calibrator tries to predict :math:`p(y_i = 1 | f_i)`. The samples that are used to fit the calibrator should not be the same -samples used to fit the classifier, as this would -introduce bias. The classifier performance on its training data would be -better than for novel data. Using the classifier output from training data +samples used to fit the classifier, as this would introduce bias. +This is because performance of the classifier on its training data would be +better than for novel data. Using the classifier output of training data to fit the calibrator would thus result in a biased calibrator that maps to probabilities closer to 0 and 1 than it should. @@ -107,22 +107,39 @@ Usage The :class:`CalibratedClassifierCV` class is used to calibrate a classifier. -:class:`CalibratedClassifierCV` uses a cross-validation approach to fit both -the classifier and the regressor. The data is split into k -`(train_set, test_set)` couples (as determined by `cv`). The classifier -(`base_estimator`) is trained on the train set, and its predictions on the -test set are used to fit a regressor. This ensures that the data used to fit -the classifier is always disjoint from the data used to fit the calibrator. -After fitting, we end up with k -`(classifier, regressor)` couples where each regressor maps the output of -its corresponding classifier into [0, 1]. Each couple is exposed in the -`calibrated_classifiers_` attribute, where each entry is a calibrated +:class:`CalibratedClassifierCV` uses a cross-validation approach to ensure +unbiased data is always used to fit the calibrator. The data is split into k +`(train_set, test_set)` couples (as determined by `cv`). When `ensemble=True` +(default), the following procedure is repeated independently for each +cross-validation split: a clone of `base_estimator` is first trained on the +train subset. Then its predictions on the test subset are used to fit a +calibrator (either a sigmoid or isotonic regressor). This results in an +ensemble of k `(classifier, calibrator)` couples where each calibrator maps +the output of its corresponding classifier into [0, 1]. Each couple is exposed +in the `calibrated_classifiers_` attribute, where each entry is a calibrated classifier with a :term:`predict_proba` method that outputs calibrated probabilities. The output of :term:`predict_proba` for the main :class:`CalibratedClassifierCV` instance corresponds to the average of the -predicted probabilities of the `k` estimators in the -`calibrated_classifiers_` list. The output of :term:`predict` is the class -that has the highest probability. +predicted probabilities of the `k` estimators in the `calibrated_classifiers_` +list. The output of :term:`predict` is the class that has the highest +probability. + +When `ensemble=False`, cross-validation is used to obtain 'unbiased' +predictions for all the data, via +:func:`~sklearn.model_selection.cross_val_predict`. +These unbiased predictions are then used to train the calibrator. The attribute +`calibrated_classifiers_` consists of only one `(classifier, calibrator)` +couple where the classifier is the `base_estimator` trained on all the data. +In this case the output of :term:`predict_proba` for +:class:`CalibratedClassifierCV` is the predicted probabilities obtained +from the single `(classifier, calibrator)` couple. + +The main advantage of `ensemble=True` is to benefit from the traditional +ensembling effect (similar to :ref:`bagging`). The resulting ensemble should +both be well calibrated and slightly more accurate than with `ensemble=False`. +The main advantage of using `ensemble=False` is computational: it reduces the +overall fit time by training only a single base classifier and calibrator +pair, decreases the final model size and increases prediction speed. Alternatively an already fitted classifier can be calibrated by setting `cv="prefit"`. In this case, the data is not split and all of it is used to diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index 0e87b29828977..15907d614d629 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -58,6 +58,14 @@ Changelog sparse matrix or dataframe at the start. :pr:`17546` by :user:`Lucy Liu <lucyleeow>`. +- |Enhancement| Add `ensemble` parameter to + :class:`calibration.CalibratedClassifierCV`, which enables implementation + of calibration via an ensemble of calibrators (current method) or + just one calibrator using all the data (similar to the built-in feature of + :mod:`sklearn.svm` estimators with the `probabilities=True` parameter). + :pr:`17856` by :user:`Lucy Liu <lucyleeow>` and + :user:`Andrea Esuli <aesuli>`. + :mod:`sklearn.cluster` ...................... diff --git a/sklearn/calibration.py b/sklearn/calibration.py index d1b0febb15605..3a6289402d929 100644 --- a/sklearn/calibration.py +++ b/sklearn/calibration.py @@ -10,6 +10,7 @@ import warnings from inspect import signature from contextlib import suppress +from functools import partial from math import log import numpy as np @@ -18,60 +19,43 @@ from scipy.special import expit from scipy.special import xlogy from scipy.optimize import fmin_bfgs -from .preprocessing import LabelEncoder from .base import (BaseEstimator, ClassifierMixin, RegressorMixin, clone, MetaEstimatorMixin) -from .preprocessing import label_binarize, LabelBinarizer +from .preprocessing import label_binarize, LabelEncoder from .utils import check_array, indexable, column_or_1d +from .utils.multiclass import check_classification_targets from .utils.fixes import delayed from .utils.validation import check_is_fitted, check_consistent_length from .utils.validation import _check_sample_weight from .pipeline import Pipeline from .isotonic import IsotonicRegression from .svm import LinearSVC -from .model_selection import check_cv +from .model_selection import check_cv, cross_val_predict from .utils.validation import _deprecate_positional_args -def _fit_calibrated_classifer(estimator, X, y, train, test, supports_sw, - method, classes, sample_weight=None): - """Fit calibrated classifier for a given dataset split. - - Returns - ------- - calibrated_classifier : estimator object - The calibrated estimator. - """ - if sample_weight is not None and supports_sw: - estimator.fit(X[train], y[train], - sample_weight=sample_weight[train]) - else: - estimator.fit(X[train], y[train]) - - calibrated_classifier = _CalibratedClassifier(estimator, - method=method, - classes=classes) - sw = None if sample_weight is None else sample_weight[test] - calibrated_classifier.fit(X[test], y[test], sample_weight=sw) - return calibrated_classifier - - class CalibratedClassifierCV(ClassifierMixin, MetaEstimatorMixin, BaseEstimator): """Probability calibration with isotonic regression or logistic regression. This class uses cross-validation to both estimate the parameters of a - classifier and subsequently calibrate a classifier. For each cv split it - fits a copy of the base estimator to the training folds, and calibrates it - using the testing fold. For prediction, predicted probabilities are - averaged across these individual calibrated classifiers. - - Already fitted classifiers can be calibrated via the parameter cv="prefit". - In this case, no cross-validation is used and all provided data is used - for calibration. The user has to take care manually that data for model - fitting and calibration are disjoint. + classifier and subsequently calibrate a classifier. With default + `ensemble=True`, for each cv split it + fits a copy of the base estimator to the training subset, and calibrates it + using the testing subset. For prediction, predicted probabilities are + averaged across these individual calibrated classifiers. When + `ensemble=False`, cross-validation is used to obtain unbiased predictions, + via :func:`~sklearn.model_selection.cross_val_predict`, which are then + used for calibration. For prediction, the base estimator, trained using all + the data, is used. This is the method implemented when `probabilities=True` + for :mod:`sklearn.svm` estimators. + + Already fitted classifiers can be calibrated via the parameter + `cv="prefit"`. In this case, no cross-validation is used and all provided + data is used for calibration. The user has to take care manually that data + for model fitting and calibration are disjoint. The calibration is based on the :term:`decision_function` method of the `base_estimator` if it exists, else on :term:`predict_proba`. @@ -122,21 +106,50 @@ class CalibratedClassifierCV(ClassifierMixin, ``-1`` means using all processors. Base estimator clones are fitted in parallel across cross-validation - iterations. Therefore parallelism happens only when cv != "prefit". + iterations. Therefore parallelism happens only when `cv != "prefit"`. See :term:`Glossary <n_jobs>` for more details. .. versionadded:: 0.24 + ensemble : bool, default=True + Determines how the calibrator is fitted when `cv` is not `'prefit'`. + Ignored if `cv='prefit'`. + + If `True`, the `base_estimator` is fitted using training data and + calibrated using testing data, for each `cv` fold. The final estimator + is an ensemble of `n_cv` fitted classifer and calibrator pairs, where + `n_cv` is the number of cross-validation folds. The output is the + average predicted probabilities of all pairs. + + If `False`, `cv` is used to compute unbiased predictions, via + :func:`~sklearn.model_selection.cross_val_predict`, which are then + used for calibration. At prediction time, the classifier used is the + `base_estimator` trained on all the data. + Note that this method is also internally implemented in + :mod:`sklearn.svm` estimators with the `probabilities=True` parameter. + + .. versionadded:: 0.24 + Attributes ---------- classes_ : ndarray of shape (n_classes,) The class labels. - calibrated_classifiers_ : list (len() equal to cv or 1 if cv == "prefit") - The list of calibrated classifiers, one for each cross-validation - split, which has been fitted on training folds and - calibrated on the testing fold. + calibrated_classifiers_ : list (len() equal to cv or 1 if `cv="prefit"` \ + or `ensemble=False`) + The list of classifier and calibrator pairs. + + - When `cv="prefit"`, the fitted `base_estimator` and fitted + calibrator. + - When `cv` is not "prefit" and `ensemble=True`, `n_cv` fitted + `base_estimator` and calibrator pairs. `n_cv` is the number of + cross-validation folds. + - When `cv` is not "prefit" and `ensemble=False`, the `base_estimator`, + fitted on all the data, and fitted calibrator. + + .. versionchanged:: 0.24 + Single calibrated classifier case when `ensemble=False`. Examples -------- @@ -194,14 +207,15 @@ class CalibratedClassifierCV(ClassifierMixin, """ @_deprecate_positional_args def __init__(self, base_estimator=None, *, method='sigmoid', - cv=None, n_jobs=None): + cv=None, n_jobs=None, ensemble=True): self.base_estimator = base_estimator self.method = method self.cv = cv self.n_jobs = n_jobs + self.ensemble = ensemble def fit(self, X, y, sample_weight=None): - """Fit the calibrated model + """Fit the calibrated model. Parameters ---------- @@ -219,9 +233,9 @@ def fit(self, X, y, sample_weight=None): self : object Returns an instance of self. """ + check_classification_targets(y) X, y = indexable(X, y) - self.calibrated_classifiers_ = [] if self.base_estimator is None: # we want all classifiers that don't expose a random_state # to be deterministic (and we don't want to expose this one). @@ -229,8 +243,10 @@ def fit(self, X, y, sample_weight=None): else: base_estimator = self.base_estimator + self.calibrated_classifiers_ = [] if self.cv == "prefit": - # Set `n_features_in_` attribute + # `classes_` and `n_features_in_` should be consistent with that + # of base_estimator if isinstance(self.base_estimator, Pipeline): check_is_fitted(self.base_estimator[-1]) else: @@ -239,17 +255,35 @@ def fit(self, X, y, sample_weight=None): self.n_features_in_ = base_estimator.n_features_in_ self.classes_ = self.base_estimator.classes_ - calibrated_classifier = _CalibratedClassifier( - base_estimator, method=self.method) - calibrated_classifier.fit(X, y, sample_weight) + pred_method = _get_prediction_method(base_estimator) + n_classes = len(self.classes_) + predictions = _compute_predictions(pred_method, X, n_classes) + + calibrated_classifier = _fit_calibrator( + base_estimator, predictions, y, self.classes_, self.method, + sample_weight + ) self.calibrated_classifiers_.append(calibrated_classifier) else: X, y = self._validate_data( X, y, accept_sparse=['csc', 'csr', 'coo'], force_all_finite=False, allow_nd=True ) - le = LabelBinarizer().fit(y) - self.classes_ = le.classes_ + # Set `classes_` using all `y` + label_encoder_ = LabelEncoder().fit(y) + self.classes_ = label_encoder_.classes_ + n_classes = len(self.classes_) + + # sample_weight checks + fit_parameters = signature(base_estimator.fit).parameters + supports_sw = "sample_weight" in fit_parameters + if sample_weight is not None: + sample_weight = _check_sample_weight(sample_weight, X) + if not supports_sw: + estimator_name = type(base_estimator).__name__ + warnings.warn(f"Since {estimator_name} does not support " + "sample_weights, sample weights will only be" + " used for the calibration itself.") # Check that each cross-validation fold can have at least one # example per class @@ -261,42 +295,46 @@ def fit(self, X, y, sample_weight=None): n_folds = None if n_folds and np.any([np.sum(y == class_) < n_folds for class_ in self.classes_]): - raise ValueError(f"Requesting {n_folds}-fold cross-validation " - f"but provided less than {n_folds} examples " - "for at least one class.") - + raise ValueError(f"Requesting {n_folds}-fold " + "cross-validation but provided less than " + f"{n_folds} examples for at least one class.") cv = check_cv(self.cv, y, classifier=True) - fit_parameters = signature(base_estimator.fit).parameters - supports_sw = "sample_weight" in fit_parameters - if sample_weight is not None: - sample_weight = _check_sample_weight(sample_weight, X) + if self.ensemble: + parallel = Parallel(n_jobs=self.n_jobs) - if not supports_sw: - estimator_name = type(base_estimator).__name__ - warnings.warn("Since %s does not support sample_weights, " - "sample weights will only be used for the " - "calibration itself." % estimator_name) - - parallel = Parallel(n_jobs=self.n_jobs) - - self.calibrated_classifiers_ = parallel(delayed( - _fit_calibrated_classifer)(clone(base_estimator), - X, y, - train=train, test=test, - method=self.method, - classes=self.classes_, - supports_sw=supports_sw, - sample_weight=sample_weight) - for train, test - in cv.split(X, y)) + self.calibrated_classifiers_ = parallel( + delayed(_fit_classifier_calibrator_pair)( + clone(base_estimator), X, y, train=train, test=test, + method=self.method, classes=self.classes_, + supports_sw=supports_sw, sample_weight=sample_weight) + for train, test in cv.split(X, y) + ) + else: + this_estimator = clone(base_estimator) + method_name = _get_prediction_method(this_estimator).__name__ + pred_method = partial( + cross_val_predict, estimator=this_estimator, X=X, y=y, + cv=cv, method=method_name, n_jobs=self.n_jobs + ) + predictions = _compute_predictions(pred_method, X, n_classes) + + if sample_weight is not None and supports_sw: + this_estimator.fit(X, y, sample_weight) + else: + this_estimator.fit(X, y) + calibrated_classifier = _fit_calibrator( + this_estimator, predictions, y, self.classes_, self.method, + sample_weight + ) + self.calibrated_classifiers_.append(calibrated_classifier) return self def predict_proba(self, X): - """Posterior probabilities of classification + """Calibrated probabilities of classification. - This function returns posterior probabilities of classification + This function returns calibrated probabilities of classification according to each class on an array of test vectors X. Parameters @@ -350,145 +388,244 @@ def _more_tags(self): } -class _CalibratedClassifier: - """Probability calibration with isotonic regression or sigmoid. +def _fit_classifier_calibrator_pair(estimator, X, y, train, test, supports_sw, + method, classes, sample_weight=None): + """Fit a classifier/calibration pair on a given train/test split. - It assumes that base_estimator has already been fit, and trains the - calibration on the input set of the fit function. Note that this class - should not be used as an estimator directly. Use CalibratedClassifierCV - with cv="prefit" instead. + Fit the classifier on the train set, compute its predictions on the test + set and use the predictions as input to fit the calibrator along with the + test labels. Parameters ---------- - base_estimator : instance BaseEstimator - The classifier whose output decision function needs to be calibrated - to offer more accurate predict_proba outputs. No default value since - it has to be an already fitted estimator. + estimator : estimator instance + Cloned base estimator. - method : {'sigmoid', 'isotonic'}, default='sigmoid' - The method to use for calibration. Can be 'sigmoid' which - corresponds to Platt's method or 'isotonic' which is a - non-parametric approach based on isotonic regression. + X : array-like, shape (n_samples, n_features) + Sample data. - classes : array-like of shape (n_classes,), default=None - Contains unique classes used to fit the base estimator. - if None, then classes is extracted from the given target values - in fit(). + y : array-like, shape (n_samples,) + Targets. - See Also - -------- - CalibratedClassifierCV + train : ndarray, shape (n_train_indicies,) + Indices of the training subset. - References + test : ndarray, shape (n_test_indicies,) + Indices of the testing subset. + + supports_sw : bool + Whether or not the `estimator` supports sample weights. + + method : {'sigmoid', 'isotonic'} + Method to use for calibration. + + classes : ndarray, shape (n_classes,) + The target classes. + + sample_weight : array-like, default=None + Sample weights for `X`. + + Returns + ------- + calibrated_classifier : _CalibratedClassifier instance + """ + if sample_weight is not None and supports_sw: + estimator.fit(X[train], y[train], + sample_weight=sample_weight[train]) + else: + estimator.fit(X[train], y[train]) + + n_classes = len(classes) + pred_method = _get_prediction_method(estimator) + predictions = _compute_predictions(pred_method, X[test], n_classes) + + sw = None if sample_weight is None else sample_weight[test] + calibrated_classifier = _fit_calibrator( + estimator, predictions, y[test], classes, method, sample_weight=sw + ) + return calibrated_classifier + + +def _get_prediction_method(clf): + """Return prediction method. + + `decision_function` method of `clf` returned, if it + exists, otherwise `predict_proba` method returned. + + Parameters ---------- - .. [1] Obtaining calibrated probability estimates from decision trees - and naive Bayesian classifiers, B. Zadrozny & C. Elkan, ICML 2001 + clf : Estimator instance + Fitted classifier to obtain the prediction method from. - .. [2] Transforming Classifier Scores into Accurate Multiclass - Probability Estimates, B. Zadrozny & C. Elkan, (KDD 2002) + Returns + ------- + prediction_method : callable + The prediction method. + """ + if hasattr(clf, 'decision_function'): + method = getattr(clf, 'decision_function') + elif hasattr(clf, 'predict_proba'): + method = getattr(clf, 'predict_proba') + else: + raise RuntimeError("'base_estimator' has no 'decision_function' or " + "'predict_proba' method.") + return method - .. [3] Probabilistic Outputs for Support Vector Machines and Comparisons to - Regularized Likelihood Methods, J. Platt, (1999) - .. [4] Predicting Good Probabilities with Supervised Learning, - A. Niculescu-Mizil & R. Caruana, ICML 2005 +def _compute_predictions(pred_method, X, n_classes): + """Return predictions for `X` and reshape binary outputs to shape + (n_samples, 1). + + Parameters + ---------- + pred_method : callable + Prediction method. + + X : array-like or None + Data used to obtain predictions. + + n_classes : int + Number of classes present. + + Returns + ------- + predictions : array-like, shape (X.shape[0], len(clf.classes_)) + The predictions. Note if there are 2 classes, array is of shape + (X.shape[0], 1). """ - @_deprecate_positional_args - def __init__(self, base_estimator, *, method='sigmoid', classes=None): - self.base_estimator = base_estimator - self.method = method - self.classes = classes + predictions = pred_method(X=X) + if hasattr(pred_method, '__name__'): + method_name = pred_method.__name__ + else: + method_name = signature(pred_method).parameters['method'].default - def _preproc(self, X): - n_classes = len(self.classes_) - if hasattr(self.base_estimator, "decision_function"): - df = self.base_estimator.decision_function(X) - if df.ndim == 1: - df = df[:, np.newaxis] - elif hasattr(self.base_estimator, "predict_proba"): - df = self.base_estimator.predict_proba(X) - if n_classes == 2: - df = df[:, 1:] - else: - raise RuntimeError('classifier has no decision_function or ' - 'predict_proba method.') + if method_name == 'decision_function': + if predictions.ndim == 1: + predictions = predictions[:, np.newaxis] + elif method_name == 'predict_proba': + if n_classes == 2: + predictions = predictions[:, 1:] + else: # pragma: no cover + # this branch should be unreachable. + raise ValueError(f"Invalid prediction method: {method_name}") + return predictions - idx_pos_class = self.label_encoder_.\ - transform(self.base_estimator.classes_) - return df, idx_pos_class +def _fit_calibrator(clf, predictions, y, classes, method, sample_weight=None): + """Fit calibrator(s) and return a `_CalibratedClassifier` + instance. - def fit(self, X, y, sample_weight=None): - """Calibrate the fitted model + `n_classes` (i.e. `len(clf.classes_)`) calibrators are fitted. + However, if `n_classes` equals 2, one calibrator is fitted. - Parameters - ---------- - X : array-like of shape (n_samples, n_features) - Training data. + Parameters + ---------- + clf : estimator instance + Fitted classifier. - y : array-like of shape (n_samples,) - Target values. + predictions : array-like, shape (n_samples, n_classes) or (n_samples, 1) \ + when binary. + Raw predictions returned by the un-calibrated base classifier. - sample_weight : array-like of shape (n_samples,), default=None - Sample weights. If None, then samples are equally weighted. + y : array-like, shape (n_samples,) + The targets. - Returns - ------- - self : object - Returns an instance of self. - """ + classes : ndarray, shape (n_classes,) + All the prediction classes. + + method : {'sigmoid', 'isotonic'} + The method to use for calibration. + + sample_weight : ndarray, shape (n_samples,), default=None + Sample weights. If None, then samples are equally weighted. - self.label_encoder_ = LabelEncoder() - if self.classes is None: - self.label_encoder_.fit(y) + Returns + ------- + pipeline : _CalibratedClassifier instance + """ + Y = label_binarize(y, classes=classes) + label_encoder = LabelEncoder().fit(classes) + pos_class_indices = label_encoder.transform(clf.classes_) + calibrators = [] + for class_idx, this_pred in zip(pos_class_indices, predictions.T): + if method == 'isotonic': + calibrator = IsotonicRegression(out_of_bounds='clip') + elif method == 'sigmoid': + calibrator = _SigmoidCalibration() else: - self.label_encoder_.fit(self.classes) + raise ValueError("'method' should be one of: 'sigmoid' or " + f"'isotonic'. Got {method}.") + calibrator.fit(this_pred, Y[:, class_idx], sample_weight) + calibrators.append(calibrator) - self.classes_ = self.label_encoder_.classes_ - Y = label_binarize(y, classes=self.classes_) + pipeline = _CalibratedClassifier( + clf, calibrators, method=method, classes=classes + ) + return pipeline - df, idx_pos_class = self._preproc(X) - self.calibrators_ = [] - for k, this_df in zip(idx_pos_class, df.T): - if self.method == 'isotonic': - calibrator = IsotonicRegression(out_of_bounds='clip') - elif self.method == 'sigmoid': - calibrator = _SigmoidCalibration() - else: - raise ValueError('method should be "sigmoid" or ' - '"isotonic". Got %s.' % self.method) - calibrator.fit(this_df, Y[:, k], sample_weight) - self.calibrators_.append(calibrator) +class _CalibratedClassifier: + """Pipeline-like chaining a fitted classifier and its fitted calibrators. - return self + Parameters + ---------- + base_estimator : estimator instance + Fitted classifier. + + calibrators : list of fitted estimator instances + List of fitted calibrators (either 'IsotonicRegression' or + '_SigmoidCalibration'). The number of calibrators equals the number of + classes. However, if there are 2 classes, the list contains only one + fitted calibrator. + + classes : array-like of shape (n_classes,) + All the prediction classes. + + method : {'sigmoid', 'isotonic'}, default='sigmoid' + The method to use for calibration. Can be 'sigmoid' which + corresponds to Platt's method or 'isotonic' which is a + non-parametric approach based on isotonic regression. + """ + def __init__(self, base_estimator, calibrators, *, classes, + method='sigmoid'): + self.base_estimator = base_estimator + self.calibrators = calibrators + self.classes = classes + self.method = method def predict_proba(self, X): - """Posterior probabilities of classification + """Calculate calibrated probabilities. - This function returns posterior probabilities of classification - according to each class on an array of test vectors X. + Calculates classification calibrated probabilities + for each class, in a one-vs-all manner, for `X`. Parameters ---------- - X : array-like of shape (n_samples, n_features) - The samples. + X : ndarray of shape (n_samples, n_features) + The sample data. Returns ------- - C : ndarray of shape (n_samples, n_classes) - The predicted probas. Can be exact zeros. + proba : array, shape (n_samples, n_classes) + The predicted probabilities. Can be exact zeros. """ - n_classes = len(self.classes_) - proba = np.zeros((X.shape[0], n_classes)) + n_classes = len(self.classes) + pred_method = _get_prediction_method(self.base_estimator) + predictions = _compute_predictions(pred_method, X, n_classes) - df, idx_pos_class = self._preproc(X) + label_encoder = LabelEncoder().fit(self.classes) + pos_class_indices = label_encoder.transform( + self.base_estimator.classes_ + ) - for k, this_df, calibrator in \ - zip(idx_pos_class, df.T, self.calibrators_): + proba = np.zeros((X.shape[0], n_classes)) + for class_idx, this_pred, calibrator in \ + zip(pos_class_indices, predictions.T, self.calibrators): if n_classes == 2: - k += 1 - proba[:, k] = calibrator.predict(this_df) + # When binary, `predictions` consists only of predictions for + # clf.classes_[1] but `pos_class_indices` = 0 + class_idx += 1 + proba[:, class_idx] = calibrator.predict(this_pred) # Normalize the probabilities if n_classes == 2: @@ -505,12 +642,12 @@ def predict_proba(self, X): return proba -def _sigmoid_calibration(df, y, sample_weight=None): +def _sigmoid_calibration(predictions, y, sample_weight=None): """Probability Calibration with sigmoid method (Platt 2000) Parameters ---------- - df : ndarray of shape (n_samples,) + predictions : ndarray of shape (n_samples,) The decision function or predict proba for the samples. y : ndarray of shape (n_samples,) @@ -531,10 +668,10 @@ def _sigmoid_calibration(df, y, sample_weight=None): ---------- Platt, "Probabilistic Outputs for Support Vector Machines" """ - df = column_or_1d(df) + predictions = column_or_1d(predictions) y = column_or_1d(y) - F = df # F follows Platt's notations + F = predictions # F follows Platt's notations # Bayesian priors (see Platt end of section 2.2) prior0 = float(np.sum(y <= 0))
diff --git a/sklearn/tests/test_calibration.py b/sklearn/tests/test_calibration.py index f4e6f6d62d938..3d2931d0c65f9 100644 --- a/sklearn/tests/test_calibration.py +++ b/sklearn/tests/test_calibration.py @@ -13,27 +13,38 @@ assert_almost_equal, assert_array_equal, assert_raises, ignore_warnings) +from sklearn.utils.extmath import softmax from sklearn.exceptions import NotFittedError from sklearn.datasets import make_classification, make_blobs -from sklearn.preprocessing import LabelBinarizer -from sklearn.model_selection import KFold +from sklearn.preprocessing import LabelEncoder +from sklearn.model_selection import KFold, cross_val_predict from sklearn.naive_bayes import MultinomialNB from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor from sklearn.svm import LinearSVC +from sklearn.isotonic import IsotonicRegression from sklearn.feature_extraction import DictVectorizer from sklearn.pipeline import Pipeline from sklearn.impute import SimpleImputer -from sklearn.metrics import brier_score_loss, log_loss +from sklearn.metrics import brier_score_loss from sklearn.calibration import CalibratedClassifierCV from sklearn.calibration import _sigmoid_calibration, _SigmoidCalibration from sklearn.calibration import calibration_curve -def test_calibration(): - """Test calibration objects with isotonic and sigmoid""" [email protected](scope="module") +def data(): + X, y = make_classification( + n_samples=200, n_features=6, random_state=42 + ) + return X, y + + [email protected]('method', ['sigmoid', 'isotonic']) [email protected]('ensemble', [True, False]) +def test_calibration(data, method, ensemble): + # Test calibration objects with isotonic and sigmoid n_samples = 100 - X, y = make_classification(n_samples=2 * n_samples, n_features=6, - random_state=42) + X, y = data sample_weight = np.random.RandomState(seed=42).uniform(size=y.size) X -= X.min() # MultinomialNB only allows positive X @@ -47,66 +58,76 @@ def test_calibration(): clf = MultinomialNB().fit(X_train, y_train, sample_weight=sw_train) prob_pos_clf = clf.predict_proba(X_test)[:, 1] - pc_clf = CalibratedClassifierCV(clf, cv=y.size + 1) - assert_raises(ValueError, pc_clf.fit, X, y) + cal_clf = CalibratedClassifierCV(clf, cv=y.size + 1, ensemble=ensemble) + assert_raises(ValueError, cal_clf.fit, X, y) # Naive Bayes with calibration for this_X_train, this_X_test in [(X_train, X_test), (sparse.csr_matrix(X_train), sparse.csr_matrix(X_test))]: - for method in ['isotonic', 'sigmoid']: - pc_clf = CalibratedClassifierCV(clf, method=method, cv=2) - # Note that this fit overwrites the fit on the entire training - # set - pc_clf.fit(this_X_train, y_train, sample_weight=sw_train) - prob_pos_pc_clf = pc_clf.predict_proba(this_X_test)[:, 1] - - # Check that brier score has improved after calibration + cal_clf = CalibratedClassifierCV( + clf, method=method, cv=5, ensemble=ensemble + ) + # Note that this fit overwrites the fit on the entire training + # set + cal_clf.fit(this_X_train, y_train, sample_weight=sw_train) + prob_pos_cal_clf = cal_clf.predict_proba(this_X_test)[:, 1] + + # Check that brier score has improved after calibration + assert (brier_score_loss(y_test, prob_pos_clf) > + brier_score_loss(y_test, prob_pos_cal_clf)) + + # Check invariance against relabeling [0, 1] -> [1, 2] + cal_clf.fit(this_X_train, y_train + 1, sample_weight=sw_train) + prob_pos_cal_clf_relabeled = cal_clf.predict_proba(this_X_test)[:, 1] + assert_array_almost_equal(prob_pos_cal_clf, + prob_pos_cal_clf_relabeled) + + # Check invariance against relabeling [0, 1] -> [-1, 1] + cal_clf.fit(this_X_train, 2 * y_train - 1, sample_weight=sw_train) + prob_pos_cal_clf_relabeled = cal_clf.predict_proba(this_X_test)[:, 1] + assert_array_almost_equal(prob_pos_cal_clf, prob_pos_cal_clf_relabeled) + + # Check invariance against relabeling [0, 1] -> [1, 0] + cal_clf.fit(this_X_train, (y_train + 1) % 2, sample_weight=sw_train) + prob_pos_cal_clf_relabeled = cal_clf.predict_proba(this_X_test)[:, 1] + if method == "sigmoid": + assert_array_almost_equal(prob_pos_cal_clf, + 1 - prob_pos_cal_clf_relabeled) + else: + # Isotonic calibration is not invariant against relabeling + # but should improve in both cases assert (brier_score_loss(y_test, prob_pos_clf) > - brier_score_loss(y_test, prob_pos_pc_clf)) - - # Check invariance against relabeling [0, 1] -> [1, 2] - pc_clf.fit(this_X_train, y_train + 1, sample_weight=sw_train) - prob_pos_pc_clf_relabeled = pc_clf.predict_proba(this_X_test)[:, 1] - assert_array_almost_equal(prob_pos_pc_clf, - prob_pos_pc_clf_relabeled) - - # Check invariance against relabeling [0, 1] -> [-1, 1] - pc_clf.fit(this_X_train, 2 * y_train - 1, sample_weight=sw_train) - prob_pos_pc_clf_relabeled = pc_clf.predict_proba(this_X_test)[:, 1] - assert_array_almost_equal(prob_pos_pc_clf, - prob_pos_pc_clf_relabeled) - - # Check invariance against relabeling [0, 1] -> [1, 0] - pc_clf.fit(this_X_train, (y_train + 1) % 2, - sample_weight=sw_train) - prob_pos_pc_clf_relabeled = \ - pc_clf.predict_proba(this_X_test)[:, 1] - if method == "sigmoid": - assert_array_almost_equal(prob_pos_pc_clf, - 1 - prob_pos_pc_clf_relabeled) - else: - # Isotonic calibration is not invariant against relabeling - # but should improve in both cases - assert (brier_score_loss(y_test, prob_pos_clf) > - brier_score_loss((y_test + 1) % 2, - prob_pos_pc_clf_relabeled)) + brier_score_loss((y_test + 1) % 2, + prob_pos_cal_clf_relabeled)) - # Check failure cases: - # only "isotonic" and "sigmoid" should be accepted as methods - clf_invalid_method = CalibratedClassifierCV(clf, method="foo") - assert_raises(ValueError, clf_invalid_method.fit, X_train, y_train) - # base-estimators should provide either decision_function or - # predict_proba (most regressors, for instance, should fail) - clf_base_regressor = \ - CalibratedClassifierCV(RandomForestRegressor(), method="sigmoid") - assert_raises(RuntimeError, clf_base_regressor.fit, X_train, y_train) [email protected]('ensemble', [True, False]) +def test_calibration_bad_method(data, ensemble): + # Check only "isotonic" and "sigmoid" are accepted as methods + X, y = data + clf = LinearSVC() + clf_invalid_method = CalibratedClassifierCV( + clf, method="foo", ensemble=ensemble + ) + with pytest.raises(ValueError): + clf_invalid_method.fit(X, y) + + [email protected]('ensemble', [True, False]) +def test_calibration_regressor(data, ensemble): + # `base-estimator` should provide either decision_function or + # predict_proba (most regressors, for instance, should fail) + X, y = data + clf_base_regressor = \ + CalibratedClassifierCV(RandomForestRegressor(), ensemble=ensemble) + with pytest.raises(RuntimeError): + clf_base_regressor.fit(X, y) -def test_calibration_default_estimator(): +def test_calibration_default_estimator(data): # Check base_estimator default is LinearSVC - X, y = make_classification(n_samples=100, n_features=6, random_state=42) + X, y = data calib_clf = CalibratedClassifierCV(cv=2) calib_clf.fit(X, y) @@ -114,120 +135,144 @@ def test_calibration_default_estimator(): assert isinstance(base_est, LinearSVC) -def test_calibration_cv_splitter(): [email protected]('ensemble', [True, False]) +def test_calibration_cv_splitter(data, ensemble): # Check when `cv` is a CV splitter - X, y = make_classification(n_samples=100, n_features=6, random_state=42) + X, y = data splits = 5 kfold = KFold(n_splits=splits) - calib_clf = CalibratedClassifierCV(cv=kfold) + calib_clf = CalibratedClassifierCV(cv=kfold, ensemble=ensemble) assert isinstance(calib_clf.cv, KFold) assert calib_clf.cv.n_splits == splits calib_clf.fit(X, y) - assert len(calib_clf.calibrated_classifiers_) == splits + expected_n_clf = splits if ensemble else 1 + assert len(calib_clf.calibrated_classifiers_) == expected_n_clf -def test_sample_weight(): [email protected]('method', ['sigmoid', 'isotonic']) [email protected]('ensemble', [True, False]) +def test_sample_weight(data, method, ensemble): n_samples = 100 - X, y = make_classification(n_samples=2 * n_samples, n_features=6, - random_state=42) + X, y = data sample_weight = np.random.RandomState(seed=42).uniform(size=len(y)) X_train, y_train, sw_train = \ X[:n_samples], y[:n_samples], sample_weight[:n_samples] X_test = X[n_samples:] - for method in ['sigmoid', 'isotonic']: - base_estimator = LinearSVC(random_state=42) - calibrated_clf = CalibratedClassifierCV(base_estimator, method=method) - calibrated_clf.fit(X_train, y_train, sample_weight=sw_train) - probs_with_sw = calibrated_clf.predict_proba(X_test) + base_estimator = LinearSVC(random_state=42) + calibrated_clf = CalibratedClassifierCV( + base_estimator, method=method, ensemble=ensemble + ) + calibrated_clf.fit(X_train, y_train, sample_weight=sw_train) + probs_with_sw = calibrated_clf.predict_proba(X_test) - # As the weights are used for the calibration, they should still yield - # a different predictions - calibrated_clf.fit(X_train, y_train) - probs_without_sw = calibrated_clf.predict_proba(X_test) + # As the weights are used for the calibration, they should still yield + # different predictions + calibrated_clf.fit(X_train, y_train) + probs_without_sw = calibrated_clf.predict_proba(X_test) - diff = np.linalg.norm(probs_with_sw - probs_without_sw) - assert diff > 0.1 + diff = np.linalg.norm(probs_with_sw - probs_without_sw) + assert diff > 0.1 [email protected]("method", ['sigmoid', 'isotonic']) -def test_parallel_execution(method): [email protected]('method', ['sigmoid', 'isotonic']) [email protected]('ensemble', [True, False]) +def test_parallel_execution(data, method, ensemble): """Test parallel calibration""" - X, y = make_classification(random_state=42) + X, y = data X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42) base_estimator = LinearSVC(random_state=42) - cal_clf_parallel = CalibratedClassifierCV(base_estimator, - method=method, n_jobs=2) + cal_clf_parallel = CalibratedClassifierCV( + base_estimator, method=method, n_jobs=2, ensemble=ensemble + ) cal_clf_parallel.fit(X_train, y_train) probs_parallel = cal_clf_parallel.predict_proba(X_test) - cal_clf_sequential = CalibratedClassifierCV(base_estimator, - method=method, - n_jobs=1) + cal_clf_sequential = CalibratedClassifierCV( + base_estimator, method=method, n_jobs=1, ensemble=ensemble + ) cal_clf_sequential.fit(X_train, y_train) probs_sequential = cal_clf_sequential.predict_proba(X_test) assert_allclose(probs_parallel, probs_sequential) -def test_calibration_multiclass(): - """Test calibration for multiclass """ - # test multi-class setting with classifier that implements - # only decision function - clf = LinearSVC() - X, y_idx = make_blobs(n_samples=100, n_features=2, random_state=42, - centers=3, cluster_std=3.0) - - # Use categorical labels to check that CalibratedClassifierCV supports - # them correctly - target_names = np.array(['a', 'b', 'c']) - y = target_names[y_idx] - [email protected]('method', ['sigmoid', 'isotonic']) [email protected]('ensemble', [True, False]) +# increase the number of RNG seeds to assess the statistical stability of this +# test: [email protected]('seed', range(2)) +def test_calibration_multiclass(method, ensemble, seed): + + def multiclass_brier(y_true, proba_pred, n_classes): + Y_onehot = np.eye(n_classes)[y_true] + return np.sum((Y_onehot - proba_pred) ** 2) / Y_onehot.shape[0] + + # Test calibration for multiclass with classifier that implements + # only decision function. + clf = LinearSVC(random_state=7) + X, y = make_blobs(n_samples=500, n_features=100, random_state=seed, + centers=10, cluster_std=15.0) + + # Use an unbalanced dataset by collapsing 8 clusters into one class + # to make the naive calibration based on a softmax more unlikely + # to work. + y[y > 2] = 2 + n_classes = np.unique(y).shape[0] X_train, y_train = X[::2], y[::2] X_test, y_test = X[1::2], y[1::2] clf.fit(X_train, y_train) - for method in ['isotonic', 'sigmoid']: - cal_clf = CalibratedClassifierCV(clf, method=method, cv=2) - cal_clf.fit(X_train, y_train) - probas = cal_clf.predict_proba(X_test) - assert_array_almost_equal(np.sum(probas, axis=1), np.ones(len(X_test))) - - # Check that log-loss of calibrated classifier is smaller than - # log-loss of naively turned OvR decision function to probabilities - # via softmax - def softmax(y_pred): - e = np.exp(-y_pred) - return e / e.sum(axis=1).reshape(-1, 1) - - uncalibrated_log_loss = \ - log_loss(y_test, softmax(clf.decision_function(X_test))) - calibrated_log_loss = log_loss(y_test, probas) - assert uncalibrated_log_loss >= calibrated_log_loss + + cal_clf = CalibratedClassifierCV( + clf, method=method, cv=5, ensemble=ensemble + ) + cal_clf.fit(X_train, y_train) + probas = cal_clf.predict_proba(X_test) + # Check probabilities sum to 1 + assert_allclose(np.sum(probas, axis=1), np.ones(len(X_test))) + + # Check that the dataset is not too trivial, otherwise it's hard + # to get interesting calibration data during the internal + # cross-validation loop. + assert 0.65 < clf.score(X_test, y_test) < 0.95 + + # Check that the accuracy of the calibrated model is never degraded + # too much compared to the original classifier. + assert cal_clf.score(X_test, y_test) > 0.95 * clf.score(X_test, y_test) + + # Check that Brier loss of calibrated classifier is smaller than + # loss obtained by naively turning OvR decision function to + # probabilities via a softmax + uncalibrated_brier = \ + multiclass_brier(y_test, softmax(clf.decision_function(X_test)), + n_classes=n_classes) + calibrated_brier = multiclass_brier(y_test, probas, + n_classes=n_classes) + + assert calibrated_brier < 1.1 * uncalibrated_brier # Test that calibration of a multiclass classifier decreases log-loss # for RandomForestClassifier - X, y = make_blobs(n_samples=100, n_features=2, random_state=42, - cluster_std=3.0) - X_train, y_train = X[::2], y[::2] - X_test, y_test = X[1::2], y[1::2] - - clf = RandomForestClassifier(n_estimators=10, random_state=42) + clf = RandomForestClassifier(n_estimators=30, random_state=42) clf.fit(X_train, y_train) clf_probs = clf.predict_proba(X_test) - loss = log_loss(y_test, clf_probs) + uncalibrated_brier = multiclass_brier(y_test, clf_probs, + n_classes=n_classes) - for method in ['isotonic', 'sigmoid']: - cal_clf = CalibratedClassifierCV(clf, method=method, cv=3) - cal_clf.fit(X_train, y_train) - cal_clf_probs = cal_clf.predict_proba(X_test) - cal_loss = log_loss(y_test, cal_clf_probs) - assert loss > cal_loss + cal_clf = CalibratedClassifierCV( + clf, method=method, cv=5, ensemble=ensemble + ) + cal_clf.fit(X_train, y_train) + cal_clf_probs = cal_clf.predict_proba(X_test) + calibrated_brier = multiclass_brier(y_test, cal_clf_probs, + n_classes=n_classes) + assert calibrated_brier < 1.1 * uncalibrated_brier def test_calibration_prefit(): @@ -262,18 +307,45 @@ def test_calibration_prefit(): (sparse.csr_matrix(X_calib), sparse.csr_matrix(X_test))]: for method in ['isotonic', 'sigmoid']: - pc_clf = CalibratedClassifierCV(clf, method=method, cv="prefit") + cal_clf = CalibratedClassifierCV(clf, method=method, cv="prefit") for sw in [sw_calib, None]: - pc_clf.fit(this_X_calib, y_calib, sample_weight=sw) - y_prob = pc_clf.predict_proba(this_X_test) - y_pred = pc_clf.predict(this_X_test) - prob_pos_pc_clf = y_prob[:, 1] + cal_clf.fit(this_X_calib, y_calib, sample_weight=sw) + y_prob = cal_clf.predict_proba(this_X_test) + y_pred = cal_clf.predict(this_X_test) + prob_pos_cal_clf = y_prob[:, 1] assert_array_equal(y_pred, np.array([0, 1])[np.argmax(y_prob, axis=1)]) assert (brier_score_loss(y_test, prob_pos_clf) > - brier_score_loss(y_test, prob_pos_pc_clf)) + brier_score_loss(y_test, prob_pos_cal_clf)) + + [email protected]('method', ['sigmoid', 'isotonic']) +def test_calibration_ensemble_false(data, method): + # Test that `ensemble=False` is the same as using predictions from + # `cross_val_predict` to train calibrator. + X, y = data + clf = LinearSVC(random_state=7) + + cal_clf = CalibratedClassifierCV(clf, method=method, cv=3, ensemble=False) + cal_clf.fit(X, y) + cal_probas = cal_clf.predict_proba(X) + + # Get probas manually + unbiased_preds = cross_val_predict( + clf, X, y, cv=3, method='decision_function' + ) + if method == 'isotonic': + calibrator = IsotonicRegression(out_of_bounds='clip') + else: + calibrator = _SigmoidCalibration() + calibrator.fit(unbiased_preds, y) + # Use `clf` fit on all data + clf.fit(X, y) + clf_df = clf.decision_function(X) + manual_probas = calibrator.predict(clf_df) + assert_allclose(cal_probas[:, 1], manual_probas) def test_sigmoid_calibration(): @@ -329,7 +401,8 @@ def test_calibration_curve(): strategy='percentile') -def test_calibration_nan_imputer(): [email protected]('ensemble', [True, False]) +def test_calibration_nan_imputer(ensemble): """Test that calibration can accept nan""" X, y = make_classification(n_samples=10, n_features=2, n_informative=2, n_redundant=0, @@ -338,42 +411,56 @@ def test_calibration_nan_imputer(): clf = Pipeline( [('imputer', SimpleImputer()), ('rf', RandomForestClassifier(n_estimators=1))]) - clf_c = CalibratedClassifierCV(clf, cv=2, method='isotonic') + clf_c = CalibratedClassifierCV( + clf, cv=2, method='isotonic', ensemble=ensemble + ) clf_c.fit(X, y) clf_c.predict(X) -def test_calibration_prob_sum(): [email protected]('ensemble', [True, False]) +def test_calibration_prob_sum(ensemble): # Test that sum of probabilities is 1. A non-regression test for # issue #7796 num_classes = 2 X, y = make_classification(n_samples=10, n_features=5, n_classes=num_classes) - clf = LinearSVC(C=1.0) - clf_prob = CalibratedClassifierCV(clf, method="sigmoid", cv=LeaveOneOut()) + clf = LinearSVC(C=1.0, random_state=7) + clf_prob = CalibratedClassifierCV( + clf, method="sigmoid", cv=LeaveOneOut(), ensemble=ensemble + ) clf_prob.fit(X, y) probs = clf_prob.predict_proba(X) assert_array_almost_equal(probs.sum(axis=1), np.ones(probs.shape[0])) -def test_calibration_less_classes(): [email protected]('ensemble', [True, False]) +def test_calibration_less_classes(ensemble): # Test to check calibration works fine when train set in a test-train # split does not contain all classes # Since this test uses LOO, at each iteration train set will not contain a # class label X = np.random.randn(10, 5) y = np.arange(10) - clf = LinearSVC(C=1.0) - cal_clf = CalibratedClassifierCV(clf, method="sigmoid", cv=LeaveOneOut()) + clf = LinearSVC(C=1.0, random_state=7) + cal_clf = CalibratedClassifierCV( + clf, method="sigmoid", cv=LeaveOneOut(), ensemble=ensemble + ) cal_clf.fit(X, y) for i, calibrated_classifier in \ enumerate(cal_clf.calibrated_classifiers_): proba = calibrated_classifier.predict_proba(X) - assert_array_equal(proba[:, i], np.zeros(len(y))) - assert np.all(np.hstack([proba[:, :i], - proba[:, i + 1:]])) + if ensemble: + # Check that the unobserved class has proba=0 + assert_array_equal(proba[:, i], np.zeros(len(y))) + # Check for all other classes proba>0 + assert np.all(proba[:, :i] > 0) + assert np.all(proba[:, i + 1:] > 0) + else: + # Check `proba` are all 1/n_classes + assert np.allclose(proba, 1 / proba.shape[0]) @ignore_warnings(category=FutureWarning) @@ -452,6 +539,6 @@ def test_calibration_attributes(clf, cv): assert_array_equal(calib_clf.classes_, clf.classes_) assert calib_clf.n_features_in_ == clf.n_features_in_ else: - classes = LabelBinarizer().fit(y).classes_ + classes = LabelEncoder().fit(y).classes_ assert_array_equal(calib_clf.classes_, classes) assert calib_clf.n_features_in_ == X.shape[1]
[ { "path": "doc/modules/calibration.rst", "old_path": "a/doc/modules/calibration.rst", "new_path": "b/doc/modules/calibration.rst", "metadata": "diff --git a/doc/modules/calibration.rst b/doc/modules/calibration.rst\nindex cb157a9d78c93..146601d70765e 100644\n--- a/doc/modules/calibration.rst\n+++ b/doc/modules/calibration.rst\n@@ -96,9 +96,9 @@ in [0, 1]. Denoting the output of the classifier for a given sample by :math:`f_\n the calibrator tries to predict :math:`p(y_i = 1 | f_i)`.\n \n The samples that are used to fit the calibrator should not be the same\n-samples used to fit the classifier, as this would\n-introduce bias. The classifier performance on its training data would be\n-better than for novel data. Using the classifier output from training data\n+samples used to fit the classifier, as this would introduce bias.\n+This is because performance of the classifier on its training data would be\n+better than for novel data. Using the classifier output of training data\n to fit the calibrator would thus result in a biased calibrator that maps to\n probabilities closer to 0 and 1 than it should.\n \n@@ -107,22 +107,39 @@ Usage\n \n The :class:`CalibratedClassifierCV` class is used to calibrate a classifier.\n \n-:class:`CalibratedClassifierCV` uses a cross-validation approach to fit both\n-the classifier and the regressor. The data is split into k\n-`(train_set, test_set)` couples (as determined by `cv`). The classifier\n-(`base_estimator`) is trained on the train set, and its predictions on the\n-test set are used to fit a regressor. This ensures that the data used to fit\n-the classifier is always disjoint from the data used to fit the calibrator.\n-After fitting, we end up with k\n-`(classifier, regressor)` couples where each regressor maps the output of\n-its corresponding classifier into [0, 1]. Each couple is exposed in the\n-`calibrated_classifiers_` attribute, where each entry is a calibrated\n+:class:`CalibratedClassifierCV` uses a cross-validation approach to ensure\n+unbiased data is always used to fit the calibrator. The data is split into k\n+`(train_set, test_set)` couples (as determined by `cv`). When `ensemble=True`\n+(default), the following procedure is repeated independently for each\n+cross-validation split: a clone of `base_estimator` is first trained on the\n+train subset. Then its predictions on the test subset are used to fit a\n+calibrator (either a sigmoid or isotonic regressor). This results in an\n+ensemble of k `(classifier, calibrator)` couples where each calibrator maps\n+the output of its corresponding classifier into [0, 1]. Each couple is exposed\n+in the `calibrated_classifiers_` attribute, where each entry is a calibrated\n classifier with a :term:`predict_proba` method that outputs calibrated\n probabilities. The output of :term:`predict_proba` for the main\n :class:`CalibratedClassifierCV` instance corresponds to the average of the\n-predicted probabilities of the `k` estimators in the\n-`calibrated_classifiers_` list. The output of :term:`predict` is the class\n-that has the highest probability.\n+predicted probabilities of the `k` estimators in the `calibrated_classifiers_`\n+list. The output of :term:`predict` is the class that has the highest\n+probability.\n+\n+When `ensemble=False`, cross-validation is used to obtain 'unbiased'\n+predictions for all the data, via\n+:func:`~sklearn.model_selection.cross_val_predict`.\n+These unbiased predictions are then used to train the calibrator. The attribute\n+`calibrated_classifiers_` consists of only one `(classifier, calibrator)`\n+couple where the classifier is the `base_estimator` trained on all the data.\n+In this case the output of :term:`predict_proba` for\n+:class:`CalibratedClassifierCV` is the predicted probabilities obtained\n+from the single `(classifier, calibrator)` couple.\n+\n+The main advantage of `ensemble=True` is to benefit from the traditional\n+ensembling effect (similar to :ref:`bagging`). The resulting ensemble should\n+both be well calibrated and slightly more accurate than with `ensemble=False`.\n+The main advantage of using `ensemble=False` is computational: it reduces the\n+overall fit time by training only a single base classifier and calibrator\n+pair, decreases the final model size and increases prediction speed.\n \n Alternatively an already fitted classifier can be calibrated by setting\n `cv=\"prefit\"`. In this case, the data is not split and all of it is used to\n" }, { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex 0e87b29828977..15907d614d629 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -58,6 +58,14 @@ Changelog\n sparse matrix or dataframe at the start. :pr:`17546` by\n :user:`Lucy Liu <lucyleeow>`.\n \n+- |Enhancement| Add `ensemble` parameter to\n+ :class:`calibration.CalibratedClassifierCV`, which enables implementation\n+ of calibration via an ensemble of calibrators (current method) or\n+ just one calibrator using all the data (similar to the built-in feature of\n+ :mod:`sklearn.svm` estimators with the `probabilities=True` parameter).\n+ :pr:`17856` by :user:`Lucy Liu <lucyleeow>` and\n+ :user:`Andrea Esuli <aesuli>`.\n+\n :mod:`sklearn.cluster`\n ......................\n \n" } ]
0.24
8d10285ffc2d64eb6f2107dc248bdbbc41ad1b50
[ "sklearn/tests/test_calibration.py::test_calibration_attributes[clf0-2]", "sklearn/tests/test_calibration.py::test_sigmoid_calibration", "sklearn/tests/test_calibration.py::test_calibration_accepts_ndarray[X0]", "sklearn/tests/test_calibration.py::test_calibration_attributes[clf1-prefit]", "sklearn/tests/test_calibration.py::test_calibration_curve", "sklearn/tests/test_calibration.py::test_calibration_pipeline", "sklearn/tests/test_calibration.py::test_calibration_prefit", "sklearn/tests/test_calibration.py::test_calibration_accepts_ndarray[X1]", "sklearn/tests/test_calibration.py::test_calibration_default_estimator" ]
[ "sklearn/tests/test_calibration.py::test_calibration[True-isotonic]", "sklearn/tests/test_calibration.py::test_parallel_execution[False-isotonic]", "sklearn/tests/test_calibration.py::test_calibration_ensemble_false[isotonic]", "sklearn/tests/test_calibration.py::test_calibration_nan_imputer[False]", "sklearn/tests/test_calibration.py::test_calibration_multiclass[1-True-isotonic]", "sklearn/tests/test_calibration.py::test_calibration_nan_imputer[True]", "sklearn/tests/test_calibration.py::test_parallel_execution[False-sigmoid]", "sklearn/tests/test_calibration.py::test_sample_weight[True-isotonic]", "sklearn/tests/test_calibration.py::test_calibration_multiclass[0-True-isotonic]", "sklearn/tests/test_calibration.py::test_calibration_multiclass[0-False-sigmoid]", "sklearn/tests/test_calibration.py::test_calibration_multiclass[1-False-sigmoid]", "sklearn/tests/test_calibration.py::test_calibration[False-isotonic]", "sklearn/tests/test_calibration.py::test_sample_weight[True-sigmoid]", "sklearn/tests/test_calibration.py::test_calibration_ensemble_false[sigmoid]", "sklearn/tests/test_calibration.py::test_parallel_execution[True-sigmoid]", "sklearn/tests/test_calibration.py::test_calibration_cv_splitter[True]", "sklearn/tests/test_calibration.py::test_calibration_less_classes[True]", "sklearn/tests/test_calibration.py::test_calibration_prob_sum[False]", "sklearn/tests/test_calibration.py::test_calibration_cv_splitter[False]", "sklearn/tests/test_calibration.py::test_calibration_bad_method[False]", "sklearn/tests/test_calibration.py::test_calibration_multiclass[0-True-sigmoid]", "sklearn/tests/test_calibration.py::test_calibration_regressor[False]", "sklearn/tests/test_calibration.py::test_calibration_multiclass[0-False-isotonic]", "sklearn/tests/test_calibration.py::test_calibration_multiclass[1-True-sigmoid]", "sklearn/tests/test_calibration.py::test_parallel_execution[True-isotonic]", "sklearn/tests/test_calibration.py::test_calibration_less_classes[False]", "sklearn/tests/test_calibration.py::test_calibration[True-sigmoid]", "sklearn/tests/test_calibration.py::test_calibration_multiclass[1-False-isotonic]", "sklearn/tests/test_calibration.py::test_calibration[False-sigmoid]", "sklearn/tests/test_calibration.py::test_calibration_prob_sum[True]", "sklearn/tests/test_calibration.py::test_calibration_bad_method[True]", "sklearn/tests/test_calibration.py::test_calibration_regressor[True]", "sklearn/tests/test_calibration.py::test_sample_weight[False-sigmoid]", "sklearn/tests/test_calibration.py::test_sample_weight[False-isotonic]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/modules/calibration.rst", "old_path": "a/doc/modules/calibration.rst", "new_path": "b/doc/modules/calibration.rst", "metadata": "diff --git a/doc/modules/calibration.rst b/doc/modules/calibration.rst\nindex cb157a9d78c93..146601d70765e 100644\n--- a/doc/modules/calibration.rst\n+++ b/doc/modules/calibration.rst\n@@ -96,9 +96,9 @@ in [0, 1]. Denoting the output of the classifier for a given sample by :math:`f_\n the calibrator tries to predict :math:`p(y_i = 1 | f_i)`.\n \n The samples that are used to fit the calibrator should not be the same\n-samples used to fit the classifier, as this would\n-introduce bias. The classifier performance on its training data would be\n-better than for novel data. Using the classifier output from training data\n+samples used to fit the classifier, as this would introduce bias.\n+This is because performance of the classifier on its training data would be\n+better than for novel data. Using the classifier output of training data\n to fit the calibrator would thus result in a biased calibrator that maps to\n probabilities closer to 0 and 1 than it should.\n \n@@ -107,22 +107,39 @@ Usage\n \n The :class:`CalibratedClassifierCV` class is used to calibrate a classifier.\n \n-:class:`CalibratedClassifierCV` uses a cross-validation approach to fit both\n-the classifier and the regressor. The data is split into k\n-`(train_set, test_set)` couples (as determined by `cv`). The classifier\n-(`base_estimator`) is trained on the train set, and its predictions on the\n-test set are used to fit a regressor. This ensures that the data used to fit\n-the classifier is always disjoint from the data used to fit the calibrator.\n-After fitting, we end up with k\n-`(classifier, regressor)` couples where each regressor maps the output of\n-its corresponding classifier into [0, 1]. Each couple is exposed in the\n-`calibrated_classifiers_` attribute, where each entry is a calibrated\n+:class:`CalibratedClassifierCV` uses a cross-validation approach to ensure\n+unbiased data is always used to fit the calibrator. The data is split into k\n+`(train_set, test_set)` couples (as determined by `cv`). When `ensemble=True`\n+(default), the following procedure is repeated independently for each\n+cross-validation split: a clone of `base_estimator` is first trained on the\n+train subset. Then its predictions on the test subset are used to fit a\n+calibrator (either a sigmoid or isotonic regressor). This results in an\n+ensemble of k `(classifier, calibrator)` couples where each calibrator maps\n+the output of its corresponding classifier into [0, 1]. Each couple is exposed\n+in the `calibrated_classifiers_` attribute, where each entry is a calibrated\n classifier with a :term:`predict_proba` method that outputs calibrated\n probabilities. The output of :term:`predict_proba` for the main\n :class:`CalibratedClassifierCV` instance corresponds to the average of the\n-predicted probabilities of the `k` estimators in the\n-`calibrated_classifiers_` list. The output of :term:`predict` is the class\n-that has the highest probability.\n+predicted probabilities of the `k` estimators in the `calibrated_classifiers_`\n+list. The output of :term:`predict` is the class that has the highest\n+probability.\n+\n+When `ensemble=False`, cross-validation is used to obtain 'unbiased'\n+predictions for all the data, via\n+:func:`~sklearn.model_selection.cross_val_predict`.\n+These unbiased predictions are then used to train the calibrator. The attribute\n+`calibrated_classifiers_` consists of only one `(classifier, calibrator)`\n+couple where the classifier is the `base_estimator` trained on all the data.\n+In this case the output of :term:`predict_proba` for\n+:class:`CalibratedClassifierCV` is the predicted probabilities obtained\n+from the single `(classifier, calibrator)` couple.\n+\n+The main advantage of `ensemble=True` is to benefit from the traditional\n+ensembling effect (similar to :ref:`bagging`). The resulting ensemble should\n+both be well calibrated and slightly more accurate than with `ensemble=False`.\n+The main advantage of using `ensemble=False` is computational: it reduces the\n+overall fit time by training only a single base classifier and calibrator\n+pair, decreases the final model size and increases prediction speed.\n \n Alternatively an already fitted classifier can be calibrated by setting\n `cv=\"prefit\"`. In this case, the data is not split and all of it is used to\n" }, { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex 0e87b29828977..15907d614d629 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -58,6 +58,14 @@ Changelog\n sparse matrix or dataframe at the start. :pr:`<PRID>` by\n :user:`<NAME>`.\n \n+- |Enhancement| Add `ensemble` parameter to\n+ :class:`calibration.CalibratedClassifierCV`, which enables implementation\n+ of calibration via an ensemble of calibrators (current method) or\n+ just one calibrator using all the data (similar to the built-in feature of\n+ :mod:`sklearn.svm` estimators with the `probabilities=True` parameter).\n+ :pr:`<PRID>` by :user:`<NAME>` and\n+ :user:`<NAME>`.\n+\n :mod:`sklearn.cluster`\n ......................\n \n" } ]
diff --git a/doc/modules/calibration.rst b/doc/modules/calibration.rst index cb157a9d78c93..146601d70765e 100644 --- a/doc/modules/calibration.rst +++ b/doc/modules/calibration.rst @@ -96,9 +96,9 @@ in [0, 1]. Denoting the output of the classifier for a given sample by :math:`f_ the calibrator tries to predict :math:`p(y_i = 1 | f_i)`. The samples that are used to fit the calibrator should not be the same -samples used to fit the classifier, as this would -introduce bias. The classifier performance on its training data would be -better than for novel data. Using the classifier output from training data +samples used to fit the classifier, as this would introduce bias. +This is because performance of the classifier on its training data would be +better than for novel data. Using the classifier output of training data to fit the calibrator would thus result in a biased calibrator that maps to probabilities closer to 0 and 1 than it should. @@ -107,22 +107,39 @@ Usage The :class:`CalibratedClassifierCV` class is used to calibrate a classifier. -:class:`CalibratedClassifierCV` uses a cross-validation approach to fit both -the classifier and the regressor. The data is split into k -`(train_set, test_set)` couples (as determined by `cv`). The classifier -(`base_estimator`) is trained on the train set, and its predictions on the -test set are used to fit a regressor. This ensures that the data used to fit -the classifier is always disjoint from the data used to fit the calibrator. -After fitting, we end up with k -`(classifier, regressor)` couples where each regressor maps the output of -its corresponding classifier into [0, 1]. Each couple is exposed in the -`calibrated_classifiers_` attribute, where each entry is a calibrated +:class:`CalibratedClassifierCV` uses a cross-validation approach to ensure +unbiased data is always used to fit the calibrator. The data is split into k +`(train_set, test_set)` couples (as determined by `cv`). When `ensemble=True` +(default), the following procedure is repeated independently for each +cross-validation split: a clone of `base_estimator` is first trained on the +train subset. Then its predictions on the test subset are used to fit a +calibrator (either a sigmoid or isotonic regressor). This results in an +ensemble of k `(classifier, calibrator)` couples where each calibrator maps +the output of its corresponding classifier into [0, 1]. Each couple is exposed +in the `calibrated_classifiers_` attribute, where each entry is a calibrated classifier with a :term:`predict_proba` method that outputs calibrated probabilities. The output of :term:`predict_proba` for the main :class:`CalibratedClassifierCV` instance corresponds to the average of the -predicted probabilities of the `k` estimators in the -`calibrated_classifiers_` list. The output of :term:`predict` is the class -that has the highest probability. +predicted probabilities of the `k` estimators in the `calibrated_classifiers_` +list. The output of :term:`predict` is the class that has the highest +probability. + +When `ensemble=False`, cross-validation is used to obtain 'unbiased' +predictions for all the data, via +:func:`~sklearn.model_selection.cross_val_predict`. +These unbiased predictions are then used to train the calibrator. The attribute +`calibrated_classifiers_` consists of only one `(classifier, calibrator)` +couple where the classifier is the `base_estimator` trained on all the data. +In this case the output of :term:`predict_proba` for +:class:`CalibratedClassifierCV` is the predicted probabilities obtained +from the single `(classifier, calibrator)` couple. + +The main advantage of `ensemble=True` is to benefit from the traditional +ensembling effect (similar to :ref:`bagging`). The resulting ensemble should +both be well calibrated and slightly more accurate than with `ensemble=False`. +The main advantage of using `ensemble=False` is computational: it reduces the +overall fit time by training only a single base classifier and calibrator +pair, decreases the final model size and increases prediction speed. Alternatively an already fitted classifier can be calibrated by setting `cv="prefit"`. In this case, the data is not split and all of it is used to diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index 0e87b29828977..15907d614d629 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -58,6 +58,14 @@ Changelog sparse matrix or dataframe at the start. :pr:`<PRID>` by :user:`<NAME>`. +- |Enhancement| Add `ensemble` parameter to + :class:`calibration.CalibratedClassifierCV`, which enables implementation + of calibration via an ensemble of calibrators (current method) or + just one calibrator using all the data (similar to the built-in feature of + :mod:`sklearn.svm` estimators with the `probabilities=True` parameter). + :pr:`<PRID>` by :user:`<NAME>` and + :user:`<NAME>`. + :mod:`sklearn.cluster` ......................
scikit-learn/scikit-learn
scikit-learn__scikit-learn-17984
https://github.com/scikit-learn/scikit-learn/pull/17984
diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index 03ba05d08e2c8..c33f896071d15 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -70,9 +70,20 @@ Changelog `init_size_`, are deprecated and will be removed in 0.26. :pr:`17864` by :user:`Jérémie du Boisberranger <jeremiedbb>`. +- |Fix| :class:`cluster.AgglomerativeClustering` has a new parameter + `compute_distances`. When set to `True`, distances between clusters are + computed and stored in the `distances_` attribute even when the parameter + `distance_threshold` is not used. This new parameter is useful to produce + dendrogram visualizations, but introduces a computational and memory + overhead. :pr:`17984` by :user:`Michael Riedmann <mriedmann>`, + :user:`Emilie Delattre <EmilieDel>`, and + :user:`Francesco Casalegno <FrancescoCasalegno>`. + - |Fix| Fixed a bug in :class:`cluster.AffinityPropagation`, that gives incorrect clusters when the array dtype is float32. - :pr:`17995` by :user:`Thomaz Santana <Wikilicious>` and :user:`Amanda Dsouza <amy12xx>`. + :pr:`17995` by :user:`Thomaz Santana <Wikilicious>` and + :user:`Amanda Dsouza <amy12xx>`. + :mod:`sklearn.covariance` ......................... diff --git a/sklearn/cluster/_agglomerative.py b/sklearn/cluster/_agglomerative.py index dfd2ce286c213..fd9241e0b7267 100644 --- a/sklearn/cluster/_agglomerative.py +++ b/sklearn/cluster/_agglomerative.py @@ -747,6 +747,13 @@ class AgglomerativeClustering(ClusterMixin, BaseEstimator): .. versionadded:: 0.21 + compute_distances : bool, default=False + Computes distances between clusters even if `distance_threshold` is not + used. This can be used to make dendrogram visualization, but introduces + a computational and memory overhead. + + .. versionadded:: 0.24 + Attributes ---------- n_clusters_ : int @@ -776,7 +783,8 @@ class AgglomerativeClustering(ClusterMixin, BaseEstimator): distances_ : array-like of shape (n_nodes-1,) Distances between nodes in the corresponding place in `children_`. - Only computed if distance_threshold is not None. + Only computed if `distance_threshold` is used or `compute_distances` + is set to `True`. Examples -------- @@ -795,7 +803,8 @@ class AgglomerativeClustering(ClusterMixin, BaseEstimator): def __init__(self, n_clusters=2, *, affinity="euclidean", memory=None, connectivity=None, compute_full_tree='auto', - linkage='ward', distance_threshold=None): + linkage='ward', distance_threshold=None, + compute_distances=False): self.n_clusters = n_clusters self.distance_threshold = distance_threshold self.memory = memory @@ -803,6 +812,7 @@ def __init__(self, n_clusters=2, *, affinity="euclidean", self.compute_full_tree = compute_full_tree self.linkage = linkage self.affinity = affinity + self.compute_distances = compute_distances def fit(self, X, y=None): """Fit the hierarchical clustering from features, or distance matrix. @@ -879,7 +889,10 @@ def fit(self, X, y=None): distance_threshold = self.distance_threshold - return_distance = distance_threshold is not None + return_distance = ( + (distance_threshold is not None) or self.compute_distances + ) + out = memory.cache(tree_builder)(X, connectivity=connectivity, n_clusters=n_clusters, return_distance=return_distance, @@ -891,9 +904,11 @@ def fit(self, X, y=None): if return_distance: self.distances_ = out[-1] + + if self.distance_threshold is not None: # distance_threshold is used self.n_clusters_ = np.count_nonzero( self.distances_ >= distance_threshold) + 1 - else: + else: # n_clusters is used self.n_clusters_ = self.n_clusters # Cut the tree @@ -999,6 +1014,13 @@ class FeatureAgglomeration(AgglomerativeClustering, AgglomerationTransform): .. versionadded:: 0.21 + compute_distances : bool, default=False + Computes distances between clusters even if `distance_threshold` is not + used. This can be used to make dendrogram visualization, but introduces + a computational and memory overhead. + + .. versionadded:: 0.24 + Attributes ---------- n_clusters_ : int @@ -1028,7 +1050,8 @@ class FeatureAgglomeration(AgglomerativeClustering, AgglomerationTransform): distances_ : array-like of shape (n_nodes-1,) Distances between nodes in the corresponding place in `children_`. - Only computed if distance_threshold is not None. + Only computed if `distance_threshold` is used or `compute_distances` + is set to `True`. Examples -------- @@ -1049,11 +1072,12 @@ def __init__(self, n_clusters=2, *, affinity="euclidean", memory=None, connectivity=None, compute_full_tree='auto', linkage='ward', pooling_func=np.mean, - distance_threshold=None): + distance_threshold=None, compute_distances=False): super().__init__( n_clusters=n_clusters, memory=memory, connectivity=connectivity, compute_full_tree=compute_full_tree, linkage=linkage, - affinity=affinity, distance_threshold=distance_threshold) + affinity=affinity, distance_threshold=distance_threshold, + compute_distances=compute_distances) self.pooling_func = pooling_func def fit(self, X, y=None, **params):
diff --git a/sklearn/cluster/tests/test_hierarchical.py b/sklearn/cluster/tests/test_hierarchical.py index 9e7796c219a83..26f30dcd87847 100644 --- a/sklearn/cluster/tests/test_hierarchical.py +++ b/sklearn/cluster/tests/test_hierarchical.py @@ -143,6 +143,37 @@ def test_zero_cosine_linkage_tree(): assert_raise_message(ValueError, msg, linkage_tree, X, affinity='cosine') [email protected]('n_clusters, distance_threshold', + [(None, 0.5), (10, None)]) [email protected]('compute_distances', [True, False]) [email protected]('linkage', ["ward", "complete", "average", "single"]) +def test_agglomerative_clustering_distances(n_clusters, + compute_distances, + distance_threshold, + linkage): + # Check that when `compute_distances` is True or `distance_threshold` is + # given, the fitted model has an attribute `distances_`. + rng = np.random.RandomState(0) + mask = np.ones([10, 10], dtype=bool) + n_samples = 100 + X = rng.randn(n_samples, 50) + connectivity = grid_to_graph(*mask.shape) + + clustering = AgglomerativeClustering(n_clusters=n_clusters, + connectivity=connectivity, + linkage=linkage, + distance_threshold=distance_threshold, + compute_distances=compute_distances) + clustering.fit(X) + if compute_distances or (distance_threshold is not None): + assert hasattr(clustering, 'distances_') + n_children = clustering.children_.shape[0] + n_nodes = n_children + 1 + assert clustering.distances_.shape == (n_nodes-1, ) + else: + assert not hasattr(clustering, 'distances_') + + def test_agglomerative_clustering(): # Check that we obtain the correct number of clusters with # agglomerative clustering.
[ { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex 03ba05d08e2c8..c33f896071d15 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -70,9 +70,20 @@ Changelog\n `init_size_`, are deprecated and will be removed in 0.26. :pr:`17864` by\n :user:`Jérémie du Boisberranger <jeremiedbb>`.\n \n+- |Fix| :class:`cluster.AgglomerativeClustering` has a new parameter\n+ `compute_distances`. When set to `True`, distances between clusters are\n+ computed and stored in the `distances_` attribute even when the parameter\n+ `distance_threshold` is not used. This new parameter is useful to produce\n+ dendrogram visualizations, but introduces a computational and memory\n+ overhead. :pr:`17984` by :user:`Michael Riedmann <mriedmann>`,\n+ :user:`Emilie Delattre <EmilieDel>`, and\n+ :user:`Francesco Casalegno <FrancescoCasalegno>`.\n+\n - |Fix| Fixed a bug in :class:`cluster.AffinityPropagation`, that\n gives incorrect clusters when the array dtype is float32.\n- :pr:`17995` by :user:`Thomaz Santana <Wikilicious>` and :user:`Amanda Dsouza <amy12xx>`.\n+ :pr:`17995` by :user:`Thomaz Santana <Wikilicious>` and\n+ :user:`Amanda Dsouza <amy12xx>`.\n+\n \n :mod:`sklearn.covariance`\n .........................\n" } ]
0.24
3cb3d4109e7acc497ad1e306013547e5f72ee5f4
[ "sklearn/cluster/tests/test_hierarchical.py::test_vector_scikit_single_vs_scipy_single[1]", "sklearn/cluster/tests/test_hierarchical.py::test_agglomerative_clustering_with_distance_threshold_edge_case[1.5-y_true2-average]", "sklearn/cluster/tests/test_hierarchical.py::test_invalid_shape_precomputed_dist_matrix", "sklearn/cluster/tests/test_hierarchical.py::test_agglomerative_clustering_with_distance_threshold_edge_case[0.5-y_true0-ward]", "sklearn/cluster/tests/test_hierarchical.py::test_single_linkage_clustering", "sklearn/cluster/tests/test_hierarchical.py::test_agglomerative_clustering_with_distance_threshold_edge_case[1.5-y_true2-complete]", "sklearn/cluster/tests/test_hierarchical.py::test_zero_cosine_linkage_tree", "sklearn/cluster/tests/test_hierarchical.py::test_vector_scikit_single_vs_scipy_single[2]", "sklearn/cluster/tests/test_hierarchical.py::test_agglomerative_clustering_with_distance_threshold[ward]", "sklearn/cluster/tests/test_hierarchical.py::test_agglomerative_clustering_with_distance_threshold_edge_case[0.5-y_true0-average]", "sklearn/cluster/tests/test_hierarchical.py::test_compute_full_tree", "sklearn/cluster/tests/test_hierarchical.py::test_connectivity_fixing_non_lil", "sklearn/cluster/tests/test_hierarchical.py::test_n_components", "sklearn/cluster/tests/test_hierarchical.py::test_cluster_distances_with_distance_threshold", "sklearn/cluster/tests/test_hierarchical.py::test_unstructured_linkage_tree", "sklearn/cluster/tests/test_hierarchical.py::test_ward_linkage_tree_return_distance", "sklearn/cluster/tests/test_hierarchical.py::test_agglomerative_clustering", "sklearn/cluster/tests/test_hierarchical.py::test_structured_linkage_tree", "sklearn/cluster/tests/test_hierarchical.py::test_agglomerative_clustering_with_distance_threshold_edge_case[1.0-y_true1-average]", "sklearn/cluster/tests/test_hierarchical.py::test_linkage_misc", "sklearn/cluster/tests/test_hierarchical.py::test_agglomerative_clustering_with_distance_threshold[complete]", "sklearn/cluster/tests/test_hierarchical.py::test_sparse_scikit_vs_scipy", "sklearn/cluster/tests/test_hierarchical.py::test_ward_agglomeration", "sklearn/cluster/tests/test_hierarchical.py::test_connectivity_propagation", "sklearn/cluster/tests/test_hierarchical.py::test_agg_n_clusters", "sklearn/cluster/tests/test_hierarchical.py::test_ward_tree_children_order", "sklearn/cluster/tests/test_hierarchical.py::test_vector_scikit_single_vs_scipy_single[0]", "sklearn/cluster/tests/test_hierarchical.py::test_agglomerative_clustering_with_distance_threshold_edge_case[1.5-y_true2-ward]", "sklearn/cluster/tests/test_hierarchical.py::test_agglomerative_clustering_with_distance_threshold[average]", "sklearn/cluster/tests/test_hierarchical.py::test_int_float_dict", "sklearn/cluster/tests/test_hierarchical.py::test_identical_points", "sklearn/cluster/tests/test_hierarchical.py::test_agglomerative_clustering_with_distance_threshold_edge_case[0.5-y_true0-complete]", "sklearn/cluster/tests/test_hierarchical.py::test_agglomerative_clustering_with_distance_threshold_edge_case[1.0-y_true1-ward]", "sklearn/cluster/tests/test_hierarchical.py::test_affinity_passed_to_fix_connectivity", "sklearn/cluster/tests/test_hierarchical.py::test_agglomerative_clustering_with_distance_threshold_edge_case[1.0-y_true1-complete]", "sklearn/cluster/tests/test_hierarchical.py::test_dist_threshold_invalid_parameters", "sklearn/cluster/tests/test_hierarchical.py::test_small_distance_threshold", "sklearn/cluster/tests/test_hierarchical.py::test_connectivity_callable", "sklearn/cluster/tests/test_hierarchical.py::test_agglomerative_clustering_wrong_arg_memory", "sklearn/cluster/tests/test_hierarchical.py::test_vector_scikit_single_vs_scipy_single[4]", "sklearn/cluster/tests/test_hierarchical.py::test_height_linkage_tree", "sklearn/cluster/tests/test_hierarchical.py::test_connectivity_ignores_diagonal", "sklearn/cluster/tests/test_hierarchical.py::test_vector_scikit_single_vs_scipy_single[3]" ]
[ "sklearn/cluster/tests/test_hierarchical.py::test_agglomerative_clustering_distances[complete-False-10-None]", "sklearn/cluster/tests/test_hierarchical.py::test_agglomerative_clustering_distances[average-False-10-None]", "sklearn/cluster/tests/test_hierarchical.py::test_agglomerative_clustering_distances[single-False-10-None]", "sklearn/cluster/tests/test_hierarchical.py::test_agglomerative_clustering_distances[complete-False-None-0.5]", "sklearn/cluster/tests/test_hierarchical.py::test_agglomerative_clustering_distances[ward-True-10-None]", "sklearn/cluster/tests/test_hierarchical.py::test_agglomerative_clustering_distances[ward-True-None-0.5]", "sklearn/cluster/tests/test_hierarchical.py::test_agglomerative_clustering_distances[single-False-None-0.5]", "sklearn/cluster/tests/test_hierarchical.py::test_agglomerative_clustering_distances[ward-False-None-0.5]", "sklearn/cluster/tests/test_hierarchical.py::test_agglomerative_clustering_distances[complete-True-10-None]", "sklearn/cluster/tests/test_hierarchical.py::test_agglomerative_clustering_distances[complete-True-None-0.5]", "sklearn/cluster/tests/test_hierarchical.py::test_agglomerative_clustering_distances[average-True-None-0.5]", "sklearn/cluster/tests/test_hierarchical.py::test_agglomerative_clustering_distances[single-True-None-0.5]", "sklearn/cluster/tests/test_hierarchical.py::test_agglomerative_clustering_distances[ward-False-10-None]", "sklearn/cluster/tests/test_hierarchical.py::test_agglomerative_clustering_distances[average-False-None-0.5]", "sklearn/cluster/tests/test_hierarchical.py::test_agglomerative_clustering_distances[average-True-10-None]", "sklearn/cluster/tests/test_hierarchical.py::test_agglomerative_clustering_distances[single-True-10-None]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex 03ba05d08e2c8..c33f896071d15 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -70,9 +70,20 @@ Changelog\n `init_size_`, are deprecated and will be removed in 0.26. :pr:`<PRID>` by\n :user:`<NAME>`.\n \n+- |Fix| :class:`cluster.AgglomerativeClustering` has a new parameter\n+ `compute_distances`. When set to `True`, distances between clusters are\n+ computed and stored in the `distances_` attribute even when the parameter\n+ `distance_threshold` is not used. This new parameter is useful to produce\n+ dendrogram visualizations, but introduces a computational and memory\n+ overhead. :pr:`<PRID>` by :user:`<NAME>`,\n+ :user:`<NAME>`, and\n+ :user:`<NAME>`.\n+\n - |Fix| Fixed a bug in :class:`cluster.AffinityPropagation`, that\n gives incorrect clusters when the array dtype is float32.\n- :pr:`<PRID>` by :user:`<NAME>` and :user:`<NAME>`.\n+ :pr:`<PRID>` by :user:`<NAME>` and\n+ :user:`<NAME>`.\n+\n \n :mod:`sklearn.covariance`\n .........................\n" } ]
diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index 03ba05d08e2c8..c33f896071d15 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -70,9 +70,20 @@ Changelog `init_size_`, are deprecated and will be removed in 0.26. :pr:`<PRID>` by :user:`<NAME>`. +- |Fix| :class:`cluster.AgglomerativeClustering` has a new parameter + `compute_distances`. When set to `True`, distances between clusters are + computed and stored in the `distances_` attribute even when the parameter + `distance_threshold` is not used. This new parameter is useful to produce + dendrogram visualizations, but introduces a computational and memory + overhead. :pr:`<PRID>` by :user:`<NAME>`, + :user:`<NAME>`, and + :user:`<NAME>`. + - |Fix| Fixed a bug in :class:`cluster.AffinityPropagation`, that gives incorrect clusters when the array dtype is float32. - :pr:`<PRID>` by :user:`<NAME>` and :user:`<NAME>`. + :pr:`<PRID>` by :user:`<NAME>` and + :user:`<NAME>`. + :mod:`sklearn.covariance` .........................
scikit-learn/scikit-learn
scikit-learn__scikit-learn-18052
https://github.com/scikit-learn/scikit-learn/pull/18052
diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index 8843a7bc1ca19..2682902a20983 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -72,6 +72,11 @@ Changelog :user:`Emilie Delattre <EmilieDel>`, and :user:`Francesco Casalegno <FrancescoCasalegno>`. +- |Enhancement| :class:`cluster.SpectralClustering` and + :func:`cluster.spectral_clustering` have a new keyword argument `verbose`. + When set to `True`, additional messages will be displayed which can aid with + debugging. :pr:`18052` by :user:`Sean O. Stalley <sstalley>`. + - |API| :class:`cluster.MiniBatchKMeans` attributes, `counts_` and `init_size_`, are deprecated and will be removed in 0.26. :pr:`17864` by :user:`Jérémie du Boisberranger <jeremiedbb>`. diff --git a/sklearn/cluster/_spectral.py b/sklearn/cluster/_spectral.py index e40e6e694969d..847714f1cbbd4 100644 --- a/sklearn/cluster/_spectral.py +++ b/sklearn/cluster/_spectral.py @@ -160,7 +160,8 @@ def discretize(vectors, *, copy=True, max_svd_restarts=30, n_iter_max=20, @_deprecate_positional_args def spectral_clustering(affinity, *, n_clusters=8, n_components=None, eigen_solver=None, random_state=None, n_init=10, - eigen_tol=0.0, assign_labels='kmeans'): + eigen_tol=0.0, assign_labels='kmeans', + verbose=False): """Apply clustering to a projection of the normalized Laplacian. In practice Spectral Clustering is very useful when the structure of @@ -222,6 +223,11 @@ def spectral_clustering(affinity, *, n_clusters=8, n_components=None, the 'Multiclass spectral clustering' paper referenced below for more details on the discretization approach. + verbose : bool, default=False + Verbosity mode. + + .. versionadded:: 0.24 + Returns ------- labels : array of integers, shape: n_samples @@ -265,10 +271,12 @@ def spectral_clustering(affinity, *, n_clusters=8, n_components=None, eigen_solver=eigen_solver, random_state=random_state, eigen_tol=eigen_tol, drop_first=False) + if verbose: + print(f'Computing label assignment using {assign_labels}') if assign_labels == 'kmeans': _, labels, _ = k_means(maps, n_clusters, random_state=random_state, - n_init=n_init) + n_init=n_init, verbose=verbose) else: labels = discretize(maps, random_state=random_state) @@ -381,6 +389,11 @@ class SpectralClustering(ClusterMixin, BaseEstimator): ``-1`` means using all processors. See :term:`Glossary <n_jobs>` for more details. + verbose : bool, default=False + Verbosity mode. + + .. versionadded:: 0.24 + Attributes ---------- affinity_matrix_ : array-like of shape (n_samples, n_samples) @@ -443,7 +456,8 @@ class SpectralClustering(ClusterMixin, BaseEstimator): def __init__(self, n_clusters=8, *, eigen_solver=None, n_components=None, random_state=None, n_init=10, gamma=1., affinity='rbf', n_neighbors=10, eigen_tol=0.0, assign_labels='kmeans', - degree=3, coef0=1, kernel_params=None, n_jobs=None): + degree=3, coef0=1, kernel_params=None, n_jobs=None, + verbose=False): self.n_clusters = n_clusters self.eigen_solver = eigen_solver self.n_components = n_components @@ -458,6 +472,7 @@ def __init__(self, n_clusters=8, *, eigen_solver=None, n_components=None, self.coef0 = coef0 self.kernel_params = kernel_params self.n_jobs = n_jobs + self.verbose = verbose def fit(self, X, y=None): """Perform spectral clustering from features, or affinity matrix. @@ -523,7 +538,8 @@ def fit(self, X, y=None): random_state=random_state, n_init=self.n_init, eigen_tol=self.eigen_tol, - assign_labels=self.assign_labels) + assign_labels=self.assign_labels, + verbose=self.verbose) return self def fit_predict(self, X, y=None):
diff --git a/sklearn/cluster/tests/test_spectral.py b/sklearn/cluster/tests/test_spectral.py index 1df7dcf103532..42e285d70a66f 100644 --- a/sklearn/cluster/tests/test_spectral.py +++ b/sklearn/cluster/tests/test_spectral.py @@ -1,4 +1,5 @@ """Testing for Spectral Clustering methods""" +import re import numpy as np from scipy import sparse @@ -248,3 +249,20 @@ def test_n_components(): labels_diff_ncomp = SpectralClustering(n_components=2, random_state=0).fit(X).labels_ assert not np.array_equal(labels, labels_diff_ncomp) + + [email protected]('assign_labels', ('kmeans', 'discretize')) +def test_verbose(assign_labels, capsys): + # Check verbose mode of KMeans for better coverage. + X, y = make_blobs(n_samples=20, random_state=0, + centers=[[1, 1], [-1, -1]], cluster_std=0.01) + + SpectralClustering(n_clusters=2, random_state=42, verbose=1).fit(X) + + captured = capsys.readouterr() + + assert re.search(r"Computing label assignment using", captured.out) + + if assign_labels == "kmeans": + assert re.search(r"Initialization complete", captured.out) + assert re.search(r"Iteration [0-9]+, inertia", captured.out)
[ { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex 8843a7bc1ca19..2682902a20983 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -72,6 +72,11 @@ Changelog\n :user:`Emilie Delattre <EmilieDel>`, and\n :user:`Francesco Casalegno <FrancescoCasalegno>`.\n \n+- |Enhancement| :class:`cluster.SpectralClustering` and\n+ :func:`cluster.spectral_clustering` have a new keyword argument `verbose`.\n+ When set to `True`, additional messages will be displayed which can aid with\n+ debugging. :pr:`18052` by :user:`Sean O. Stalley <sstalley>`.\n+\n - |API| :class:`cluster.MiniBatchKMeans` attributes, `counts_` and\n `init_size_`, are deprecated and will be removed in 0.26. :pr:`17864` by\n :user:`Jérémie du Boisberranger <jeremiedbb>`.\n" } ]
0.24
61ce18fcb748ec76082ec1a83dc026d64f842a51
[ "sklearn/cluster/tests/test_spectral.py::test_n_components", "sklearn/cluster/tests/test_spectral.py::test_discretize[100]", "sklearn/cluster/tests/test_spectral.py::test_discretize[150]", "sklearn/cluster/tests/test_spectral.py::test_spectral_clustering_with_arpack_amg_solvers", "sklearn/cluster/tests/test_spectral.py::test_spectral_clustering[kmeans-arpack]", "sklearn/cluster/tests/test_spectral.py::test_spectral_clustering[kmeans-lobpcg]", "sklearn/cluster/tests/test_spectral.py::test_spectral_clustering[discretize-lobpcg]", "sklearn/cluster/tests/test_spectral.py::test_spectral_clustering_sparse", "sklearn/cluster/tests/test_spectral.py::test_discretize[500]", "sklearn/cluster/tests/test_spectral.py::test_discretize[50]", "sklearn/cluster/tests/test_spectral.py::test_spectral_clustering[discretize-arpack]", "sklearn/cluster/tests/test_spectral.py::test_spectral_unknown_assign_labels", "sklearn/cluster/tests/test_spectral.py::test_spectral_unknown_mode", "sklearn/cluster/tests/test_spectral.py::test_precomputed_nearest_neighbors_filtering", "sklearn/cluster/tests/test_spectral.py::test_affinities" ]
[ "sklearn/cluster/tests/test_spectral.py::test_verbose[discretize]", "sklearn/cluster/tests/test_spectral.py::test_verbose[kmeans]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex 8843a7bc1ca19..2682902a20983 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -72,6 +72,11 @@ Changelog\n :user:`<NAME>`, and\n :user:`<NAME>`.\n \n+- |Enhancement| :class:`cluster.SpectralClustering` and\n+ :func:`cluster.spectral_clustering` have a new keyword argument `verbose`.\n+ When set to `True`, additional messages will be displayed which can aid with\n+ debugging. :pr:`<PRID>` by :user:`<NAME>`.\n+\n - |API| :class:`cluster.MiniBatchKMeans` attributes, `counts_` and\n `init_size_`, are deprecated and will be removed in 0.26. :pr:`<PRID>` by\n :user:`<NAME>`.\n" } ]
diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index 8843a7bc1ca19..2682902a20983 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -72,6 +72,11 @@ Changelog :user:`<NAME>`, and :user:`<NAME>`. +- |Enhancement| :class:`cluster.SpectralClustering` and + :func:`cluster.spectral_clustering` have a new keyword argument `verbose`. + When set to `True`, additional messages will be displayed which can aid with + debugging. :pr:`<PRID>` by :user:`<NAME>`. + - |API| :class:`cluster.MiniBatchKMeans` attributes, `counts_` and `init_size_`, are deprecated and will be removed in 0.26. :pr:`<PRID>` by :user:`<NAME>`.
scikit-learn/scikit-learn
scikit-learn__scikit-learn-17396
https://github.com/scikit-learn/scikit-learn/pull/17396
diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index 927812d9fd6dd..ea27d7579ae4d 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -44,6 +44,14 @@ Changelog :pr:`123456` by :user:`Joe Bloggs <joeongithub>`. where 123456 is the *pull request* number, not the issue number. +:mod:`sklearn.datasets` +....................... + +- |Enhancement| :func:`datasets.fetch_openml` now allows argument `as_frame` + to be 'auto', which tries to convert returned data to pandas DataFrame + unless data is sparse. + :pr:`17396` by :user:`Jiaxiang <fujiaxiang>`. + :mod:`sklearn.decomposition` ............................ diff --git a/sklearn/datasets/_openml.py b/sklearn/datasets/_openml.py index 112cd9c0e525e..c1f9eb94c78d3 100644 --- a/sklearn/datasets/_openml.py +++ b/sklearn/datasets/_openml.py @@ -667,13 +667,16 @@ def fetch_openml(name=None, *, version='active', data_id=None, data_home=None, If True, returns ``(data, target)`` instead of a Bunch object. See below for more information about the `data` and `target` objects. - as_frame : boolean, default=False + as_frame : boolean or 'auto', default=False If True, the data is a pandas DataFrame including columns with appropriate dtypes (numeric, string or categorical). The target is a pandas DataFrame or Series depending on the number of target_columns. The Bunch will contain a ``frame`` attribute with the target and the data. If ``return_X_y`` is True, then ``(data, target)`` will be pandas DataFrames or Series as describe above. + If as_frame is 'auto', the data and target will be converted to + DataFrame or Series as if as_frame is set to True, unless the dataset + is stored in sparse format. Returns ------- @@ -768,6 +771,9 @@ def fetch_openml(name=None, *, version='active', data_id=None, data_home=None, if data_description['format'].lower() == 'sparse_arff': return_sparse = True + if as_frame == 'auto': + as_frame = not return_sparse + if as_frame and return_sparse: raise ValueError('Cannot return dataframe with sparse data')
diff --git a/sklearn/datasets/tests/test_openml.py b/sklearn/datasets/tests/test_openml.py index 44fe392e42e74..950c208444b7d 100644 --- a/sklearn/datasets/tests/test_openml.py +++ b/sklearn/datasets/tests/test_openml.py @@ -489,6 +489,20 @@ def test_fetch_openml_australian_pandas_error_sparse(monkeypatch): fetch_openml(data_id=data_id, as_frame=True, cache=False) +def test_fetch_openml_as_frame_auto(monkeypatch): + pd = pytest.importorskip('pandas') + + data_id = 61 # iris dataset version 1 + _monkey_patch_webbased_functions(monkeypatch, data_id, True) + data = fetch_openml(data_id=data_id, as_frame='auto') + assert isinstance(data.data, pd.DataFrame) + + data_id = 292 # Australian dataset version 1 + _monkey_patch_webbased_functions(monkeypatch, data_id, True) + data = fetch_openml(data_id=data_id, as_frame='auto') + assert isinstance(data.data, scipy.sparse.csr_matrix) + + def test_convert_arff_data_dataframe_warning_low_memory_pandas(monkeypatch): pytest.importorskip('pandas')
[ { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex 927812d9fd6dd..ea27d7579ae4d 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -44,6 +44,14 @@ Changelog\n :pr:`123456` by :user:`Joe Bloggs <joeongithub>`.\n where 123456 is the *pull request* number, not the issue number.\n \n+:mod:`sklearn.datasets`\n+.......................\n+\n+- |Enhancement| :func:`datasets.fetch_openml` now allows argument `as_frame`\n+ to be 'auto', which tries to convert returned data to pandas DataFrame\n+ unless data is sparse.\n+ :pr:`17396` by :user:`Jiaxiang <fujiaxiang>`.\n+\n :mod:`sklearn.decomposition`\n ............................\n \n" } ]
0.24
3fb9e758a57455fc16847cc8d9452147f25d43a0
[ "sklearn/datasets/tests/test_openml.py::test_fetch_openml_cpu[False]", "sklearn/datasets/tests/test_openml.py::test_open_openml_url_unlinks_local_path[False-True]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_with_ignored_feature[False]", "sklearn/datasets/tests/test_openml.py::test_warn_ignore_attribute[True]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_cache[True]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_raises_missing_values_target[False]", "sklearn/datasets/tests/test_openml.py::test_feature_to_dtype[feature5-float64]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_adultcensus[False]", "sklearn/datasets/tests/test_openml.py::test_fetch_nonexiting[True]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_miceprotein_pandas", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_cpu_pandas", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_with_ignored_feature[True]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_iris[True]", "sklearn/datasets/tests/test_openml.py::test_open_openml_url_cache[False]", "sklearn/datasets/tests/test_openml.py::test_dataset_with_openml_error[True]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_anneal[True]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_iris_multitarget[False]", "sklearn/datasets/tests/test_openml.py::test_raises_illegal_multitarget[True]", "sklearn/datasets/tests/test_openml.py::test_dataset_with_openml_error[False]", "sklearn/datasets/tests/test_openml.py::test_decode_anneal", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_anneal[False]", "sklearn/datasets/tests/test_openml.py::test_dataset_with_openml_warning[True]", "sklearn/datasets/tests/test_openml.py::test_feature_to_dtype[feature7-float64]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_notarget[False]", "sklearn/datasets/tests/test_openml.py::test_string_attribute_without_dataframe[False]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_emotions_pandas", "sklearn/datasets/tests/test_openml.py::test_illegal_column[False]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_cache[False]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_anneal_pandas", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_iris_multitarget_pandas", "sklearn/datasets/tests/test_openml.py::test_decode_cpu", "sklearn/datasets/tests/test_openml.py::test_feature_to_dtype[feature3-float64]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_emotions[True]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_iris_pandas_equal_to_no_frame", "sklearn/datasets/tests/test_openml.py::test_decode_emotions", "sklearn/datasets/tests/test_openml.py::test_string_attribute_without_dataframe[True]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_iris_pandas", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_emotions[False]", "sklearn/datasets/tests/test_openml.py::test_open_openml_url_unlinks_local_path[False-False]", "sklearn/datasets/tests/test_openml.py::test_open_openml_url_cache[True]", "sklearn/datasets/tests/test_openml.py::test_retry_with_clean_cache_http_error", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_anneal_multitarget[True]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_australian[False]", "sklearn/datasets/tests/test_openml.py::test_dataset_with_openml_warning[False]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_iris[False]", "sklearn/datasets/tests/test_openml.py::test_feature_to_dtype[feature2-float64]", "sklearn/datasets/tests/test_openml.py::test_feature_to_dtype[feature8-category]", "sklearn/datasets/tests/test_openml.py::test_fetch_nonexiting[False]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_raises_illegal_argument", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_notarget[True]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_adultcensus_pandas_return_X_y", "sklearn/datasets/tests/test_openml.py::test_decode_iris", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_cpu[True]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_miceprotein[True]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_raises_missing_values_target[True]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_miceprotein[False]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_inactive[False]", "sklearn/datasets/tests/test_openml.py::test_retry_with_clean_cache", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_adultcensus[True]", "sklearn/datasets/tests/test_openml.py::test_open_openml_url_unlinks_local_path[True-False]", "sklearn/datasets/tests/test_openml.py::test_raises_illegal_multitarget[False]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_adultcensus_pandas", "sklearn/datasets/tests/test_openml.py::test_illegal_column[True]", "sklearn/datasets/tests/test_openml.py::test_feature_to_dtype[feature6-int64]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_australian_pandas_error_sparse", "sklearn/datasets/tests/test_openml.py::test_feature_to_dtype[feature4-float64]", "sklearn/datasets/tests/test_openml.py::test_convert_arff_data_dataframe_warning_low_memory_pandas", "sklearn/datasets/tests/test_openml.py::test_open_openml_url_unlinks_local_path[True-True]", "sklearn/datasets/tests/test_openml.py::test_feature_to_dtype[feature9-category]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_inactive[True]", "sklearn/datasets/tests/test_openml.py::test_feature_to_dtype_error[feature0]", "sklearn/datasets/tests/test_openml.py::test_feature_to_dtype[feature1-object]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_iris_multitarget[True]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_australian[True]", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_titanic_pandas", "sklearn/datasets/tests/test_openml.py::test_fetch_openml_anneal_multitarget[False]", "sklearn/datasets/tests/test_openml.py::test_warn_ignore_attribute[False]", "sklearn/datasets/tests/test_openml.py::test_feature_to_dtype[feature0-object]" ]
[ "sklearn/datasets/tests/test_openml.py::test_fetch_openml_as_frame_auto" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex 927812d9fd6dd..ea27d7579ae4d 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -44,6 +44,14 @@ Changelog\n :pr:`<PRID>` by :user:`<NAME>`.\n where <PRID> is the *pull request* number, not the issue number.\n \n+:mod:`sklearn.datasets`\n+.......................\n+\n+- |Enhancement| :func:`datasets.fetch_openml` now allows argument `as_frame`\n+ to be 'auto', which tries to convert returned data to pandas DataFrame\n+ unless data is sparse.\n+ :pr:`<PRID>` by :user:`<NAME>`.\n+\n :mod:`sklearn.decomposition`\n ............................\n \n" } ]
diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index 927812d9fd6dd..ea27d7579ae4d 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -44,6 +44,14 @@ Changelog :pr:`<PRID>` by :user:`<NAME>`. where <PRID> is the *pull request* number, not the issue number. +:mod:`sklearn.datasets` +....................... + +- |Enhancement| :func:`datasets.fetch_openml` now allows argument `as_frame` + to be 'auto', which tries to convert returned data to pandas DataFrame + unless data is sparse. + :pr:`<PRID>` by :user:`<NAME>`. + :mod:`sklearn.decomposition` ............................
scikit-learn/scikit-learn
scikit-learn__scikit-learn-17937
https://github.com/scikit-learn/scikit-learn/pull/17937
diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst index 6dbab18d94a0c..b58821710a125 100644 --- a/doc/modules/classes.rst +++ b/doc/modules/classes.rst @@ -124,6 +124,7 @@ Functions cluster.dbscan cluster.estimate_bandwidth cluster.k_means + cluster.kmeans_plusplus cluster.mean_shift cluster.spectral_clustering cluster.ward_tree diff --git a/doc/modules/clustering.rst b/doc/modules/clustering.rst index 208f6461d7e33..4bcc95d4b9826 100644 --- a/doc/modules/clustering.rst +++ b/doc/modules/clustering.rst @@ -197,7 +197,11 @@ initializations of the centroids. One method to help address this issue is the k-means++ initialization scheme, which has been implemented in scikit-learn (use the ``init='k-means++'`` parameter). This initializes the centroids to be (generally) distant from each other, leading to provably better results than -random initialization, as shown in the reference. +random initialization, as shown in the reference. + +K-means++ can also be called independently to select seeds for other +clustering algorithms, see :func:`sklearn.cluster.kmeans_plusplus` for details +and example usage. The algorithm supports sample weights, which can be given by a parameter ``sample_weight``. This allows to assign more weight to some samples when diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index 9db5535415af5..1d27fc7f5ceab 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -79,6 +79,10 @@ Changelog `init_size_`, are deprecated and will be removed in 0.26. :pr:`17864` by :user:`Jérémie du Boisberranger <jeremiedbb>`. +- |Enhancement| Added :func:`cluster.kmeans_plusplus` as public function. + Initialization by KMeans++ can now be called separately to generate + initial cluster centroids. :pr:`17937` by :user:`g-walsh` + :mod:`sklearn.compose` ...................... diff --git a/examples/cluster/plot_kmeans_plusplus.py b/examples/cluster/plot_kmeans_plusplus.py new file mode 100644 index 0000000000000..d9821db2d452e --- /dev/null +++ b/examples/cluster/plot_kmeans_plusplus.py @@ -0,0 +1,45 @@ +""" +=========================================================== +An example of K-Means++ initialization +=========================================================== + +An example to show the output of the :func:`sklearn.cluster.kmeans_plusplus` +function for generating initial seeds for clustering. + +K-Means++ is used as the default initialization for :ref:`k_means`. + +""" +print(__doc__) + +from sklearn.cluster import kmeans_plusplus +from sklearn.datasets import make_blobs +import matplotlib.pyplot as plt + +# Generate sample data +n_samples = 4000 +n_components = 4 + +X, y_true = make_blobs(n_samples=n_samples, + centers=n_components, + cluster_std=0.60, + random_state=0) +X = X[:, ::-1] + +# Calculate seeds from kmeans++ +centers_init, indices = kmeans_plusplus(X, n_clusters=4, + random_state=0) + +# Plot init seeds along side sample data +plt.figure(1) +colors = ['#4EACC5', '#FF9C34', '#4E9A06', 'm'] + +for k, col in enumerate(colors): + cluster_data = y_true == k + plt.scatter(X[cluster_data, 0], X[cluster_data, 1], + c=col, marker='.', s=10) + +plt.scatter(centers_init[:, 0], centers_init[:, 1], c='b', s=50) +plt.title("K-Means++ Initialization") +plt.xticks([]) +plt.yticks([]) +plt.show() diff --git a/sklearn/cluster/__init__.py b/sklearn/cluster/__init__.py index 5f3cc58507576..714395d4fe469 100644 --- a/sklearn/cluster/__init__.py +++ b/sklearn/cluster/__init__.py @@ -9,7 +9,7 @@ from ._affinity_propagation import affinity_propagation, AffinityPropagation from ._agglomerative import (ward_tree, AgglomerativeClustering, linkage_tree, FeatureAgglomeration) -from ._kmeans import k_means, KMeans, MiniBatchKMeans +from ._kmeans import k_means, KMeans, MiniBatchKMeans, kmeans_plusplus from ._dbscan import dbscan, DBSCAN from ._optics import (OPTICS, cluster_optics_dbscan, compute_optics_graph, cluster_optics_xi) @@ -34,6 +34,7 @@ 'estimate_bandwidth', 'get_bin_seeds', 'k_means', + 'kmeans_plusplus', 'linkage_tree', 'mean_shift', 'spectral_clustering', diff --git a/sklearn/cluster/_kmeans.py b/sklearn/cluster/_kmeans.py index 69901236d73b8..d3d34f825d86f 100644 --- a/sklearn/cluster/_kmeans.py +++ b/sklearn/cluster/_kmeans.py @@ -45,14 +45,15 @@ # Initialization heuristic -def _k_init(X, n_clusters, x_squared_norms, random_state, n_local_trials=None): - """Init n_clusters seeds according to k-means++ +def _kmeans_plusplus(X, n_clusters, x_squared_norms, + random_state, n_local_trials=None): + """Computational component for initialization of n_clusters by + k-means++. Prior validation of data is assumed. Parameters ---------- X : {ndarray, sparse matrix} of shape (n_samples, n_features) - The data to pick seeds for. To avoid memory copy, the input data - should be double precision (dtype=np.float64). + The data to pick seeds for. n_clusters : int The number of seeds to choose. @@ -70,22 +71,19 @@ def _k_init(X, n_clusters, x_squared_norms, random_state, n_local_trials=None): Set to None to make the number of trials depend logarithmically on the number of seeds (2+log(k)); this is the default. - Notes - ----- - Selects initial cluster centers for k-mean clustering in a smart way - to speed up convergence. see: Arthur, D. and Vassilvitskii, S. - "k-means++: the advantages of careful seeding". ACM-SIAM symposium - on Discrete algorithms. 2007 + Returns + ------- + centers : ndarray of shape (n_clusters, n_features) + The inital centers for k-means. - Version ported from http://www.stanford.edu/~darthur/kMeansppTest.zip, - which is the implementation used in the aforementioned paper. + indices : ndarray of shape (n_clusters,) + The index location of the chosen centers in the data array X. For a + given index and center, X[index] = center. """ n_samples, n_features = X.shape centers = np.empty((n_clusters, n_features), dtype=X.dtype) - assert x_squared_norms is not None, 'x_squared_norms None in _k_init' - # Set the number of local seeding trials if none is given if n_local_trials is None: # This is what Arthur/Vassilvitskii tried, but did not report @@ -93,12 +91,14 @@ def _k_init(X, n_clusters, x_squared_norms, random_state, n_local_trials=None): # that it helped. n_local_trials = 2 + int(np.log(n_clusters)) - # Pick first center randomly + # Pick first center randomly and track index of point center_id = random_state.randint(n_samples) + indices = np.full(n_clusters, -1, dtype=int) if sp.issparse(X): centers[0] = X[center_id].toarray() else: centers[0] = X[center_id] + indices[0] = center_id # Initialize list of closest distances and calculate current potential closest_dist_sq = euclidean_distances( @@ -137,8 +137,9 @@ def _k_init(X, n_clusters, x_squared_norms, random_state, n_local_trials=None): centers[c] = X[best_candidate].toarray() else: centers[c] = X[best_candidate] + indices[c] = best_candidate - return centers + return centers, indices ############################################################################### @@ -902,8 +903,9 @@ def _init_centroids(self, X, x_squared_norms, init, random_state, n_samples = X.shape[0] if isinstance(init, str) and init == 'k-means++': - centers = _k_init(X, n_clusters, random_state=random_state, - x_squared_norms=x_squared_norms) + centers, _ = _kmeans_plusplus(X, n_clusters, + random_state=random_state, + x_squared_norms=x_squared_norms) elif isinstance(init, str) and init == 'random': seeds = random_state.permutation(n_samples)[:n_clusters] centers = X[seeds] @@ -1886,3 +1888,97 @@ def _more_tags(self): 'zero sample_weight is not equivalent to removing samples', } } + + +def kmeans_plusplus(X, n_clusters, *, x_squared_norms=None, + random_state=None, n_local_trials=None): + """Init n_clusters seeds according to k-means++ + + .. versionadded:: 0.24 + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The data to pick seeds from. + + n_clusters : int + The number of centroids to initialize + + x_squared_norms : array-like of shape (n_samples,), default=None + Squared Euclidean norm of each data point. + + random_state : int or RandomState instance, default=None + Determines random number generation for centroid initialization. Pass + an int for reproducible output across multiple function calls. + See :term:`Glossary <random_state>`. + + n_local_trials : int, default=None + The number of seeding trials for each center (except the first), + of which the one reducing inertia the most is greedily chosen. + Set to None to make the number of trials depend logarithmically + on the number of seeds (2+log(k)). + + Returns + ------- + centers : ndarray of shape (n_clusters, n_features) + The inital centers for k-means. + + indices : ndarray of shape (n_clusters,) + The index location of the chosen centers in the data array X. For a + given index and center, X[index] = center. + + Notes + ----- + Selects initial cluster centers for k-mean clustering in a smart way + to speed up convergence. see: Arthur, D. and Vassilvitskii, S. + "k-means++: the advantages of careful seeding". ACM-SIAM symposium + on Discrete algorithms. 2007 + + Examples + -------- + + >>> from sklearn.cluster import kmeans_plusplus + >>> import numpy as np + >>> X = np.array([[1, 2], [1, 4], [1, 0], + ... [10, 2], [10, 4], [10, 0]]) + >>> centers, indices = kmeans_plusplus(X, n_clusters=2, random_state=0) + >>> centers + array([[10, 4], + [ 1, 0]]) + >>> indices + array([4, 2]) + """ + + # Check data + check_array(X, accept_sparse='csr', + dtype=[np.float64, np.float32]) + + if X.shape[0] < n_clusters: + raise ValueError(f"n_samples={X.shape[0]} should be >= " + f"n_clusters={n_clusters}.") + + # Check parameters + if x_squared_norms is None: + x_squared_norms = row_norms(X, squared=True) + else: + x_squared_norms = check_array(x_squared_norms, + dtype=X.dtype, + ensure_2d=False) + + if x_squared_norms.shape[0] != X.shape[0]: + raise ValueError( + f"The length of x_squared_norms {x_squared_norms.shape[0]} should " + f"be equal to the length of n_samples {X.shape[0]}.") + + if n_local_trials is not None and n_local_trials < 1: + raise ValueError( + f"n_local_trials is set to {n_local_trials} but should be an " + f"integer value greater than zero.") + + random_state = check_random_state(random_state) + + # Call private k-means++ + centers, indices = _kmeans_plusplus(X, n_clusters, x_squared_norms, + random_state, n_local_trials) + + return centers, indices
diff --git a/sklearn/cluster/tests/test_k_means.py b/sklearn/cluster/tests/test_k_means.py index 2110c08f09974..06a682eec17c7 100644 --- a/sklearn/cluster/tests/test_k_means.py +++ b/sklearn/cluster/tests/test_k_means.py @@ -20,7 +20,7 @@ from sklearn.metrics import pairwise_distances from sklearn.metrics import pairwise_distances_argmin from sklearn.metrics.cluster import v_measure_score -from sklearn.cluster import KMeans, k_means +from sklearn.cluster import KMeans, k_means, kmeans_plusplus from sklearn.cluster import MiniBatchKMeans from sklearn.cluster._kmeans import _labels_inertia from sklearn.cluster._kmeans import _mini_batch_step @@ -1030,3 +1030,60 @@ def test_minibatch_kmeans_wrong_params(param, match): # are passed for the MiniBatchKMeans specific parameters with pytest.raises(ValueError, match=match): MiniBatchKMeans(**param).fit(X) + + [email protected]("param, match", [ + ({"n_local_trials": 0}, + r"n_local_trials is set to 0 but should be an " + r"integer value greater than zero"), + ({"x_squared_norms": X[:2]}, + r"The length of x_squared_norms .* should " + r"be equal to the length of n_samples")] +) +def test_kmeans_plusplus_wrong_params(param, match): + with pytest.raises(ValueError, match=match): + kmeans_plusplus(X, n_clusters, **param) + + [email protected]("data", [X, X_csr]) [email protected]("dtype", [np.float64, np.float32]) +def test_kmeans_plusplus_output(data, dtype): + # Check for the correct number of seeds and all positive values + data = data.astype(dtype) + centers, indices = kmeans_plusplus(data, n_clusters) + + # Check there are the correct number of indices and that all indices are + # positive and within the number of samples + assert indices.shape[0] == n_clusters + assert (indices >= 0).all() + assert (indices <= data.shape[0]).all() + + # Check for the correct number of seeds and that they are bound by the data + assert centers.shape[0] == n_clusters + assert (centers.max(axis=0) <= data.max(axis=0)).all() + assert (centers.min(axis=0) >= data.min(axis=0)).all() + + # Check that indices correspond to reported centers + # Use X for comparison rather than data, test still works against centers + # calculated with sparse data. + assert_allclose(X[indices].astype(dtype), centers) + + [email protected]("x_squared_norms", [row_norms(X, squared=True), None]) +def test_kmeans_plusplus_norms(x_squared_norms): + # Check that defining x_squared_norms returns the same as default=None. + centers, indices = kmeans_plusplus(X, n_clusters, + x_squared_norms=x_squared_norms) + + assert_allclose(X[indices], centers) + + +def test_kmeans_plusplus_dataorder(): + # Check that memory layout does not effect result + centers_c, _ = kmeans_plusplus(X, n_clusters, random_state=0) + + X_fortran = np.asfortranarray(X) + + centers_fortran, _ = kmeans_plusplus(X_fortran, n_clusters, random_state=0) + + assert_allclose(centers_c, centers_fortran)
[ { "path": "doc/modules/classes.rst", "old_path": "a/doc/modules/classes.rst", "new_path": "b/doc/modules/classes.rst", "metadata": "diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst\nindex 6dbab18d94a0c..b58821710a125 100644\n--- a/doc/modules/classes.rst\n+++ b/doc/modules/classes.rst\n@@ -124,6 +124,7 @@ Functions\n cluster.dbscan\n cluster.estimate_bandwidth\n cluster.k_means\n+ cluster.kmeans_plusplus\n cluster.mean_shift\n cluster.spectral_clustering\n cluster.ward_tree\n" }, { "path": "doc/modules/clustering.rst", "old_path": "a/doc/modules/clustering.rst", "new_path": "b/doc/modules/clustering.rst", "metadata": "diff --git a/doc/modules/clustering.rst b/doc/modules/clustering.rst\nindex 208f6461d7e33..4bcc95d4b9826 100644\n--- a/doc/modules/clustering.rst\n+++ b/doc/modules/clustering.rst\n@@ -197,7 +197,11 @@ initializations of the centroids. One method to help address this issue is the\n k-means++ initialization scheme, which has been implemented in scikit-learn\n (use the ``init='k-means++'`` parameter). This initializes the centroids to be\n (generally) distant from each other, leading to provably better results than\n-random initialization, as shown in the reference.\n+random initialization, as shown in the reference. \n+\n+K-means++ can also be called independently to select seeds for other \n+clustering algorithms, see :func:`sklearn.cluster.kmeans_plusplus` for details\n+and example usage.\n \n The algorithm supports sample weights, which can be given by a parameter\n ``sample_weight``. This allows to assign more weight to some samples when\n" }, { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex 9db5535415af5..1d27fc7f5ceab 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -79,6 +79,10 @@ Changelog\n `init_size_`, are deprecated and will be removed in 0.26. :pr:`17864` by\n :user:`Jérémie du Boisberranger <jeremiedbb>`.\n \n+- |Enhancement| Added :func:`cluster.kmeans_plusplus` as public function. \n+ Initialization by KMeans++ can now be called separately to generate\n+ initial cluster centroids. :pr:`17937` by :user:`g-walsh`\n+\n :mod:`sklearn.compose`\n ......................\n \n" } ]
0.24
74f18faffa90c143f42feeb48c524cff3a0e8270
[]
[ "sklearn/cluster/tests/test_k_means.py::test_predict[KMeans-full-random-float64-dense]", "sklearn/cluster/tests/test_k_means.py::test_float_precision[KMeans-sparse]", "sklearn/cluster/tests/test_k_means.py::test_centers_not_mutated[KMeans-float32]", "sklearn/cluster/tests/test_k_means.py::test_warning_n_init_precomputed_centers[MiniBatchKMeans]", "sklearn/cluster/tests/test_k_means.py::test_kmeans_plusplus_wrong_params[param1-The length of x_squared_norms .* should be equal to the length of n_samples]", "sklearn/cluster/tests/test_k_means.py::test_fortran_aligned_data[KMeans]", "sklearn/cluster/tests/test_k_means.py::test_minibatch_kmeans_partial_fit_init[ndarray]", "sklearn/cluster/tests/test_k_means.py::test_k_means_fit_predict[0-2-1e-07-csr_matrix-float64-full]", "sklearn/cluster/tests/test_k_means.py::test_all_init[KMeans-callable-dense]", "sklearn/cluster/tests/test_k_means.py::test_kmeans_verbose[0-full]", "sklearn/cluster/tests/test_k_means.py::test_kmeans_copyx", "sklearn/cluster/tests/test_k_means.py::test_sample_weight_unchanged[MiniBatchKMeans]", "sklearn/cluster/tests/test_k_means.py::test_k_means_1_iteration[full-sparse]", "sklearn/cluster/tests/test_k_means.py::test_k_means_fit_predict[1-2-0.1-csr_matrix-float32-elkan]", "sklearn/cluster/tests/test_k_means.py::test_wrong_params[param0-n_init should be > 0-MiniBatchKMeans]", "sklearn/cluster/tests/test_k_means.py::test_predict[KMeans-elkan-k-means++-float32-dense]", "sklearn/cluster/tests/test_k_means.py::test_weighted_vs_repeated", "sklearn/cluster/tests/test_k_means.py::test_kmeans_results[float32-full-dense]", "sklearn/cluster/tests/test_k_means.py::test_integer_input[KMeans-k-means++-int32-sparse]", "sklearn/cluster/tests/test_k_means.py::test_wrong_params[param2-n_samples.* should be >= n_clusters-KMeans]", "sklearn/cluster/tests/test_k_means.py::test_transform[MiniBatchKMeans]", "sklearn/cluster/tests/test_k_means.py::test_kmeans_elkan_results[0.01-sparse-blobs]", "sklearn/cluster/tests/test_k_means.py::test_integer_input[MiniBatchKMeans-k-means++-int32-sparse]", "sklearn/cluster/tests/test_k_means.py::test_integer_input[KMeans-k-means++-int32-dense]", "sklearn/cluster/tests/test_k_means.py::test_scaled_weights", "sklearn/cluster/tests/test_k_means.py::test_k_means_1_iteration[elkan-dense]", "sklearn/cluster/tests/test_k_means.py::test_predict[KMeans-full-k-means++-float32-dense]", "sklearn/cluster/tests/test_k_means.py::test_predict[KMeans-elkan-k-means++-float32-sparse]", "sklearn/cluster/tests/test_k_means.py::test_transform[KMeans]", "sklearn/cluster/tests/test_k_means.py::test_inertia[float64]", "sklearn/cluster/tests/test_k_means.py::test_kmeans_elkan_results[1e-100-sparse-normal]", "sklearn/cluster/tests/test_k_means.py::test_centers_not_mutated[MiniBatchKMeans-int64]", "sklearn/cluster/tests/test_k_means.py::test_minibatch_kmeans_wrong_params[param3-reassignment_ratio should be >= 0]", "sklearn/cluster/tests/test_k_means.py::test_all_init[MiniBatchKMeans-callable-dense]", "sklearn/cluster/tests/test_k_means.py::test_wrong_params[param6-The shape of the initial centers .* does not match the number of features of the data-KMeans]", "sklearn/cluster/tests/test_k_means.py::test_k_means_fit_predict[3-300-1e-07-csr_matrix-float64-elkan]", "sklearn/cluster/tests/test_k_means.py::test_n_jobs_deprecated[None]", "sklearn/cluster/tests/test_k_means.py::test_wrong_params[param2-n_samples.* should be >= n_clusters-MiniBatchKMeans]", "sklearn/cluster/tests/test_k_means.py::test_wrong_params[param7-init should be either 'k-means\\\\+\\\\+', 'random', a ndarray or a callable-MiniBatchKMeans]", "sklearn/cluster/tests/test_k_means.py::test_kmeans_elkan_results[0.01-dense-normal]", "sklearn/cluster/tests/test_k_means.py::test_score_max_iter[MiniBatchKMeans]", "sklearn/cluster/tests/test_k_means.py::test_all_init[KMeans-random-dense]", "sklearn/cluster/tests/test_k_means.py::test_wrong_params[param3-The shape of the initial centers .* does not match the number of clusters-MiniBatchKMeans]", "sklearn/cluster/tests/test_k_means.py::test_precompute_distance_deprecated[True]", "sklearn/cluster/tests/test_k_means.py::test_centers_not_mutated[MiniBatchKMeans-float64]", "sklearn/cluster/tests/test_k_means.py::test_kmeans_elkan_results[1e-08-dense-normal]", "sklearn/cluster/tests/test_k_means.py::test_k_means_fit_predict[3-300-1e-07-csr_matrix-float32-elkan]", "sklearn/cluster/tests/test_k_means.py::test_kmeans_verbose[0.01-elkan]", "sklearn/cluster/tests/test_k_means.py::test_minibatch_with_many_reassignments", "sklearn/cluster/tests/test_k_means.py::test_k_means_1_iteration[elkan-sparse]", "sklearn/cluster/tests/test_k_means.py::test_kmeans_elkan_results[0-dense-normal]", "sklearn/cluster/tests/test_k_means.py::test_minibatch_kmeans_partial_fit_init[callable]", "sklearn/cluster/tests/test_k_means.py::test_wrong_params[param6-The shape of the initial centers .* does not match the number of features of the data-MiniBatchKMeans]", "sklearn/cluster/tests/test_k_means.py::test_predict[MiniBatchKMeans-None-random-float32-dense]", "sklearn/cluster/tests/test_k_means.py::test_all_init[KMeans-k-means++-dense]", "sklearn/cluster/tests/test_k_means.py::test_k_means_fit_predict[1-2-0.1-csr_matrix-float32-full]", "sklearn/cluster/tests/test_k_means.py::test_all_init[MiniBatchKMeans-ndarray-sparse]", "sklearn/cluster/tests/test_k_means.py::test_kmeans_plusplus_norms[x_squared_norms0]", "sklearn/cluster/tests/test_k_means.py::test_inertia[float32]", "sklearn/cluster/tests/test_k_means.py::test_predict[KMeans-full-random-float64-sparse]", "sklearn/cluster/tests/test_k_means.py::test_all_init[KMeans-random-sparse]", "sklearn/cluster/tests/test_k_means.py::test_k_means_fit_predict[4-300-0.1-asarray-float32-full]", "sklearn/cluster/tests/test_k_means.py::test_n_jobs_deprecated[1]", "sklearn/cluster/tests/test_k_means.py::test_k_means_fit_predict[3-300-1e-07-asarray-float64-elkan]", "sklearn/cluster/tests/test_k_means.py::test_relocate_empty_clusters[dense]", "sklearn/cluster/tests/test_k_means.py::test_score_max_iter[KMeans]", "sklearn/cluster/tests/test_k_means.py::test_integer_input[MiniBatchKMeans-ndarray-int64-sparse]", "sklearn/cluster/tests/test_k_means.py::test_k_means_fit_predict[0-2-1e-07-asarray-float32-full]", "sklearn/cluster/tests/test_k_means.py::test_kmeans_verbose[0.01-full]", "sklearn/cluster/tests/test_k_means.py::test_k_means_fit_predict[4-300-0.1-csr_matrix-float32-elkan]", "sklearn/cluster/tests/test_k_means.py::test_warning_elkan_1_cluster", "sklearn/cluster/tests/test_k_means.py::test_kmeans_warns_less_centers_than_unique_points", "sklearn/cluster/tests/test_k_means.py::test_k_means_fit_predict[3-300-1e-07-asarray-float64-full]", "sklearn/cluster/tests/test_k_means.py::test_result_of_kmeans_equal_in_diff_n_threads", "sklearn/cluster/tests/test_k_means.py::test_minibatch_kmeans_deprecated_attributes[counts_]", "sklearn/cluster/tests/test_k_means.py::test_sample_weight_unchanged[KMeans]", "sklearn/cluster/tests/test_k_means.py::test_kmeans_plusplus_output[float32-data1]", "sklearn/cluster/tests/test_k_means.py::test_predict[KMeans-elkan-random-float64-sparse]", "sklearn/cluster/tests/test_k_means.py::test_euclidean_distance[False-float64]", "sklearn/cluster/tests/test_k_means.py::test_minibatch_kmeans_deprecated_attributes[random_state_]", "sklearn/cluster/tests/test_k_means.py::test_minibatch_kmeans_wrong_params[param1-batch_size should be > 0]", "sklearn/cluster/tests/test_k_means.py::test_all_init[MiniBatchKMeans-random-dense]", "sklearn/cluster/tests/test_k_means.py::test_kmeans_elkan_results[0-sparse-blobs]", "sklearn/cluster/tests/test_k_means.py::test_k_means_fit_predict[3-300-1e-07-asarray-float32-full]", "sklearn/cluster/tests/test_k_means.py::test_k_means_fit_predict[4-300-0.1-asarray-float64-full]", "sklearn/cluster/tests/test_k_means.py::test_k_means_fit_predict[1-2-0.1-asarray-float32-elkan]", "sklearn/cluster/tests/test_k_means.py::test_integer_input[KMeans-ndarray-int64-sparse]", "sklearn/cluster/tests/test_k_means.py::test_predict[MiniBatchKMeans-None-k-means++-float32-dense]", "sklearn/cluster/tests/test_k_means.py::test_integer_input[KMeans-ndarray-int32-dense]", "sklearn/cluster/tests/test_k_means.py::test_wrong_params[param1-max_iter should be > 0-KMeans]", "sklearn/cluster/tests/test_k_means.py::test_wrong_params[param4-The shape of the initial centers .* does not match the number of clusters-MiniBatchKMeans]", "sklearn/cluster/tests/test_k_means.py::test_centers_not_mutated[MiniBatchKMeans-float32]", "sklearn/cluster/tests/test_k_means.py::test_k_means_fit_predict[1-2-0.1-asarray-float64-elkan]", "sklearn/cluster/tests/test_k_means.py::test_predict[KMeans-full-random-float32-dense]", "sklearn/cluster/tests/test_k_means.py::test_float_precision[KMeans-dense]", "sklearn/cluster/tests/test_k_means.py::test_k_means_1_iteration[full-dense]", "sklearn/cluster/tests/test_k_means.py::test_kmeans_plusplus_norms[None]", "sklearn/cluster/tests/test_k_means.py::test_centers_not_mutated[KMeans-float64]", "sklearn/cluster/tests/test_k_means.py::test_minibatch_kmeans_partial_fit_init[random]", "sklearn/cluster/tests/test_k_means.py::test_all_init[KMeans-ndarray-dense]", "sklearn/cluster/tests/test_k_means.py::test_all_init[MiniBatchKMeans-k-means++-sparse]", "sklearn/cluster/tests/test_k_means.py::test_k_means_fit_predict[0-2-1e-07-asarray-float32-elkan]", "sklearn/cluster/tests/test_k_means.py::test_integer_input[KMeans-k-means++-int64-dense]", "sklearn/cluster/tests/test_k_means.py::test_k_means_fit_predict[0-2-1e-07-asarray-float64-full]", "sklearn/cluster/tests/test_k_means.py::test_k_means_fit_predict[4-300-0.1-asarray-float64-elkan]", "sklearn/cluster/tests/test_k_means.py::test_k_means_fit_predict[4-300-0.1-csr_matrix-float64-elkan]", "sklearn/cluster/tests/test_k_means.py::test_kmeans_init_fitted_centers[dense]", "sklearn/cluster/tests/test_k_means.py::test_fortran_aligned_data[MiniBatchKMeans]", "sklearn/cluster/tests/test_k_means.py::test_wrong_params[param3-The shape of the initial centers .* does not match the number of clusters-KMeans]", "sklearn/cluster/tests/test_k_means.py::test_predict[MiniBatchKMeans-None-random-float64-dense]", "sklearn/cluster/tests/test_k_means.py::test_all_init[KMeans-k-means++-sparse]", "sklearn/cluster/tests/test_k_means.py::test_k_means_fit_predict[0-2-1e-07-csr_matrix-float64-elkan]", "sklearn/cluster/tests/test_k_means.py::test_kmeans_convergence[full]", "sklearn/cluster/tests/test_k_means.py::test_kmeans_init_fitted_centers[sparse]", "sklearn/cluster/tests/test_k_means.py::test_all_init[KMeans-ndarray-sparse]", "sklearn/cluster/tests/test_k_means.py::test_k_means_fit_predict[1-2-0.1-csr_matrix-float64-elkan]", "sklearn/cluster/tests/test_k_means.py::test_minibatch_kmeans_verbose", "sklearn/cluster/tests/test_k_means.py::test_predict[KMeans-elkan-random-float32-dense]", "sklearn/cluster/tests/test_k_means.py::test_integer_input[MiniBatchKMeans-ndarray-int64-dense]", "sklearn/cluster/tests/test_k_means.py::test_centers_not_mutated[KMeans-int32]", "sklearn/cluster/tests/test_k_means.py::test_predict[MiniBatchKMeans-None-random-float64-sparse]", "sklearn/cluster/tests/test_k_means.py::test_k_means_fit_predict[3-300-1e-07-csr_matrix-float64-full]", "sklearn/cluster/tests/test_k_means.py::test_k_means_fit_predict[3-300-1e-07-asarray-float32-elkan]", "sklearn/cluster/tests/test_k_means.py::test_kmeans_wrong_params[param0-Algorithm must be 'auto', 'full' or 'elkan']", "sklearn/cluster/tests/test_k_means.py::test_wrong_params[param7-init should be either 'k-means\\\\+\\\\+', 'random', a ndarray or a callable-KMeans]", "sklearn/cluster/tests/test_k_means.py::test_kmeans_elkan_results[0-dense-blobs]", "sklearn/cluster/tests/test_k_means.py::test_euclidean_distance[True-float64]", "sklearn/cluster/tests/test_k_means.py::test_minibatch_kmeans_partial_fit_init[k-means++]", "sklearn/cluster/tests/test_k_means.py::test_kmeans_elkan_results[0.01-sparse-normal]", "sklearn/cluster/tests/test_k_means.py::test_minibatch_kmeans_deprecated_attributes[init_size_]", "sklearn/cluster/tests/test_k_means.py::test_wrong_params[param1-max_iter should be > 0-MiniBatchKMeans]", "sklearn/cluster/tests/test_k_means.py::test_integer_input[KMeans-k-means++-int64-sparse]", "sklearn/cluster/tests/test_k_means.py::test_centers_not_mutated[KMeans-int64]", "sklearn/cluster/tests/test_k_means.py::test_minibatch_kmeans_wrong_params[param2-init_size should be > 0]", "sklearn/cluster/tests/test_k_means.py::test_minibatch_kmeans_init_size", "sklearn/cluster/tests/test_k_means.py::test_kmeans_empty_cluster_relocated[sparse]", "sklearn/cluster/tests/test_k_means.py::test_wrong_params[param4-The shape of the initial centers .* does not match the number of clusters-KMeans]", "sklearn/cluster/tests/test_k_means.py::test_k_means_fit_predict[3-300-1e-07-csr_matrix-float32-full]", "sklearn/cluster/tests/test_k_means.py::test_kmeans_relocated_clusters[elkan-dense]", "sklearn/cluster/tests/test_k_means.py::test_k_means_fit_predict[0-2-1e-07-csr_matrix-float32-elkan]", "sklearn/cluster/tests/test_k_means.py::test_kmeans_results[float64-elkan-dense]", "sklearn/cluster/tests/test_k_means.py::test_kmeans_results[float32-elkan-dense]", "sklearn/cluster/tests/test_k_means.py::test_predict[KMeans-elkan-random-float32-sparse]", "sklearn/cluster/tests/test_k_means.py::test_predict[MiniBatchKMeans-None-k-means++-float32-sparse]", "sklearn/cluster/tests/test_k_means.py::test_predict_dense_sparse[KMeans-ndarray]", "sklearn/cluster/tests/test_k_means.py::test_precompute_distance_deprecated[auto]", "sklearn/cluster/tests/test_k_means.py::test_kmeans_plusplus_output[float32-data0]", "sklearn/cluster/tests/test_k_means.py::test_kmeans_elkan_iter_attribute", "sklearn/cluster/tests/test_k_means.py::test_kmeans_relocated_clusters[full-dense]", "sklearn/cluster/tests/test_k_means.py::test_integer_input[KMeans-ndarray-int32-sparse]", "sklearn/cluster/tests/test_k_means.py::test_kmeans_plusplus_dataorder", "sklearn/cluster/tests/test_k_means.py::test_predict[MiniBatchKMeans-None-random-float32-sparse]", "sklearn/cluster/tests/test_k_means.py::test_wrong_params[param5-The shape of the initial centers .* does not match the number of features of the data-KMeans]", "sklearn/cluster/tests/test_k_means.py::test_minibatch_kmeans_wrong_params[param0-max_no_improvement should be >= 0]", "sklearn/cluster/tests/test_k_means.py::test_kmeans_elkan_results[1e-08-dense-blobs]", "sklearn/cluster/tests/test_k_means.py::test_kmeans_elkan_results[0.01-dense-blobs]", "sklearn/cluster/tests/test_k_means.py::test_kmeans_elkan_results[1e-08-sparse-normal]", "sklearn/cluster/tests/test_k_means.py::test_kmeans_results[float64-elkan-sparse]", "sklearn/cluster/tests/test_k_means.py::test_float_precision[MiniBatchKMeans-dense]", "sklearn/cluster/tests/test_k_means.py::test_kmeans_results[float32-elkan-sparse]", "sklearn/cluster/tests/test_k_means.py::test_k_means_fit_predict[4-300-0.1-asarray-float32-elkan]", "sklearn/cluster/tests/test_k_means.py::test_centers_not_mutated[MiniBatchKMeans-int32]", "sklearn/cluster/tests/test_k_means.py::test_relocate_empty_clusters[sparse]", "sklearn/cluster/tests/test_k_means.py::test_all_init[MiniBatchKMeans-callable-sparse]", "sklearn/cluster/tests/test_k_means.py::test_kmeans_elkan_results[1e-08-sparse-blobs]", "sklearn/cluster/tests/test_k_means.py::test_predict[KMeans-elkan-k-means++-float64-dense]", "sklearn/cluster/tests/test_k_means.py::test_kmeans_plusplus_output[float64-data1]", "sklearn/cluster/tests/test_k_means.py::test_k_means_fit_predict[1-2-0.1-asarray-float64-full]", "sklearn/cluster/tests/test_k_means.py::test_wrong_params[param5-The shape of the initial centers .* does not match the number of features of the data-MiniBatchKMeans]", "sklearn/cluster/tests/test_k_means.py::test_kmeans_elkan_results[1e-100-sparse-blobs]", "sklearn/cluster/tests/test_k_means.py::test_kmeans_elkan_results[1e-100-dense-blobs]", "sklearn/cluster/tests/test_k_means.py::test_kmeans_relocated_clusters[elkan-sparse]", "sklearn/cluster/tests/test_k_means.py::test_minibatch_sensible_reassign", "sklearn/cluster/tests/test_k_means.py::test_kmeans_results[float64-full-sparse]", "sklearn/cluster/tests/test_k_means.py::test_predict[KMeans-elkan-k-means++-float64-sparse]", "sklearn/cluster/tests/test_k_means.py::test_predict[MiniBatchKMeans-None-k-means++-float64-sparse]", "sklearn/cluster/tests/test_k_means.py::test_warning_n_init_precomputed_centers[KMeans]", "sklearn/cluster/tests/test_k_means.py::test_integer_input[MiniBatchKMeans-k-means++-int64-dense]", "sklearn/cluster/tests/test_k_means.py::test_kmeans_plusplus_wrong_params[param0-n_local_trials is set to 0 but should be an integer value greater than zero]", "sklearn/cluster/tests/test_k_means.py::test_k_means_fit_predict[1-2-0.1-csr_matrix-float64-full]", "sklearn/cluster/tests/test_k_means.py::test_n_init", "sklearn/cluster/tests/test_k_means.py::test_predict_dense_sparse[KMeans-k-means++]", "sklearn/cluster/tests/test_k_means.py::test_k_means_fit_predict[0-2-1e-07-asarray-float64-elkan]", "sklearn/cluster/tests/test_k_means.py::test_kmeans_results[float64-full-dense]", "sklearn/cluster/tests/test_k_means.py::test_predict_dense_sparse[MiniBatchKMeans-random]", "sklearn/cluster/tests/test_k_means.py::test_predict[KMeans-full-k-means++-float64-sparse]", "sklearn/cluster/tests/test_k_means.py::test_minibatch_update_consistency", "sklearn/cluster/tests/test_k_means.py::test_kmeans_results[float32-full-sparse]", "sklearn/cluster/tests/test_k_means.py::test_kmeans_elkan_results[0-sparse-normal]", "sklearn/cluster/tests/test_k_means.py::test_unit_weights_vs_no_weights[MiniBatchKMeans-dense]", "sklearn/cluster/tests/test_k_means.py::test_precompute_distance_deprecated[False]", "sklearn/cluster/tests/test_k_means.py::test_predict[KMeans-full-random-float32-sparse]", "sklearn/cluster/tests/test_k_means.py::test_euclidean_distance[True-float32]", "sklearn/cluster/tests/test_k_means.py::test_k_means_fit_predict[4-300-0.1-csr_matrix-float64-full]", "sklearn/cluster/tests/test_k_means.py::test_predict_dense_sparse[MiniBatchKMeans-k-means++]", "sklearn/cluster/tests/test_k_means.py::test_predict_dense_sparse[MiniBatchKMeans-ndarray]", "sklearn/cluster/tests/test_k_means.py::test_all_init[KMeans-callable-sparse]", "sklearn/cluster/tests/test_k_means.py::test_kmeans_plusplus_output[float64-data0]", "sklearn/cluster/tests/test_k_means.py::test_kmeans_elkan_results[1e-100-dense-normal]", "sklearn/cluster/tests/test_k_means.py::test_unit_weights_vs_no_weights[KMeans-dense]", "sklearn/cluster/tests/test_k_means.py::test_k_means_fit_predict[1-2-0.1-asarray-float32-full]", "sklearn/cluster/tests/test_k_means.py::test_kmeans_verbose[0-elkan]", "sklearn/cluster/tests/test_k_means.py::test_k_means_fit_predict[0-2-1e-07-csr_matrix-float32-full]", "sklearn/cluster/tests/test_k_means.py::test_integer_input[MiniBatchKMeans-k-means++-int32-dense]", "sklearn/cluster/tests/test_k_means.py::test_fit_transform[MiniBatchKMeans]", "sklearn/cluster/tests/test_k_means.py::test_fit_transform[KMeans]", "sklearn/cluster/tests/test_k_means.py::test_k_means_fit_predict[4-300-0.1-csr_matrix-float32-full]", "sklearn/cluster/tests/test_k_means.py::test_predict[MiniBatchKMeans-None-k-means++-float64-dense]", "sklearn/cluster/tests/test_k_means.py::test_euclidean_distance[False-float32]", "sklearn/cluster/tests/test_k_means.py::test_all_init[MiniBatchKMeans-k-means++-dense]", "sklearn/cluster/tests/test_k_means.py::test_predict[KMeans-elkan-random-float64-dense]", "sklearn/cluster/tests/test_k_means.py::test_predict_dense_sparse[KMeans-random]", "sklearn/cluster/tests/test_k_means.py::test_predict[KMeans-full-k-means++-float32-sparse]", "sklearn/cluster/tests/test_k_means.py::test_unit_weights_vs_no_weights[MiniBatchKMeans-sparse]", "sklearn/cluster/tests/test_k_means.py::test_all_init[MiniBatchKMeans-random-sparse]", "sklearn/cluster/tests/test_k_means.py::test_kmeans_convergence[elkan]", "sklearn/cluster/tests/test_k_means.py::test_minibatch_kmeans_warning_init_size", "sklearn/cluster/tests/test_k_means.py::test_float_precision[MiniBatchKMeans-sparse]", "sklearn/cluster/tests/test_k_means.py::test_wrong_params[param0-n_init should be > 0-KMeans]", "sklearn/cluster/tests/test_k_means.py::test_k_means_function", "sklearn/cluster/tests/test_k_means.py::test_minibatch_reassign", "sklearn/cluster/tests/test_k_means.py::test_integer_input[KMeans-ndarray-int64-dense]", "sklearn/cluster/tests/test_k_means.py::test_integer_input[MiniBatchKMeans-ndarray-int32-sparse]", "sklearn/cluster/tests/test_k_means.py::test_all_init[MiniBatchKMeans-ndarray-dense]", "sklearn/cluster/tests/test_k_means.py::test_integer_input[MiniBatchKMeans-k-means++-int64-sparse]", "sklearn/cluster/tests/test_k_means.py::test_integer_input[MiniBatchKMeans-ndarray-int32-dense]", "sklearn/cluster/tests/test_k_means.py::test_predict[KMeans-full-k-means++-float64-dense]", "sklearn/cluster/tests/test_k_means.py::test_kmeans_relocated_clusters[full-sparse]", "sklearn/cluster/tests/test_k_means.py::test_kmeans_empty_cluster_relocated[dense]", "sklearn/cluster/tests/test_k_means.py::test_unit_weights_vs_no_weights[KMeans-sparse]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [ { "type": "file", "name": "examples/cluster/plot_kmeans_plusplus.py" } ] }
[ { "path": "doc/modules/classes.rst", "old_path": "a/doc/modules/classes.rst", "new_path": "b/doc/modules/classes.rst", "metadata": "diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst\nindex 6dbab18d94a0c..b58821710a125 100644\n--- a/doc/modules/classes.rst\n+++ b/doc/modules/classes.rst\n@@ -124,6 +124,7 @@ Functions\n cluster.dbscan\n cluster.estimate_bandwidth\n cluster.k_means\n+ cluster.kmeans_plusplus\n cluster.mean_shift\n cluster.spectral_clustering\n cluster.ward_tree\n" }, { "path": "doc/modules/clustering.rst", "old_path": "a/doc/modules/clustering.rst", "new_path": "b/doc/modules/clustering.rst", "metadata": "diff --git a/doc/modules/clustering.rst b/doc/modules/clustering.rst\nindex 208f6461d7e33..4bcc95d4b9826 100644\n--- a/doc/modules/clustering.rst\n+++ b/doc/modules/clustering.rst\n@@ -197,7 +197,11 @@ initializations of the centroids. One method to help address this issue is the\n k-means++ initialization scheme, which has been implemented in scikit-learn\n (use the ``init='k-means++'`` parameter). This initializes the centroids to be\n (generally) distant from each other, leading to provably better results than\n-random initialization, as shown in the reference.\n+random initialization, as shown in the reference. \n+\n+K-means++ can also be called independently to select seeds for other \n+clustering algorithms, see :func:`sklearn.cluster.kmeans_plusplus` for details\n+and example usage.\n \n The algorithm supports sample weights, which can be given by a parameter\n ``sample_weight``. This allows to assign more weight to some samples when\n" }, { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex 9db5535415af5..1d27fc7f5ceab 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -79,6 +79,10 @@ Changelog\n `init_size_`, are deprecated and will be removed in 0.26. :pr:`<PRID>` by\n :user:`<NAME>`.\n \n+- |Enhancement| Added :func:`cluster.kmeans_plusplus` as public function. \n+ Initialization by KMeans++ can now be called separately to generate\n+ initial cluster centroids. :pr:`<PRID>` by :user:`<NAME>`\n+\n :mod:`sklearn.compose`\n ......................\n \n" } ]
diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst index 6dbab18d94a0c..b58821710a125 100644 --- a/doc/modules/classes.rst +++ b/doc/modules/classes.rst @@ -124,6 +124,7 @@ Functions cluster.dbscan cluster.estimate_bandwidth cluster.k_means + cluster.kmeans_plusplus cluster.mean_shift cluster.spectral_clustering cluster.ward_tree diff --git a/doc/modules/clustering.rst b/doc/modules/clustering.rst index 208f6461d7e33..4bcc95d4b9826 100644 --- a/doc/modules/clustering.rst +++ b/doc/modules/clustering.rst @@ -197,7 +197,11 @@ initializations of the centroids. One method to help address this issue is the k-means++ initialization scheme, which has been implemented in scikit-learn (use the ``init='k-means++'`` parameter). This initializes the centroids to be (generally) distant from each other, leading to provably better results than -random initialization, as shown in the reference. +random initialization, as shown in the reference. + +K-means++ can also be called independently to select seeds for other +clustering algorithms, see :func:`sklearn.cluster.kmeans_plusplus` for details +and example usage. The algorithm supports sample weights, which can be given by a parameter ``sample_weight``. This allows to assign more weight to some samples when diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index 9db5535415af5..1d27fc7f5ceab 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -79,6 +79,10 @@ Changelog `init_size_`, are deprecated and will be removed in 0.26. :pr:`<PRID>` by :user:`<NAME>`. +- |Enhancement| Added :func:`cluster.kmeans_plusplus` as public function. + Initialization by KMeans++ can now be called separately to generate + initial cluster centroids. :pr:`<PRID>` by :user:`<NAME>` + :mod:`sklearn.compose` ...................... If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names: [{'type': 'file', 'name': 'examples/cluster/plot_kmeans_plusplus.py'}]
scikit-learn/scikit-learn
scikit-learn__scikit-learn-18280
https://github.com/scikit-learn/scikit-learn/pull/18280
diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index c6ef6e5994cdf..9294bab242432 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -112,7 +112,15 @@ Changelog - |Enhancement| :func:`datasets.fetch_covtype` now now supports the optional argument `as_frame`; when it is set to True, the returned Bunch object's `data` and `frame` members are pandas DataFrames, and the `target` member is - a pandas Series. :pr:`17491` by :user:`Alex Liang <tianchuliang>`. + a pandas Series. + :pr:`17491` by :user:`Alex Liang <tianchuliang>`. + +- |Enhancement| :func:`datasets.fetch_kddcup99` now now supports the optional + argument `as_frame`; when it is set to True, the returned Bunch object's + `data` and `frame` members are pandas DataFrames, and the `target` member is + a pandas Series. + :pr:`18280` by :user:`Alex Liang <tianchuliang>` and + `Guillaume Lemaitre`_. - |API| The default value of `as_frame` in :func:`datasets.fetch_openml` is changed from False to 'auto'. diff --git a/sklearn/datasets/_kddcup99.py b/sklearn/datasets/_kddcup99.py index 2c9263701e0c4..e5c8bb2f298de 100644 --- a/sklearn/datasets/_kddcup99.py +++ b/sklearn/datasets/_kddcup99.py @@ -18,6 +18,7 @@ import joblib from ._base import _fetch_remote +from ._base import _convert_data_dataframe from . import get_data_home from ._base import RemoteFileMetadata from ..utils import Bunch @@ -48,7 +49,8 @@ @_deprecate_positional_args def fetch_kddcup99(*, subset=None, data_home=None, shuffle=False, random_state=None, - percent10=True, download_if_missing=True, return_X_y=False): + percent10=True, download_if_missing=True, return_X_y=False, + as_frame=False): """Load the kddcup99 dataset (classification). Download it if necessary. @@ -97,29 +99,48 @@ def fetch_kddcup99(*, subset=None, data_home=None, shuffle=False, .. versionadded:: 0.20 + as_frame : bool, default=False + If `True`, returns a pandas Dataframe for the ``data`` and ``target`` + objects in the `Bunch` returned object; `Bunch` return object will also + have a ``frame`` member. + + .. versionadded:: 0.24 + Returns ------- data : :class:`~sklearn.utils.Bunch` Dictionary-like object, with the following attributes. - data : ndarray of shape (494021, 41) - The data matrix to learn. - target : ndarray of shape (494021,) - The regression target for each sample. + data : {ndarray, dataframe} of shape (494021, 41) + The data matrix to learn. If `as_frame=True`, `data` will be a + pandas DataFrame. + target : {ndarray, series} of shape (494021,) + The regression target for each sample. If `as_frame=True`, `target` + will be a pandas Series. + frame : dataframe of shape (494021, 42) + Only present when `as_frame=True`. Contains `data` and `target`. DESCR : str The full description of the dataset. + feature_names : list + The names of the dataset columns + target_names: list + The names of the target columns (data, target) : tuple if ``return_X_y`` is True .. versionadded:: 0.20 """ data_home = get_data_home(data_home=data_home) - kddcup99 = _fetch_brute_kddcup99(data_home=data_home, - percent10=percent10, - download_if_missing=download_if_missing) + kddcup99 = _fetch_brute_kddcup99( + data_home=data_home, + percent10=percent10, + download_if_missing=download_if_missing + ) data = kddcup99.data target = kddcup99.target + feature_names = kddcup99.feature_names + target_names = kddcup99.target_names if subset == 'SA': s = target == b'normal.' @@ -143,6 +164,7 @@ def fetch_kddcup99(*, subset=None, data_home=None, shuffle=False, # select all samples with positive logged_in attribute: s = data[:, 11] == 1 data = np.c_[data[s, :11], data[s, 12:]] + feature_names = feature_names[:11] + feature_names[12:] target = target[s] data[:, 0] = np.log((data[:, 0] + 0.1).astype(float, copy=False)) @@ -154,15 +176,21 @@ def fetch_kddcup99(*, subset=None, data_home=None, shuffle=False, data = data[s] target = target[s] data = np.c_[data[:, 0], data[:, 4], data[:, 5]] + feature_names = [feature_names[0], feature_names[4], + feature_names[5]] if subset == 'smtp': s = data[:, 2] == b'smtp' data = data[s] target = target[s] data = np.c_[data[:, 0], data[:, 4], data[:, 5]] + feature_names = [feature_names[0], feature_names[4], + feature_names[5]] if subset == 'SF': data = np.c_[data[:, 0], data[:, 2], data[:, 4], data[:, 5]] + feature_names = [feature_names[0], feature_names[2], + feature_names[4], feature_names[5]] if shuffle: data, target = shuffle_method(data, target, random_state=random_state) @@ -174,7 +202,20 @@ def fetch_kddcup99(*, subset=None, data_home=None, shuffle=False, if return_X_y: return data, target - return Bunch(data=data, target=target, DESCR=fdescr) + frame = None + if as_frame: + frame, data, target = _convert_data_dataframe( + "fetch_kddcup99", data, target, feature_names, target_names + ) + + return Bunch( + data=data, + target=target, + frame=frame, + target_names=target_names, + feature_names=feature_names, + DESCR=fdescr, + ) def _fetch_brute_kddcup99(data_home=None, @@ -205,6 +246,10 @@ def _fetch_brute_kddcup99(data_home=None, target : ndarray of shape (494021,) Each value corresponds to one of the 21 attack types or to the label 'normal.'. + feature_names : list + The names of the dataset columns + target_names: list + The names of the target columns DESCR : str Description of the kddcup99 dataset. @@ -224,52 +269,56 @@ def _fetch_brute_kddcup99(data_home=None, targets_path = join(kddcup_dir, "targets") available = exists(samples_path) + dt = [('duration', int), + ('protocol_type', 'S4'), + ('service', 'S11'), + ('flag', 'S6'), + ('src_bytes', int), + ('dst_bytes', int), + ('land', int), + ('wrong_fragment', int), + ('urgent', int), + ('hot', int), + ('num_failed_logins', int), + ('logged_in', int), + ('num_compromised', int), + ('root_shell', int), + ('su_attempted', int), + ('num_root', int), + ('num_file_creations', int), + ('num_shells', int), + ('num_access_files', int), + ('num_outbound_cmds', int), + ('is_host_login', int), + ('is_guest_login', int), + ('count', int), + ('srv_count', int), + ('serror_rate', float), + ('srv_serror_rate', float), + ('rerror_rate', float), + ('srv_rerror_rate', float), + ('same_srv_rate', float), + ('diff_srv_rate', float), + ('srv_diff_host_rate', float), + ('dst_host_count', int), + ('dst_host_srv_count', int), + ('dst_host_same_srv_rate', float), + ('dst_host_diff_srv_rate', float), + ('dst_host_same_src_port_rate', float), + ('dst_host_srv_diff_host_rate', float), + ('dst_host_serror_rate', float), + ('dst_host_srv_serror_rate', float), + ('dst_host_rerror_rate', float), + ('dst_host_srv_rerror_rate', float), + ('labels', 'S16')] + + column_names = [c[0] for c in dt] + target_names = column_names[-1] + feature_names = column_names[:-1] if download_if_missing and not available: _mkdirp(kddcup_dir) logger.info("Downloading %s" % archive.url) _fetch_remote(archive, dirname=kddcup_dir) - dt = [('duration', int), - ('protocol_type', 'S4'), - ('service', 'S11'), - ('flag', 'S6'), - ('src_bytes', int), - ('dst_bytes', int), - ('land', int), - ('wrong_fragment', int), - ('urgent', int), - ('hot', int), - ('num_failed_logins', int), - ('logged_in', int), - ('num_compromised', int), - ('root_shell', int), - ('su_attempted', int), - ('num_root', int), - ('num_file_creations', int), - ('num_shells', int), - ('num_access_files', int), - ('num_outbound_cmds', int), - ('is_host_login', int), - ('is_guest_login', int), - ('count', int), - ('srv_count', int), - ('serror_rate', float), - ('srv_serror_rate', float), - ('rerror_rate', float), - ('srv_rerror_rate', float), - ('same_srv_rate', float), - ('diff_srv_rate', float), - ('srv_diff_host_rate', float), - ('dst_host_count', int), - ('dst_host_srv_count', int), - ('dst_host_same_srv_rate', float), - ('dst_host_diff_srv_rate', float), - ('dst_host_same_src_port_rate', float), - ('dst_host_srv_diff_host_rate', float), - ('dst_host_serror_rate', float), - ('dst_host_srv_serror_rate', float), - ('dst_host_rerror_rate', float), - ('dst_host_srv_rerror_rate', float), - ('labels', 'S16')] DT = np.dtype(dt) logger.debug("extracting archive") archive_path = join(kddcup_dir, archive.filename) @@ -304,7 +353,12 @@ def _fetch_brute_kddcup99(data_home=None, X = joblib.load(samples_path) y = joblib.load(targets_path) - return Bunch(data=X, target=y) + return Bunch( + data=X, + target=y, + feature_names=feature_names, + target_names=[target_names], + ) def _mkdirp(d): diff --git a/sklearn/datasets/descr/kddcup99.rst b/sklearn/datasets/descr/kddcup99.rst index 00427ac08b748..8bdcccf7973ea 100644 --- a/sklearn/datasets/descr/kddcup99.rst +++ b/sklearn/datasets/descr/kddcup99.rst @@ -78,8 +78,9 @@ General KDD structure : :func:`sklearn.datasets.fetch_kddcup99` will load the kddcup99 dataset; it returns a dictionary-like object with the feature matrix in the ``data`` member -and the target values in ``target``. The dataset will be downloaded from the -web if necessary. +and the target values in ``target``. The "as_frame" optional argument converts +``data`` into a pandas DataFrame and ``target`` into a pandas Series. The +dataset will be downloaded from the web if necessary. .. topic: References @@ -92,4 +93,3 @@ web if necessary. discounting learning algorithms. In Proceedings of the sixth ACM SIGKDD international conference on Knowledge discovery and data mining, pages 320-324. ACM Press, 2000. -
diff --git a/sklearn/datasets/tests/test_kddcup99.py b/sklearn/datasets/tests/test_kddcup99.py index 414c1bab1acd5..11adaacfaae20 100644 --- a/sklearn/datasets/tests/test_kddcup99.py +++ b/sklearn/datasets/tests/test_kddcup99.py @@ -6,41 +6,56 @@ is too big to use in unit-testing. """ -from sklearn.datasets.tests.test_common import check_return_X_y from functools import partial +import pytest +from sklearn.datasets import fetch_kddcup99 +from sklearn.datasets.tests.test_common import check_as_frame +from sklearn.datasets.tests.test_common import check_pandas_dependency_message +from sklearn.datasets.tests.test_common import check_return_X_y -def test_percent10(fetch_kddcup99_fxt): - data = fetch_kddcup99_fxt() - - assert data.data.shape == (494021, 41) - assert data.target.shape == (494021,) - - data_shuffled = fetch_kddcup99_fxt(shuffle=True, random_state=0) - assert data.data.shape == data_shuffled.data.shape - assert data.target.shape == data_shuffled.target.shape - data = fetch_kddcup99_fxt(subset='SA') - assert data.data.shape == (100655, 41) - assert data.target.shape == (100655,) [email protected]("as_frame", [True, False]) [email protected]( + "subset, n_samples, n_features", + [(None, 494021, 41), + ("SA", 100655, 41), + ("SF", 73237, 4), + ("http", 58725, 3), + ("smtp", 9571, 3)] +) +def test_fetch_kddcup99_percent10( + fetch_kddcup99_fxt, as_frame, subset, n_samples, n_features +): + data = fetch_kddcup99_fxt(subset=subset, as_frame=as_frame) + assert data.data.shape == (n_samples, n_features) + assert data.target.shape == (n_samples,) + if as_frame: + assert data.frame.shape == (n_samples, n_features + 1) + + +def test_fetch_kddcup99_return_X_y(fetch_kddcup99_fxt): + fetch_func = partial(fetch_kddcup99_fxt, subset='smtp') + data = fetch_func() + check_return_X_y(data, fetch_func) - data = fetch_kddcup99_fxt(subset='SF') - assert data.data.shape == (73237, 4) - assert data.target.shape == (73237,) - data = fetch_kddcup99_fxt(subset='http') - assert data.data.shape == (58725, 3) - assert data.target.shape == (58725,) +def test_fetch_kddcup99_as_frame(fetch_kddcup99_fxt): + bunch = fetch_kddcup99_fxt() + check_as_frame(bunch, fetch_kddcup99_fxt) - data = fetch_kddcup99_fxt(subset='smtp') - assert data.data.shape == (9571, 3) - assert data.target.shape == (9571,) - fetch_func = partial(fetch_kddcup99_fxt, subset='smtp') - check_return_X_y(data, fetch_func) +def test_fetch_kddcup99_shuffle(fetch_kddcup99_fxt): + dataset = fetch_kddcup99_fxt( + random_state=0, subset='SA', percent10=True, + ) + dataset_shuffled = fetch_kddcup99_fxt( + random_state=0, subset='SA', shuffle=True, percent10=True, + ) + assert set(dataset['target']) == set(dataset_shuffled['target']) + assert dataset_shuffled.data.shape == dataset.data.shape + assert dataset_shuffled.target.shape == dataset.target.shape -def test_shuffle(fetch_kddcup99_fxt): - dataset = fetch_kddcup99_fxt(random_state=0, subset='SA', shuffle=True, - percent10=True) - assert(any(dataset.target[-100:] == b'normal.')) +def test_pandas_dependency_message(fetch_kddcup99_fxt, hide_available_pandas): + check_pandas_dependency_message(fetch_kddcup99)
[ { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex c6ef6e5994cdf..9294bab242432 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -112,7 +112,15 @@ Changelog\n - |Enhancement| :func:`datasets.fetch_covtype` now now supports the optional\n argument `as_frame`; when it is set to True, the returned Bunch object's\n `data` and `frame` members are pandas DataFrames, and the `target` member is\n- a pandas Series. :pr:`17491` by :user:`Alex Liang <tianchuliang>`.\n+ a pandas Series.\n+ :pr:`17491` by :user:`Alex Liang <tianchuliang>`.\n+\n+- |Enhancement| :func:`datasets.fetch_kddcup99` now now supports the optional\n+ argument `as_frame`; when it is set to True, the returned Bunch object's\n+ `data` and `frame` members are pandas DataFrames, and the `target` member is\n+ a pandas Series.\n+ :pr:`18280` by :user:`Alex Liang <tianchuliang>` and\n+ `Guillaume Lemaitre`_.\n \n - |API| The default value of `as_frame` in :func:`datasets.fetch_openml` is\n changed from False to 'auto'.\n" } ]
0.24
138dd7b88f1634447f838bc58088e594ffaf5549
[]
[ "sklearn/datasets/tests/test_kddcup99.py::test_pandas_dependency_message" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex c6ef6e5994cdf..9294bab242432 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -112,7 +112,15 @@ Changelog\n - |Enhancement| :func:`datasets.fetch_covtype` now now supports the optional\n argument `as_frame`; when it is set to True, the returned Bunch object's\n `data` and `frame` members are pandas DataFrames, and the `target` member is\n- a pandas Series. :pr:`<PRID>` by :user:`<NAME>`.\n+ a pandas Series.\n+ :pr:`<PRID>` by :user:`<NAME>`.\n+\n+- |Enhancement| :func:`datasets.fetch_kddcup99` now now supports the optional\n+ argument `as_frame`; when it is set to True, the returned Bunch object's\n+ `data` and `frame` members are pandas DataFrames, and the `target` member is\n+ a pandas Series.\n+ :pr:`<PRID>` by :user:`<NAME>` and\n+ `Guillaume Lemaitre`_.\n \n - |API| The default value of `as_frame` in :func:`datasets.fetch_openml` is\n changed from False to 'auto'.\n" } ]
diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index c6ef6e5994cdf..9294bab242432 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -112,7 +112,15 @@ Changelog - |Enhancement| :func:`datasets.fetch_covtype` now now supports the optional argument `as_frame`; when it is set to True, the returned Bunch object's `data` and `frame` members are pandas DataFrames, and the `target` member is - a pandas Series. :pr:`<PRID>` by :user:`<NAME>`. + a pandas Series. + :pr:`<PRID>` by :user:`<NAME>`. + +- |Enhancement| :func:`datasets.fetch_kddcup99` now now supports the optional + argument `as_frame`; when it is set to True, the returned Bunch object's + `data` and `frame` members are pandas DataFrames, and the `target` member is + a pandas Series. + :pr:`<PRID>` by :user:`<NAME>` and + `Guillaume Lemaitre`_. - |API| The default value of `as_frame` in :func:`datasets.fetch_openml` is changed from False to 'auto'.
scikit-learn/scikit-learn
scikit-learn__scikit-learn-11064
https://github.com/scikit-learn/scikit-learn/pull/11064
diff --git a/doc/modules/decomposition.rst b/doc/modules/decomposition.rst index f6296e25250db..6d441004f8ae6 100644 --- a/doc/modules/decomposition.rst +++ b/doc/modules/decomposition.rst @@ -622,11 +622,18 @@ of heteroscedastic noise: :align: center :scale: 75% +Factor Analysis is often followed by a rotation of the factors (with the +parameter `rotation`), usually to improve interpretability. For example, +Varimax rotation maximizes the sum of the variances of the squared loadings, +i.e., it tends to produce sparser factors, which are influenced by only a few +features each (the "simple structure"). See e.g., the first example below. .. topic:: Examples: + * :ref:`sphx_glr_auto_examples_decomposition_plot_varimax_fa.py` * :ref:`sphx_glr_auto_examples_decomposition_plot_pca_vs_fa_model_selection.py` + .. _ICA: Independent component analysis (ICA) @@ -959,6 +966,9 @@ when data can be fetched sequentially. <http://www.columbia.edu/~jwp2128/Papers/HoffmanBleiWangPaisley2013.pdf>`_ M. Hoffman, D. Blei, C. Wang, J. Paisley, 2013 + * `"The varimax criterion for analytic rotation in factor analysis" + <https://link.springer.com/article/10.1007%2FBF02289233>`_ + H. F. Kaiser, 1958 See also :ref:`nca_dim_reduction` for dimensionality reduction with Neighborhood Components Analysis. diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index e637e367d401e..1c71bb280994d 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -84,6 +84,10 @@ Changelog redundant with the `dictionary` attribute and constructor parameter. :pr:`17679` by :user:`Xavier Dupré <sdpython>`. +- |Enhancement| :func:`decomposition.FactorAnalysis` now supports the optional + argument `rotation`, which can take the value `None`, `'varimax'` or `'quartimax'.` + :pr:`11064` by :user:`Jona Sassenhagen <jona-sassenhagen>`. + :mod:`sklearn.ensemble` ....................... diff --git a/examples/decomposition/plot_varimax_fa.py b/examples/decomposition/plot_varimax_fa.py new file mode 100644 index 0000000000000..3f850fd3b545d --- /dev/null +++ b/examples/decomposition/plot_varimax_fa.py @@ -0,0 +1,80 @@ +""" +=============================================================== +Factor Analysis (with rotation) to visualize patterns +=============================================================== + +Investigating the Iris dataset, we see that sepal length, petal +length and petal width are highly correlated. Sepal width is +less redundant. Matrix decomposition techniques can uncover +these latent patterns. Applying rotations to the resulting +components does not inherently improve the predictve value +of the derived latent space, but can help visualise their +structure; here, for example, the varimax rotation, which +is found by maximizing the squared variances of the weights, +finds a structure where the second component only loads +positively on sepal width. +""" + +# Authors: Jona Sassenhagen +# License: BSD 3 clause + +import matplotlib.pyplot as plt +import numpy as np + +from sklearn.decomposition import FactorAnalysis, PCA +from sklearn.preprocessing import StandardScaler +from sklearn.datasets import load_iris + +print(__doc__) + +# %% +# Load Iris data +data = load_iris() +X = StandardScaler().fit_transform(data["data"]) +feature_names = data["feature_names"] + +# %% +# Plot covariance of Iris features +ax = plt.axes() + +im = ax.imshow(np.corrcoef(X.T), cmap="RdBu_r", vmin=-1, vmax=1) + +ax.set_xticks([0, 1, 2, 3]) +ax.set_xticklabels(list(feature_names), rotation=90) +ax.set_yticks([0, 1, 2, 3]) +ax.set_yticklabels(list(feature_names)) + +plt.colorbar(im).ax.set_ylabel("$r$", rotation=0) +ax.set_title("Iris feature correlation matrix") +plt.tight_layout() + +# %% +# Run factor analysis with Varimax rotation +n_comps = 2 + +methods = [('PCA', PCA()), + ('Unrotated FA', FactorAnalysis()), + ('Varimax FA', FactorAnalysis(rotation='varimax'))] +fig, axes = plt.subplots(ncols=len(methods), figsize=(10, 8)) + +for ax, (method, fa) in zip(axes, methods): + fa.set_params(n_components=n_comps) + fa.fit(X) + + components = fa.components_.T + print("\n\n %s :\n" % method) + print(components) + + vmax = np.abs(components).max() + ax.imshow(components, cmap="RdBu_r", vmax=vmax, vmin=-vmax) + ax.set_yticks(np.arange(len(feature_names))) + if ax.is_first_col(): + ax.set_yticklabels(feature_names) + else: + ax.set_yticklabels([]) + ax.set_title(str(method)) + ax.set_xticks([0, 1]) + ax.set_xticklabels(["Comp. 1", "Comp. 2"]) +fig.suptitle("Factors") +plt.tight_layout() +plt.show() diff --git a/sklearn/decomposition/_factor_analysis.py b/sklearn/decomposition/_factor_analysis.py index cc0178b70e447..51dda4625ab27 100644 --- a/sklearn/decomposition/_factor_analysis.py +++ b/sklearn/decomposition/_factor_analysis.py @@ -89,6 +89,15 @@ class FactorAnalysis(TransformerMixin, BaseEstimator): Number of iterations for the power method. 3 by default. Only used if ``svd_method`` equals 'randomized' + rotation : None | 'varimax' | 'quartimax' + If not None, apply the indicated rotation. Currently, varimax and + quartimax are implemented. See + `"The varimax criterion for analytic rotation in factor analysis" + <https://link.springer.com/article/10.1007%2FBF02289233>`_ + H. F. Kaiser, 1958 + + .. versionadded:: 0.24 + random_state : int, RandomState instance, default=0 Only used when ``svd_method`` equals 'randomized'. Pass an int for reproducible results across multiple function calls. @@ -142,7 +151,7 @@ class FactorAnalysis(TransformerMixin, BaseEstimator): def __init__(self, n_components=None, *, tol=1e-2, copy=True, max_iter=1000, noise_variance_init=None, svd_method='randomized', - iterated_power=3, random_state=0): + iterated_power=3, rotation=None, random_state=0): self.n_components = n_components self.copy = copy self.tol = tol @@ -155,6 +164,7 @@ def __init__(self, n_components=None, *, tol=1e-2, copy=True, self.noise_variance_init = noise_variance_init self.iterated_power = iterated_power self.random_state = random_state + self.rotation = rotation def fit(self, X, y=None): """Fit the FactorAnalysis model to X using SVD based approach @@ -176,6 +186,7 @@ def fit(self, X, y=None): n_components = self.n_components if n_components is None: n_components = n_features + self.mean_ = np.mean(X, axis=0) X -= self.mean_ @@ -243,6 +254,8 @@ def my_svd(X): ConvergenceWarning) self.components_ = W + if self.rotation is not None: + self.components_ = self._rotate(W) self.noise_variance_ = psi self.loglike_ = loglike self.n_iter_ = i + 1 @@ -362,3 +375,38 @@ def score(self, X, y=None): Average log-likelihood of the samples under the current model """ return np.mean(self.score_samples(X)) + + def _rotate(self, components, n_components=None, tol=1e-6): + "Rotate the factor analysis solution." + # note that tol is not exposed + implemented = ("varimax", "quartimax") + method = self.rotation + if method in implemented: + return _ortho_rotation(components.T, method=method, + tol=tol)[:self.n_components] + else: + raise ValueError("'method' must be in %s, not %s" + % (implemented, method)) + + +def _ortho_rotation(components, method='varimax', tol=1e-6, max_iter=100): + """Return rotated components.""" + nrow, ncol = components.shape + rotation_matrix = np.eye(ncol) + var = 0 + + for _ in range(max_iter): + comp_rot = np.dot(components, rotation_matrix) + if method == "varimax": + tmp = comp_rot * np.transpose((comp_rot ** 2).sum(axis=0) / nrow) + elif method == "quartimax": + tmp = 0 + u, s, v = np.linalg.svd( + np.dot(components.T, comp_rot ** 3 - tmp)) + rotation_matrix = np.dot(u, v) + var_new = np.sum(s) + if var != 0 and var_new < var * (1 + tol): + break + var = var_new + + return np.dot(components, rotation_matrix).T
diff --git a/sklearn/decomposition/tests/test_factor_analysis.py b/sklearn/decomposition/tests/test_factor_analysis.py index 128c1d04fb405..f889e49ea4a3a 100644 --- a/sklearn/decomposition/tests/test_factor_analysis.py +++ b/sklearn/decomposition/tests/test_factor_analysis.py @@ -2,15 +2,19 @@ # Alexandre Gramfort <[email protected]> # License: BSD3 +from itertools import combinations + import numpy as np import pytest from sklearn.utils._testing import assert_warns +from sklearn.utils._testing import assert_raises from sklearn.utils._testing import assert_almost_equal from sklearn.utils._testing import assert_array_almost_equal from sklearn.exceptions import ConvergenceWarning from sklearn.decomposition import FactorAnalysis from sklearn.utils._testing import ignore_warnings +from sklearn.decomposition._factor_analysis import _ortho_rotation # Ignore warnings from switching to more power iterations in randomized_svd @@ -83,3 +87,33 @@ def test_factor_analysis(): precision = fa.get_precision() assert_array_almost_equal(np.dot(cov, precision), np.eye(X.shape[1]), 12) + + # test rotation + n_components = 2 + + results, projections = {}, {} + for method in (None, "varimax", 'quartimax'): + fa_var = FactorAnalysis(n_components=n_components, + rotation=method) + results[method] = fa_var.fit_transform(X) + projections[method] = fa_var.get_covariance() + for rot1, rot2 in combinations([None, 'varimax', 'quartimax'], 2): + assert not np.allclose(results[rot1], results[rot2]) + assert np.allclose(projections[rot1], projections[rot2], atol=3) + + assert_raises(ValueError, + FactorAnalysis(rotation='not_implemented').fit_transform, X) + + # test against R's psych::principal with rotate="varimax" + # (i.e., the values below stem from rotating the components in R) + # R's factor analysis returns quite different values; therefore, we only + # test the rotation itself + factors = np.array( + [[0.89421016, -0.35854928, -0.27770122, 0.03773647], + [-0.45081822, -0.89132754, 0.0932195, -0.01787973], + [0.99500666, -0.02031465, 0.05426497, -0.11539407], + [0.96822861, -0.06299656, 0.24411001, 0.07540887]]) + r_solution = np.array([[0.962, 0.052], [-0.141, 0.989], + [0.949, -0.300], [0.937, -0.251]]) + rotated = _ortho_rotation(factors[:, :n_components], method='varimax').T + assert_array_almost_equal(np.abs(rotated), np.abs(r_solution), decimal=3)
[ { "path": "doc/modules/decomposition.rst", "old_path": "a/doc/modules/decomposition.rst", "new_path": "b/doc/modules/decomposition.rst", "metadata": "diff --git a/doc/modules/decomposition.rst b/doc/modules/decomposition.rst\nindex f6296e25250db..6d441004f8ae6 100644\n--- a/doc/modules/decomposition.rst\n+++ b/doc/modules/decomposition.rst\n@@ -622,11 +622,18 @@ of heteroscedastic noise:\n :align: center\n :scale: 75%\n \n+Factor Analysis is often followed by a rotation of the factors (with the\n+parameter `rotation`), usually to improve interpretability. For example,\n+Varimax rotation maximizes the sum of the variances of the squared loadings,\n+i.e., it tends to produce sparser factors, which are influenced by only a few\n+features each (the \"simple structure\"). See e.g., the first example below.\n \n .. topic:: Examples:\n \n+ * :ref:`sphx_glr_auto_examples_decomposition_plot_varimax_fa.py`\n * :ref:`sphx_glr_auto_examples_decomposition_plot_pca_vs_fa_model_selection.py`\n \n+\n .. _ICA:\n \n Independent component analysis (ICA)\n@@ -959,6 +966,9 @@ when data can be fetched sequentially.\n <http://www.columbia.edu/~jwp2128/Papers/HoffmanBleiWangPaisley2013.pdf>`_\n M. Hoffman, D. Blei, C. Wang, J. Paisley, 2013\n \n+ * `\"The varimax criterion for analytic rotation in factor analysis\"\n+ <https://link.springer.com/article/10.1007%2FBF02289233>`_\n+ H. F. Kaiser, 1958\n \n See also :ref:`nca_dim_reduction` for dimensionality reduction with\n Neighborhood Components Analysis.\n" }, { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex e637e367d401e..1c71bb280994d 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -84,6 +84,10 @@ Changelog\n redundant with the `dictionary` attribute and constructor parameter.\n :pr:`17679` by :user:`Xavier Dupré <sdpython>`.\n \n+- |Enhancement| :func:`decomposition.FactorAnalysis` now supports the optional\n+ argument `rotation`, which can take the value `None`, `'varimax'` or `'quartimax'.`\n+ :pr:`11064` by :user:`Jona Sassenhagen <jona-sassenhagen>`.\n+\n :mod:`sklearn.ensemble`\n .......................\n \n" } ]
0.24
52cd1104ee7c5de25e5e16e100c0d74bda8e92c1
[]
[ "sklearn/decomposition/tests/test_factor_analysis.py::test_factor_analysis" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [ { "type": "file", "name": "examples/decomposition/plot_varimax_fa.py" } ] }
[ { "path": "doc/modules/decomposition.rst", "old_path": "a/doc/modules/decomposition.rst", "new_path": "b/doc/modules/decomposition.rst", "metadata": "diff --git a/doc/modules/decomposition.rst b/doc/modules/decomposition.rst\nindex f6296e25250db..6d441004f8ae6 100644\n--- a/doc/modules/decomposition.rst\n+++ b/doc/modules/decomposition.rst\n@@ -622,11 +622,18 @@ of heteroscedastic noise:\n :align: center\n :scale: 75%\n \n+Factor Analysis is often followed by a rotation of the factors (with the\n+parameter `rotation`), usually to improve interpretability. For example,\n+Varimax rotation maximizes the sum of the variances of the squared loadings,\n+i.e., it tends to produce sparser factors, which are influenced by only a few\n+features each (the \"simple structure\"). See e.g., the first example below.\n \n .. topic:: Examples:\n \n+ * :ref:`sphx_glr_auto_examples_decomposition_plot_varimax_fa.py`\n * :ref:`sphx_glr_auto_examples_decomposition_plot_pca_vs_fa_model_selection.py`\n \n+\n .. _ICA:\n \n Independent component analysis (ICA)\n@@ -959,6 +966,9 @@ when data can be fetched sequentially.\n <http://www.columbia.edu/~jwp2128/Papers/HoffmanBleiWangPaisley2013.pdf>`_\n M. Hoffman, D. Blei, C. Wang, J. Paisley, 2013\n \n+ * `\"The varimax criterion for analytic rotation in factor analysis\"\n+ <https://link.springer.com/article/10.1007%2FBF02289233>`_\n+ H. F. Kaiser, 1958\n \n See also :ref:`nca_dim_reduction` for dimensionality reduction with\n Neighborhood Components Analysis.\n" }, { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex e637e367d401e..1c71bb280994d 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -84,6 +84,10 @@ Changelog\n redundant with the `dictionary` attribute and constructor parameter.\n :pr:`<PRID>` by :user:`<NAME>`.\n \n+- |Enhancement| :func:`decomposition.FactorAnalysis` now supports the optional\n+ argument `rotation`, which can take the value `None`, `'varimax'` or `'quartimax'.`\n+ :pr:`<PRID>` by :user:`<NAME>`.\n+\n :mod:`sklearn.ensemble`\n .......................\n \n" } ]
diff --git a/doc/modules/decomposition.rst b/doc/modules/decomposition.rst index f6296e25250db..6d441004f8ae6 100644 --- a/doc/modules/decomposition.rst +++ b/doc/modules/decomposition.rst @@ -622,11 +622,18 @@ of heteroscedastic noise: :align: center :scale: 75% +Factor Analysis is often followed by a rotation of the factors (with the +parameter `rotation`), usually to improve interpretability. For example, +Varimax rotation maximizes the sum of the variances of the squared loadings, +i.e., it tends to produce sparser factors, which are influenced by only a few +features each (the "simple structure"). See e.g., the first example below. .. topic:: Examples: + * :ref:`sphx_glr_auto_examples_decomposition_plot_varimax_fa.py` * :ref:`sphx_glr_auto_examples_decomposition_plot_pca_vs_fa_model_selection.py` + .. _ICA: Independent component analysis (ICA) @@ -959,6 +966,9 @@ when data can be fetched sequentially. <http://www.columbia.edu/~jwp2128/Papers/HoffmanBleiWangPaisley2013.pdf>`_ M. Hoffman, D. Blei, C. Wang, J. Paisley, 2013 + * `"The varimax criterion for analytic rotation in factor analysis" + <https://link.springer.com/article/10.1007%2FBF02289233>`_ + H. F. Kaiser, 1958 See also :ref:`nca_dim_reduction` for dimensionality reduction with Neighborhood Components Analysis. diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index e637e367d401e..1c71bb280994d 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -84,6 +84,10 @@ Changelog redundant with the `dictionary` attribute and constructor parameter. :pr:`<PRID>` by :user:`<NAME>`. +- |Enhancement| :func:`decomposition.FactorAnalysis` now supports the optional + argument `rotation`, which can take the value `None`, `'varimax'` or `'quartimax'.` + :pr:`<PRID>` by :user:`<NAME>`. + :mod:`sklearn.ensemble` ....................... If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names: [{'type': 'file', 'name': 'examples/decomposition/plot_varimax_fa.py'}]
scikit-learn/scikit-learn
scikit-learn__scikit-learn-14446
https://github.com/scikit-learn/scikit-learn/pull/14446
diff --git a/doc/modules/lda_qda.rst b/doc/modules/lda_qda.rst index c3ac94dedefa9..e8f25d2c66930 100644 --- a/doc/modules/lda_qda.rst +++ b/doc/modules/lda_qda.rst @@ -163,8 +163,8 @@ transformed class means :math:`\mu^*_k`). This :math:`L` corresponds to the :func:`~discriminant_analysis.LinearDiscriminantAnalysis.transform` method. See [1]_ for more details. -Shrinkage -========= +Shrinkage and Covariance Estimator +================================== Shrinkage is a form of regularization used to improve the estimation of covariance matrices in situations where the number of training samples is @@ -187,12 +187,33 @@ an estimate for the covariance matrix). Setting this parameter to a value between these two extrema will estimate a shrunk version of the covariance matrix. +The shrinked Ledoit and Wolf estimator of covariance may not always be the +best choice. For example if the distribution of the data +is normally distributed, the +Oracle Shrinkage Approximating estimator :class:`sklearn.covariance.OAS` +yields a smaller Mean Squared Error than the one given by Ledoit and Wolf's +formula used with shrinkage="auto". In LDA, the data are assumed to be gaussian +conditionally to the class. If these assumptions hold, using LDA with +the OAS estimator of covariance will yield a better classification +accuracy than if Ledoit and Wolf or the empirical covariance estimator is used. + +The covariance estimator can be chosen using with the ``covariance_estimator`` +parameter of the :class:`discriminant_analysis.LinearDiscriminantAnalysis` +class. A covariance estimator should have a :term:`fit` method and a +``covariance_`` attribute like all covariance estimators in the +:mod:`sklearn.covariance` module. + + .. |shrinkage| image:: ../auto_examples/classification/images/sphx_glr_plot_lda_001.png :target: ../auto_examples/classification/plot_lda.html :scale: 75 .. centered:: |shrinkage| +.. topic:: Examples: + + :ref:`sphx_glr_auto_examples_classification_plot_lda.py`: Comparison of LDA classifiers + with Empirical, Ledoit Wolf and OAS covariance estimator. Estimation algorithms ===================== @@ -220,7 +241,8 @@ and the SVD of the class-wise mean vectors. The 'lsqr' solver is an efficient algorithm that only works for classification. It needs to explicitly compute the covariance matrix -:math:`\Sigma`, and supports shrinkage. This solver computes the coefficients +:math:`\Sigma`, and supports shrinkage and custom covariance estimators. +This solver computes the coefficients :math:`\omega_k = \Sigma^{-1}\mu_k` by solving for :math:`\Sigma \omega = \mu_k`, thus avoiding the explicit computation of the inverse :math:`\Sigma^{-1}`. @@ -231,11 +253,6 @@ transform, and it supports shrinkage. However, the 'eigen' solver needs to compute the covariance matrix, so it might not be suitable for situations with a high number of features. -.. topic:: Examples: - - :ref:`sphx_glr_auto_examples_classification_plot_lda.py`: Comparison of LDA classifiers - with and without shrinkage. - .. topic:: References: .. [1] "The Elements of Statistical Learning", Hastie T., Tibshirani R., diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index e8225811194cc..98ccc5d143bcb 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -180,6 +180,13 @@ Changelog :func:`decomposition.NMF.non_negative_factorization`. :pr:`17414` by :user:`Bharat Raghunathan <Bharat123rox>`. +:mod:`sklearn.discriminant_analysis` +.................................... + +- |Enhancement| :class:`discriminant_analysis.LinearDiscriminantAnalysis` can + now use custom covariance estimate by setting the `covariance_estimator` + parameter. :pr:`14446` by :user:`Hugo Richard <hugorichard>` + :mod:`sklearn.ensemble` ....................... diff --git a/examples/classification/plot_lda.py b/examples/classification/plot_lda.py index 18dfbe37b804d..ad16e7b0d2efa 100644 --- a/examples/classification/plot_lda.py +++ b/examples/classification/plot_lda.py @@ -1,15 +1,17 @@ """ -==================================================================== -Normal and Shrinkage Linear Discriminant Analysis for classification -==================================================================== +=========================================================================== +Normal, Ledoit-Wolf and OAS Linear Discriminant Analysis for classification +=========================================================================== -Shows how shrinkage improves classification. +This example illustrates how the Ledoit-Wolf and Oracle Shrinkage +Approximating (OAS) estimators of covariance can improve classification. """ import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import make_blobs from sklearn.discriminant_analysis import LinearDiscriminantAnalysis +from sklearn.covariance import OAS n_train = 20 # samples for training @@ -35,34 +37,45 @@ def generate_data(n_samples, n_features): X = np.hstack([X, np.random.randn(n_samples, n_features - 1)]) return X, y -acc_clf1, acc_clf2 = [], [] + +acc_clf1, acc_clf2, acc_clf3 = [], [], [] n_features_range = range(1, n_features_max + 1, step) for n_features in n_features_range: - score_clf1, score_clf2 = 0, 0 + score_clf1, score_clf2, score_clf3 = 0, 0, 0 for _ in range(n_averages): X, y = generate_data(n_train, n_features) - clf1 = LinearDiscriminantAnalysis(solver='lsqr', shrinkage='auto').fit(X, y) - clf2 = LinearDiscriminantAnalysis(solver='lsqr', shrinkage=None).fit(X, y) + clf1 = LinearDiscriminantAnalysis(solver='lsqr', + shrinkage='auto').fit(X, y) + clf2 = LinearDiscriminantAnalysis(solver='lsqr', + shrinkage=None).fit(X, y) + oa = OAS(store_precision=False, assume_centered=False) + clf3 = LinearDiscriminantAnalysis(solver='lsqr', + covariance_estimator=oa).fit(X, y) X, y = generate_data(n_test, n_features) score_clf1 += clf1.score(X, y) score_clf2 += clf2.score(X, y) + score_clf3 += clf3.score(X, y) acc_clf1.append(score_clf1 / n_averages) acc_clf2.append(score_clf2 / n_averages) + acc_clf3.append(score_clf3 / n_averages) features_samples_ratio = np.array(n_features_range) / n_train plt.plot(features_samples_ratio, acc_clf1, linewidth=2, - label="Linear Discriminant Analysis with shrinkage", color='navy') + label="Linear Discriminant Analysis with Ledoit Wolf", color='navy') plt.plot(features_samples_ratio, acc_clf2, linewidth=2, label="Linear Discriminant Analysis", color='gold') +plt.plot(features_samples_ratio, acc_clf3, linewidth=2, + label="Linear Discriminant Analysis with OAS", color='red') plt.xlabel('n_features / n_samples') plt.ylabel('Classification accuracy') -plt.legend(loc=1, prop={'size': 12}) -plt.suptitle('Linear Discriminant Analysis vs. \ -shrinkage Linear Discriminant Analysis (1 discriminative feature)') +plt.legend(loc=3, prop={'size': 12}) +plt.suptitle('Linear Discriminant Analysis vs. ' + '\n' + + 'Shrinkage Linear Discriminant Analysis vs. ' + '\n' + + 'OAS Linear Discriminant Analysis (1 discriminative feature)') plt.show() diff --git a/sklearn/discriminant_analysis.py b/sklearn/discriminant_analysis.py index 2ce91f1540fdd..1e82578e2693b 100644 --- a/sklearn/discriminant_analysis.py +++ b/sklearn/discriminant_analysis.py @@ -29,9 +29,8 @@ __all__ = ['LinearDiscriminantAnalysis', 'QuadraticDiscriminantAnalysis'] -def _cov(X, shrinkage=None): - """Estimate covariance matrix (using optional shrinkage). - +def _cov(X, shrinkage=None, covariance_estimator=None): + """Estimate covariance matrix (using optional covariance_estimator). Parameters ---------- X : array-like of shape (n_samples, n_features) @@ -43,29 +42,52 @@ def _cov(X, shrinkage=None): - 'auto': automatic shrinkage using the Ledoit-Wolf lemma. - float between 0 and 1: fixed shrinkage parameter. + Shrinkage parameter is ignored if `covariance_estimator` + is not None. + + covariance_estimator : estimator, default=None + If not None, `covariance_estimator` is used to estimate + the covariance matrices instead of relying on the empirical + covariance estimator (with potential shrinkage). + The object should have a fit method and a ``covariance_`` attribute + like the estimators in :mod:`sklearn.covariance``. + if None the shrinkage parameter drives the estimate. + + .. versionadded:: 0.24 + Returns ------- s : ndarray of shape (n_features, n_features) Estimated covariance matrix. """ - shrinkage = "empirical" if shrinkage is None else shrinkage - if isinstance(shrinkage, str): - if shrinkage == 'auto': - sc = StandardScaler() # standardize features - X = sc.fit_transform(X) - s = ledoit_wolf(X)[0] - # rescale - s = sc.scale_[:, np.newaxis] * s * sc.scale_[np.newaxis, :] - elif shrinkage == 'empirical': - s = empirical_covariance(X) + if covariance_estimator is None: + shrinkage = "empirical" if shrinkage is None else shrinkage + if isinstance(shrinkage, str): + if shrinkage == 'auto': + sc = StandardScaler() # standardize features + X = sc.fit_transform(X) + s = ledoit_wolf(X)[0] + # rescale + s = sc.scale_[:, np.newaxis] * s * sc.scale_[np.newaxis, :] + elif shrinkage == 'empirical': + s = empirical_covariance(X) + else: + raise ValueError('unknown shrinkage parameter') + elif isinstance(shrinkage, float) or isinstance(shrinkage, int): + if shrinkage < 0 or shrinkage > 1: + raise ValueError('shrinkage parameter must be between 0 and 1') + s = shrunk_covariance(empirical_covariance(X), shrinkage) else: - raise ValueError('unknown shrinkage parameter') - elif isinstance(shrinkage, float) or isinstance(shrinkage, int): - if shrinkage < 0 or shrinkage > 1: - raise ValueError('shrinkage parameter must be between 0 and 1') - s = shrunk_covariance(empirical_covariance(X), shrinkage) + raise TypeError('shrinkage must be a float or a string') else: - raise TypeError('shrinkage must be of string or int type') + if shrinkage is not None and shrinkage != 0: + raise ValueError("covariance_estimator and shrinkage parameters " + "are not None. Only one of the two can be set.") + covariance_estimator.fit(X) + if not hasattr(covariance_estimator, 'covariance_'): + raise ValueError("%s does not have a covariance_ attribute" % + covariance_estimator.__class__.__name__) + s = covariance_estimator.covariance_ return s @@ -93,7 +115,7 @@ def _class_means(X, y): return means -def _class_cov(X, y, priors, shrinkage=None): +def _class_cov(X, y, priors, shrinkage=None, covariance_estimator=None): """Compute weighted within-class covariance matrix. The per-class covariance are weighted by the class priors. @@ -115,6 +137,18 @@ def _class_cov(X, y, priors, shrinkage=None): - 'auto': automatic shrinkage using the Ledoit-Wolf lemma. - float between 0 and 1: fixed shrinkage parameter. + Shrinkage parameter is ignored if `covariance_estimator` is not None. + + covariance_estimator : estimator, default=None + If not None, `covariance_estimator` is used to estimate + the covariance matrices instead of relying the empirical + covariance estimator (with potential shrinkage). + The object should have a fit method and a ``covariance_`` attribute + like the estimators in sklearn.covariance. + If None, the shrinkage parameter drives the estimate. + + .. versionadded:: 0.24 + Returns ------- cov : array-like of shape (n_features, n_features) @@ -124,7 +158,8 @@ def _class_cov(X, y, priors, shrinkage=None): cov = np.zeros(shape=(X.shape[1], X.shape[1])) for idx, group in enumerate(classes): Xg = X[y == group, :] - cov += priors[idx] * np.atleast_2d(_cov(Xg, shrinkage)) + cov += priors[idx] * np.atleast_2d( + _cov(Xg, shrinkage, covariance_estimator)) return cov @@ -155,8 +190,10 @@ class LinearDiscriminantAnalysis(LinearClassifierMixin, - 'svd': Singular value decomposition (default). Does not compute the covariance matrix, therefore this solver is recommended for data with a large number of features. - - 'lsqr': Least squares solution, can be combined with shrinkage. - - 'eigen': Eigenvalue decomposition, can be combined with shrinkage. + - 'lsqr': Least squares solution. + Can be combined with shrinkage or custom covariance estimator. + - 'eigen': Eigenvalue decomposition. + Can be combined with shrinkage or custom covariance estimator. shrinkage : 'auto' or float, default=None Shrinkage parameter, possible values: @@ -164,6 +201,7 @@ class LinearDiscriminantAnalysis(LinearClassifierMixin, - 'auto': automatic shrinkage using the Ledoit-Wolf lemma. - float between 0 and 1: fixed shrinkage parameter. + This should be left to None if `covariance_estimator` is used. Note that shrinkage works only with 'lsqr' and 'eigen' solvers. priors : array-like of shape (n_classes,), default=None @@ -191,6 +229,20 @@ class LinearDiscriminantAnalysis(LinearClassifierMixin, .. versionadded:: 0.17 + covariance_estimator : covariance estimator, default=None + If not None, `covariance_estimator` is used to estimate + the covariance matrices instead of relying on the empirical + covariance estimator (with potential shrinkage). + The object should have a fit method and a ``covariance_`` attribute + like the estimators in :mod:`sklearn.covariance`. + if None the shrinkage parameter drives the estimate. + + This should be left to None if `shrinkage` is used. + Note that `covariance_estimator` works only with 'lsqr' and 'eigen' + solvers. + + .. versionadded:: 0.24 + Attributes ---------- coef_ : ndarray of shape (n_features,) or (n_classes, n_features) @@ -244,22 +296,25 @@ class LinearDiscriminantAnalysis(LinearClassifierMixin, >>> print(clf.predict([[-0.8, -1]])) [1] """ - @_deprecate_positional_args - def __init__(self, *, solver='svd', shrinkage=None, priors=None, - n_components=None, store_covariance=False, tol=1e-4): + + def __init__(self, solver='svd', shrinkage=None, priors=None, + n_components=None, store_covariance=False, tol=1e-4, + covariance_estimator=None): self.solver = solver self.shrinkage = shrinkage self.priors = priors self.n_components = n_components self.store_covariance = store_covariance # used only in svd solver self.tol = tol # used only in svd solver + self.covariance_estimator = covariance_estimator - def _solve_lsqr(self, X, y, shrinkage): + def _solve_lsqr(self, X, y, shrinkage, covariance_estimator): """Least squares solver. The least squares solver computes a straightforward solution of the optimal decision rule based directly on the discriminant functions. It - can only be used for classification (with optional shrinkage), because + can only be used for classification (with any covariance estimator), + because estimation of eigenvectors is not performed. Therefore, dimensionality reduction with the transform is not supported. @@ -277,6 +332,19 @@ def _solve_lsqr(self, X, y, shrinkage): - 'auto': automatic shrinkage using the Ledoit-Wolf lemma. - float between 0 and 1: fixed shrinkage parameter. + Shrinkage parameter is ignored if `covariance_estimator` i + not None + + covariance_estimator : estimator, default=None + If not None, `covariance_estimator` is used to estimate + the covariance matrices instead of relying the empirical + covariance estimator (with potential shrinkage). + The object should have a fit method and a ``covariance_`` attribute + like the estimators in sklearn.covariance. + if None the shrinkage parameter drives the estimate. + + .. versionadded:: 0.24 + Notes ----- This solver is based on [1]_, section 2.6.2, pp. 39-41. @@ -288,18 +356,20 @@ def _solve_lsqr(self, X, y, shrinkage): 0-471-05669-3. """ self.means_ = _class_means(X, y) - self.covariance_ = _class_cov(X, y, self.priors_, shrinkage) + self.covariance_ = _class_cov(X, y, self.priors_, shrinkage, + covariance_estimator) self.coef_ = linalg.lstsq(self.covariance_, self.means_.T)[0].T self.intercept_ = (-0.5 * np.diag(np.dot(self.means_, self.coef_.T)) + np.log(self.priors_)) - def _solve_eigen(self, X, y, shrinkage): + def _solve_eigen(self, X, y, shrinkage, + covariance_estimator): """Eigenvalue solver. The eigenvalue solver computes the optimal solution of the Rayleigh coefficient (basically the ratio of between class scatter to within class scatter). This solver supports both classification and - dimensionality reduction (with optional shrinkage). + dimensionality reduction (with any covariance estimator). Parameters ---------- @@ -315,6 +385,19 @@ class scatter). This solver supports both classification and - 'auto': automatic shrinkage using the Ledoit-Wolf lemma. - float between 0 and 1: fixed shrinkage constant. + Shrinkage parameter is ignored if `covariance_estimator` i + not None + + covariance_estimator : estimator, default=None + If not None, `covariance_estimator` is used to estimate + the covariance matrices instead of relying the empirical + covariance estimator (with potential shrinkage). + The object should have a fit method and a ``covariance_`` attribute + like the estimators in sklearn.covariance. + if None the shrinkage parameter drives the estimate. + + .. versionadded:: 0.24 + Notes ----- This solver is based on [1]_, section 3.8.3, pp. 121-124. @@ -326,10 +409,11 @@ class scatter). This solver supports both classification and 0-471-05669-3. """ self.means_ = _class_means(X, y) - self.covariance_ = _class_cov(X, y, self.priors_, shrinkage) + self.covariance_ = _class_cov(X, y, self.priors_, shrinkage, + covariance_estimator) Sw = self.covariance_ # within scatter - St = _cov(X, shrinkage) # total scatter + St = _cov(X, shrinkage, covariance_estimator) # total scatter Sb = St - Sw # between scatter evals, evecs = linalg.eigh(Sb, Sw) @@ -461,11 +545,19 @@ def fit(self, X, y): if self.solver == 'svd': if self.shrinkage is not None: raise NotImplementedError('shrinkage not supported') + if self.covariance_estimator is not None: + raise ValueError( + 'covariance estimator ' + 'is not supported ' + 'with svd solver. Try another solver') self._solve_svd(X, y) elif self.solver == 'lsqr': - self._solve_lsqr(X, y, shrinkage=self.shrinkage) + self._solve_lsqr(X, y, shrinkage=self.shrinkage, + covariance_estimator=self.covariance_estimator) elif self.solver == 'eigen': - self._solve_eigen(X, y, shrinkage=self.shrinkage) + self._solve_eigen(X, y, + shrinkage=self.shrinkage, + covariance_estimator=self.covariance_estimator) else: raise ValueError("unknown solver {} (valid solvers are 'svd', " "'lsqr', and 'eigen').".format(self.solver))
diff --git a/sklearn/tests/test_discriminant_analysis.py b/sklearn/tests/test_discriminant_analysis.py index fec9df61f79a0..18364ce156f87 100644 --- a/sklearn/tests/test_discriminant_analysis.py +++ b/sklearn/tests/test_discriminant_analysis.py @@ -18,7 +18,13 @@ from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis from sklearn.discriminant_analysis import _cov +from sklearn.covariance import ledoit_wolf +from sklearn.cluster import KMeans +from sklearn.covariance import ShrunkCovariance +from sklearn.covariance import LedoitWolf + +from sklearn.preprocessing import StandardScaler # Data is just 6 separable points in the plane X = np.array([[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]], dtype='f') @@ -88,10 +94,36 @@ def test_lda_predict(): assert_raises(ValueError, clf.fit, X, y) clf = LinearDiscriminantAnalysis(solver="svd", shrinkage="auto") assert_raises(NotImplementedError, clf.fit, X, y) + clf = LinearDiscriminantAnalysis(solver="lsqr", shrinkage=np.array([1, 2])) + with pytest.raises(TypeError, + match="shrinkage must be a float or a string"): + clf.fit(X, y) + clf = LinearDiscriminantAnalysis(solver="lsqr", + shrinkage=0.1, + covariance_estimator=ShrunkCovariance()) + with pytest.raises(ValueError, + match=("covariance_estimator and shrinkage " + "parameters are not None. " + "Only one of the two can be set.")): + clf.fit(X, y) # Test unknown solver clf = LinearDiscriminantAnalysis(solver="dummy") assert_raises(ValueError, clf.fit, X, y) + # test bad solver with covariance_estimator + clf = LinearDiscriminantAnalysis(solver="svd", + covariance_estimator=LedoitWolf()) + with pytest.raises(ValueError, + match="covariance estimator is not supported with svd"): + clf.fit(X, y) + + # test bad covariance estimator + clf = LinearDiscriminantAnalysis(solver="lsqr", + covariance_estimator=KMeans(n_clusters=2)) + with pytest.raises(ValueError, + match="KMeans does not have a covariance_ attribute"): + clf.fit(X, y) + @pytest.mark.parametrize("n_classes", [2, 3]) @pytest.mark.parametrize("solver", ["svd", "lsqr", "eigen"]) @@ -327,6 +359,57 @@ def test_lda_store_covariance(): ) [email protected]('seed', range(10)) +def test_lda_shrinkage(seed): + # Test that shrunk covariance estimator and shrinkage parameter behave the + # same + rng = np.random.RandomState(seed) + X = rng.rand(100, 10) + y = rng.randint(3, size=(100)) + c1 = LinearDiscriminantAnalysis(store_covariance=True, shrinkage=0.5, + solver="lsqr") + c2 = LinearDiscriminantAnalysis( + store_covariance=True, + covariance_estimator=ShrunkCovariance(shrinkage=0.5), + solver="lsqr") + c1.fit(X, y) + c2.fit(X, y) + assert_allclose(c1.means_, c2.means_) + assert_allclose(c1.covariance_, c2.covariance_) + + +def test_lda_ledoitwolf(): + # When shrinkage="auto" current implementation uses ledoitwolf estimation + # of covariance after standardizing the data. This checks that it is indeed + # the case + class StandardizedLedoitWolf(): + def fit(self, X): + sc = StandardScaler() # standardize features + X_sc = sc.fit_transform(X) + s = ledoit_wolf(X_sc)[0] + # rescale + s = sc.scale_[:, np.newaxis] * s * sc.scale_[np.newaxis, :] + self.covariance_ = s + + rng = np.random.RandomState(0) + X = rng.rand(100, 10) + y = rng.randint(3, size=(100,)) + c1 = LinearDiscriminantAnalysis( + store_covariance=True, + shrinkage="auto", + solver="lsqr" + ) + c2 = LinearDiscriminantAnalysis( + store_covariance=True, + covariance_estimator=StandardizedLedoitWolf(), + solver="lsqr" + ) + c1.fit(X, y) + c2.fit(X, y) + assert_allclose(c1.means_, c2.means_) + assert_allclose(c1.covariance_, c2.covariance_) + + @pytest.mark.parametrize('n_features', [3, 5]) @pytest.mark.parametrize('n_classes', [5, 3]) def test_lda_dimension_warning(n_classes, n_features):
[ { "path": "doc/modules/lda_qda.rst", "old_path": "a/doc/modules/lda_qda.rst", "new_path": "b/doc/modules/lda_qda.rst", "metadata": "diff --git a/doc/modules/lda_qda.rst b/doc/modules/lda_qda.rst\nindex c3ac94dedefa9..e8f25d2c66930 100644\n--- a/doc/modules/lda_qda.rst\n+++ b/doc/modules/lda_qda.rst\n@@ -163,8 +163,8 @@ transformed class means :math:`\\mu^*_k`). This :math:`L` corresponds to the\n :func:`~discriminant_analysis.LinearDiscriminantAnalysis.transform` method. See\n [1]_ for more details.\n \n-Shrinkage\n-=========\n+Shrinkage and Covariance Estimator\n+==================================\n \n Shrinkage is a form of regularization used to improve the estimation of\n covariance matrices in situations where the number of training samples is\n@@ -187,12 +187,33 @@ an estimate for the covariance matrix). Setting this parameter to a value\n between these two extrema will estimate a shrunk version of the covariance\n matrix.\n \n+The shrinked Ledoit and Wolf estimator of covariance may not always be the\n+best choice. For example if the distribution of the data\n+is normally distributed, the\n+Oracle Shrinkage Approximating estimator :class:`sklearn.covariance.OAS`\n+yields a smaller Mean Squared Error than the one given by Ledoit and Wolf's\n+formula used with shrinkage=\"auto\". In LDA, the data are assumed to be gaussian\n+conditionally to the class. If these assumptions hold, using LDA with\n+the OAS estimator of covariance will yield a better classification \n+accuracy than if Ledoit and Wolf or the empirical covariance estimator is used.\n+\n+The covariance estimator can be chosen using with the ``covariance_estimator``\n+parameter of the :class:`discriminant_analysis.LinearDiscriminantAnalysis`\n+class. A covariance estimator should have a :term:`fit` method and a\n+``covariance_`` attribute like all covariance estimators in the\n+:mod:`sklearn.covariance` module.\n+\n+\n .. |shrinkage| image:: ../auto_examples/classification/images/sphx_glr_plot_lda_001.png\n :target: ../auto_examples/classification/plot_lda.html\n :scale: 75\n \n .. centered:: |shrinkage|\n \n+.. topic:: Examples:\n+\n+ :ref:`sphx_glr_auto_examples_classification_plot_lda.py`: Comparison of LDA classifiers\n+ with Empirical, Ledoit Wolf and OAS covariance estimator.\n \n Estimation algorithms\n =====================\n@@ -220,7 +241,8 @@ and the SVD of the class-wise mean vectors.\n \n The 'lsqr' solver is an efficient algorithm that only works for\n classification. It needs to explicitly compute the covariance matrix\n-:math:`\\Sigma`, and supports shrinkage. This solver computes the coefficients\n+:math:`\\Sigma`, and supports shrinkage and custom covariance estimators.\n+This solver computes the coefficients\n :math:`\\omega_k = \\Sigma^{-1}\\mu_k` by solving for :math:`\\Sigma \\omega =\n \\mu_k`, thus avoiding the explicit computation of the inverse\n :math:`\\Sigma^{-1}`.\n@@ -231,11 +253,6 @@ transform, and it supports shrinkage. However, the 'eigen' solver needs to\n compute the covariance matrix, so it might not be suitable for situations with\n a high number of features.\n \n-.. topic:: Examples:\n-\n- :ref:`sphx_glr_auto_examples_classification_plot_lda.py`: Comparison of LDA classifiers\n- with and without shrinkage.\n-\n .. topic:: References:\n \n .. [1] \"The Elements of Statistical Learning\", Hastie T., Tibshirani R.,\n" }, { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex e8225811194cc..98ccc5d143bcb 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -180,6 +180,13 @@ Changelog\n :func:`decomposition.NMF.non_negative_factorization`.\n :pr:`17414` by :user:`Bharat Raghunathan <Bharat123rox>`.\n \n+:mod:`sklearn.discriminant_analysis`\n+....................................\n+\n+- |Enhancement| :class:`discriminant_analysis.LinearDiscriminantAnalysis` can\n+ now use custom covariance estimate by setting the `covariance_estimator`\n+ parameter. :pr:`14446` by :user:`Hugo Richard <hugorichard>`\n+\n :mod:`sklearn.ensemble`\n .......................\n \n" } ]
0.24
ab3dc9fdf31f35854b390168ac68fb304951305f
[ "sklearn/tests/test_discriminant_analysis.py::test_lda_orthogonality", "sklearn/tests/test_discriminant_analysis.py::test_raises_value_error_on_same_number_of_classes_and_samples[svd, lsqr]", "sklearn/tests/test_discriminant_analysis.py::test_lda_dimension_warning[3-5]", "sklearn/tests/test_discriminant_analysis.py::test_lda_dtype_match[float64-float64]", "sklearn/tests/test_discriminant_analysis.py::test_lda_dimension_warning[3-3]", "sklearn/tests/test_discriminant_analysis.py::test_lda_dimension_warning[5-5]", "sklearn/tests/test_discriminant_analysis.py::test_covariance", "sklearn/tests/test_discriminant_analysis.py::test_lda_priors", "sklearn/tests/test_discriminant_analysis.py::test_qda_regularization", "sklearn/tests/test_discriminant_analysis.py::test_lda_predict_proba[svd-3]", "sklearn/tests/test_discriminant_analysis.py::test_lda_explained_variance_ratio", "sklearn/tests/test_discriminant_analysis.py::test_lda_numeric_consistency_float32_float64", "sklearn/tests/test_discriminant_analysis.py::test_lda_coefs", "sklearn/tests/test_discriminant_analysis.py::test_lda_predict_proba[svd-2]", "sklearn/tests/test_discriminant_analysis.py::test_lda_store_covariance", "sklearn/tests/test_discriminant_analysis.py::test_lda_dtype_match[float32-float32]", "sklearn/tests/test_discriminant_analysis.py::test_lda_predict_proba[lsqr-3]", "sklearn/tests/test_discriminant_analysis.py::test_qda_priors", "sklearn/tests/test_discriminant_analysis.py::test_lda_predict_proba[eigen-2]", "sklearn/tests/test_discriminant_analysis.py::test_lda_dtype_match[int64-float64]", "sklearn/tests/test_discriminant_analysis.py::test_lda_predict_proba[lsqr-2]", "sklearn/tests/test_discriminant_analysis.py::test_lda_transform", "sklearn/tests/test_discriminant_analysis.py::test_raises_value_error_on_same_number_of_classes_and_samples[eigen]", "sklearn/tests/test_discriminant_analysis.py::test_lda_dimension_warning[5-3]", "sklearn/tests/test_discriminant_analysis.py::test_qda", "sklearn/tests/test_discriminant_analysis.py::test_lda_predict_proba[eigen-3]", "sklearn/tests/test_discriminant_analysis.py::test_qda_store_covariance", "sklearn/tests/test_discriminant_analysis.py::test_lda_dtype_match[int32-float64]", "sklearn/tests/test_discriminant_analysis.py::test_lda_scaling" ]
[ "sklearn/tests/test_discriminant_analysis.py::test_lda_shrinkage[7]", "sklearn/tests/test_discriminant_analysis.py::test_lda_predict", "sklearn/tests/test_discriminant_analysis.py::test_lda_shrinkage[1]", "sklearn/tests/test_discriminant_analysis.py::test_lda_ledoitwolf", "sklearn/tests/test_discriminant_analysis.py::test_lda_shrinkage[5]", "sklearn/tests/test_discriminant_analysis.py::test_lda_shrinkage[9]", "sklearn/tests/test_discriminant_analysis.py::test_lda_shrinkage[6]", "sklearn/tests/test_discriminant_analysis.py::test_lda_shrinkage[0]", "sklearn/tests/test_discriminant_analysis.py::test_lda_shrinkage[3]", "sklearn/tests/test_discriminant_analysis.py::test_lda_shrinkage[2]", "sklearn/tests/test_discriminant_analysis.py::test_lda_shrinkage[8]", "sklearn/tests/test_discriminant_analysis.py::test_lda_shrinkage[4]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [ { "type": "error_msg", "name": "shrinkage must be a float or a string" } ] }
[ { "path": "doc/modules/lda_qda.rst", "old_path": "a/doc/modules/lda_qda.rst", "new_path": "b/doc/modules/lda_qda.rst", "metadata": "diff --git a/doc/modules/lda_qda.rst b/doc/modules/lda_qda.rst\nindex c3ac94dedefa9..e8f25d2c66930 100644\n--- a/doc/modules/lda_qda.rst\n+++ b/doc/modules/lda_qda.rst\n@@ -163,8 +163,8 @@ transformed class means :math:`\\mu^*_k`). This :math:`L` corresponds to the\n :func:`~discriminant_analysis.LinearDiscriminantAnalysis.transform` method. See\n [1]_ for more details.\n \n-Shrinkage\n-=========\n+Shrinkage and Covariance Estimator\n+==================================\n \n Shrinkage is a form of regularization used to improve the estimation of\n covariance matrices in situations where the number of training samples is\n@@ -187,12 +187,33 @@ an estimate for the covariance matrix). Setting this parameter to a value\n between these two extrema will estimate a shrunk version of the covariance\n matrix.\n \n+The shrinked Ledoit and Wolf estimator of covariance may not always be the\n+best choice. For example if the distribution of the data\n+is normally distributed, the\n+Oracle Shrinkage Approximating estimator :class:`sklearn.covariance.OAS`\n+yields a smaller Mean Squared Error than the one given by Ledoit and Wolf's\n+formula used with shrinkage=\"auto\". In LDA, the data are assumed to be gaussian\n+conditionally to the class. If these assumptions hold, using LDA with\n+the OAS estimator of covariance will yield a better classification \n+accuracy than if Ledoit and Wolf or the empirical covariance estimator is used.\n+\n+The covariance estimator can be chosen using with the ``covariance_estimator``\n+parameter of the :class:`discriminant_analysis.LinearDiscriminantAnalysis`\n+class. A covariance estimator should have a :term:`fit` method and a\n+``covariance_`` attribute like all covariance estimators in the\n+:mod:`sklearn.covariance` module.\n+\n+\n .. |shrinkage| image:: ../auto_examples/classification/images/sphx_glr_plot_lda_001.png\n :target: ../auto_examples/classification/plot_lda.html\n :scale: 75\n \n .. centered:: |shrinkage|\n \n+.. topic:: Examples:\n+\n+ :ref:`sphx_glr_auto_examples_classification_plot_lda.py`: Comparison of LDA classifiers\n+ with Empirical, Ledoit Wolf and OAS covariance estimator.\n \n Estimation algorithms\n =====================\n@@ -220,7 +241,8 @@ and the SVD of the class-wise mean vectors.\n \n The 'lsqr' solver is an efficient algorithm that only works for\n classification. It needs to explicitly compute the covariance matrix\n-:math:`\\Sigma`, and supports shrinkage. This solver computes the coefficients\n+:math:`\\Sigma`, and supports shrinkage and custom covariance estimators.\n+This solver computes the coefficients\n :math:`\\omega_k = \\Sigma^{-1}\\mu_k` by solving for :math:`\\Sigma \\omega =\n \\mu_k`, thus avoiding the explicit computation of the inverse\n :math:`\\Sigma^{-1}`.\n@@ -231,11 +253,6 @@ transform, and it supports shrinkage. However, the 'eigen' solver needs to\n compute the covariance matrix, so it might not be suitable for situations with\n a high number of features.\n \n-.. topic:: Examples:\n-\n- :ref:`sphx_glr_auto_examples_classification_plot_lda.py`: Comparison of LDA classifiers\n- with and without shrinkage.\n-\n .. topic:: References:\n \n .. [1] \"The Elements of Statistical Learning\", Hastie T., Tibshirani R.,\n" }, { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex e8225811194cc..98ccc5d143bcb 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -180,6 +180,13 @@ Changelog\n :func:`decomposition.NMF.non_negative_factorization`.\n :pr:`<PRID>` by :user:`<NAME>`.\n \n+:mod:`sklearn.discriminant_analysis`\n+....................................\n+\n+- |Enhancement| :class:`discriminant_analysis.LinearDiscriminantAnalysis` can\n+ now use custom covariance estimate by setting the `covariance_estimator`\n+ parameter. :pr:`<PRID>` by :user:`<NAME>`\n+\n :mod:`sklearn.ensemble`\n .......................\n \n" } ]
diff --git a/doc/modules/lda_qda.rst b/doc/modules/lda_qda.rst index c3ac94dedefa9..e8f25d2c66930 100644 --- a/doc/modules/lda_qda.rst +++ b/doc/modules/lda_qda.rst @@ -163,8 +163,8 @@ transformed class means :math:`\mu^*_k`). This :math:`L` corresponds to the :func:`~discriminant_analysis.LinearDiscriminantAnalysis.transform` method. See [1]_ for more details. -Shrinkage -========= +Shrinkage and Covariance Estimator +================================== Shrinkage is a form of regularization used to improve the estimation of covariance matrices in situations where the number of training samples is @@ -187,12 +187,33 @@ an estimate for the covariance matrix). Setting this parameter to a value between these two extrema will estimate a shrunk version of the covariance matrix. +The shrinked Ledoit and Wolf estimator of covariance may not always be the +best choice. For example if the distribution of the data +is normally distributed, the +Oracle Shrinkage Approximating estimator :class:`sklearn.covariance.OAS` +yields a smaller Mean Squared Error than the one given by Ledoit and Wolf's +formula used with shrinkage="auto". In LDA, the data are assumed to be gaussian +conditionally to the class. If these assumptions hold, using LDA with +the OAS estimator of covariance will yield a better classification +accuracy than if Ledoit and Wolf or the empirical covariance estimator is used. + +The covariance estimator can be chosen using with the ``covariance_estimator`` +parameter of the :class:`discriminant_analysis.LinearDiscriminantAnalysis` +class. A covariance estimator should have a :term:`fit` method and a +``covariance_`` attribute like all covariance estimators in the +:mod:`sklearn.covariance` module. + + .. |shrinkage| image:: ../auto_examples/classification/images/sphx_glr_plot_lda_001.png :target: ../auto_examples/classification/plot_lda.html :scale: 75 .. centered:: |shrinkage| +.. topic:: Examples: + + :ref:`sphx_glr_auto_examples_classification_plot_lda.py`: Comparison of LDA classifiers + with Empirical, Ledoit Wolf and OAS covariance estimator. Estimation algorithms ===================== @@ -220,7 +241,8 @@ and the SVD of the class-wise mean vectors. The 'lsqr' solver is an efficient algorithm that only works for classification. It needs to explicitly compute the covariance matrix -:math:`\Sigma`, and supports shrinkage. This solver computes the coefficients +:math:`\Sigma`, and supports shrinkage and custom covariance estimators. +This solver computes the coefficients :math:`\omega_k = \Sigma^{-1}\mu_k` by solving for :math:`\Sigma \omega = \mu_k`, thus avoiding the explicit computation of the inverse :math:`\Sigma^{-1}`. @@ -231,11 +253,6 @@ transform, and it supports shrinkage. However, the 'eigen' solver needs to compute the covariance matrix, so it might not be suitable for situations with a high number of features. -.. topic:: Examples: - - :ref:`sphx_glr_auto_examples_classification_plot_lda.py`: Comparison of LDA classifiers - with and without shrinkage. - .. topic:: References: .. [1] "The Elements of Statistical Learning", Hastie T., Tibshirani R., diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index e8225811194cc..98ccc5d143bcb 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -180,6 +180,13 @@ Changelog :func:`decomposition.NMF.non_negative_factorization`. :pr:`<PRID>` by :user:`<NAME>`. +:mod:`sklearn.discriminant_analysis` +.................................... + +- |Enhancement| :class:`discriminant_analysis.LinearDiscriminantAnalysis` can + now use custom covariance estimate by setting the `covariance_estimator` + parameter. :pr:`<PRID>` by :user:`<NAME>` + :mod:`sklearn.ensemble` ....................... If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names: [{'type': 'error_msg', 'name': 'shrinkage must be a float or a string'}]
scikit-learn/scikit-learn
scikit-learn__scikit-learn-17414
https://github.com/scikit-learn/scikit-learn/pull/17414
diff --git a/doc/modules/decomposition.rst b/doc/modules/decomposition.rst index 6d441004f8ae6..7e8e79d9d8bdd 100644 --- a/doc/modules/decomposition.rst +++ b/doc/modules/decomposition.rst @@ -759,9 +759,9 @@ and the regularized objective function is: + \frac{\alpha(1-\rho)}{2} ||W||_{\mathrm{Fro}} ^ 2 + \frac{\alpha(1-\rho)}{2} ||H||_{\mathrm{Fro}} ^ 2 -:class:`NMF` regularizes both W and H. The public function -:func:`non_negative_factorization` allows a finer control through the -:attr:`regularization` attribute, and may regularize only W, only H, or both. +:class:`NMF` regularizes both W and H by default. The :attr:`regularization` +parameter allows for finer control, with which only W, only H, +or both can be regularized. NMF with a beta-divergence -------------------------- diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index 217e0ed61cfde..c46bb51793ad1 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -114,6 +114,12 @@ Changelog argument `rotation`, which can take the value `None`, `'varimax'` or `'quartimax'.` :pr:`11064` by :user:`Jona Sassenhagen <jona-sassenhagen>`. +- |Enhancement| :class:`decomposition.NMF` now supports the optional parameter + `regularization`, which can take the values `None`, `components`, + `transformation` or `both`, in accordance with + :func:`decomposition.NMF.non_negative_factorization`. + :pr:`17414` by :user:`Bharat Raghunathan <Bharat123rox>`. + :mod:`sklearn.ensemble` ....................... diff --git a/sklearn/decomposition/_nmf.py b/sklearn/decomposition/_nmf.py index 24993102bb424..ebc905a7fbcb3 100644 --- a/sklearn/decomposition/_nmf.py +++ b/sklearn/decomposition/_nmf.py @@ -1081,7 +1081,7 @@ def non_negative_factorization(X, W=None, H=None, n_components=None, *, class NMF(TransformerMixin, BaseEstimator): - r"""Non-Negative Matrix Factorization (NMF) + """Non-Negative Matrix Factorization (NMF) Find two non-negative matrices (W, H) whose product approximates the non- negative matrix X. This factorization can be used for example for @@ -1097,8 +1097,8 @@ class NMF(TransformerMixin, BaseEstimator): Where:: - ||A||_Fro^2 = \sum_{i,j} A_{ij}^2 (Frobenius norm) - ||vec(A)||_1 = \sum_{i,j} abs(A_{ij}) (Elementwise L1 norm) + ||A||_Fro^2 = \\sum_{i,j} A_{ij}^2 (Frobenius norm) + ||vec(A)||_1 = \\sum_{i,j} abs(A_{ij}) (Elementwise L1 norm) For multiplicative-update ('mu') solver, the Frobenius norm (0.5 * ||X - WH||_Fro^2) can be changed into another beta-divergence loss, @@ -1198,6 +1198,13 @@ class NMF(TransformerMixin, BaseEstimator): .. versionadded:: 0.17 *shuffle* parameter used in the Coordinate Descent solver. + regularization : {'both', 'components', 'transformation', None}, \ + default='both' + Select whether the regularization affects the components (H), the + transformation (W), both or none of them. + + .. versionadded:: 0.24 + Attributes ---------- components_ : array, [n_components, n_features] @@ -1239,7 +1246,7 @@ class NMF(TransformerMixin, BaseEstimator): def __init__(self, n_components=None, *, init=None, solver='cd', beta_loss='frobenius', tol=1e-4, max_iter=200, random_state=None, alpha=0., l1_ratio=0., verbose=0, - shuffle=False): + shuffle=False, regularization='both'): self.n_components = n_components self.init = init self.solver = solver @@ -1251,6 +1258,7 @@ def __init__(self, n_components=None, *, init=None, solver='cd', self.l1_ratio = l1_ratio self.verbose = verbose self.shuffle = shuffle + self.regularization = regularization def _more_tags(self): return {'requires_positive_X': True} @@ -1285,7 +1293,7 @@ def fit_transform(self, X, y=None, W=None, H=None): X=X, W=W, H=H, n_components=self.n_components, init=self.init, update_H=True, solver=self.solver, beta_loss=self.beta_loss, tol=self.tol, max_iter=self.max_iter, alpha=self.alpha, - l1_ratio=self.l1_ratio, regularization='both', + l1_ratio=self.l1_ratio, regularization=self.regularization, random_state=self.random_state, verbose=self.verbose, shuffle=self.shuffle) @@ -1334,9 +1342,10 @@ def transform(self, X): X=X, W=None, H=self.components_, n_components=self.n_components_, init=self.init, update_H=False, solver=self.solver, beta_loss=self.beta_loss, tol=self.tol, max_iter=self.max_iter, - alpha=self.alpha, l1_ratio=self.l1_ratio, regularization='both', - random_state=self.random_state, verbose=self.verbose, - shuffle=self.shuffle) + alpha=self.alpha, l1_ratio=self.l1_ratio, + regularization=self.regularization, + random_state=self.random_state, + verbose=self.verbose, shuffle=self.shuffle) return W
diff --git a/sklearn/decomposition/tests/test_nmf.py b/sklearn/decomposition/tests/test_nmf.py index 439ad0697031f..ea48be660a734 100644 --- a/sklearn/decomposition/tests/test_nmf.py +++ b/sklearn/decomposition/tests/test_nmf.py @@ -20,12 +20,14 @@ @pytest.mark.parametrize('solver', ['cd', 'mu']) -def test_convergence_warning(solver): [email protected]('regularization', + [None, 'both', 'components', 'transformation']) +def test_convergence_warning(solver, regularization): convergence_warning = ("Maximum number of iterations 1 reached. " "Increase it to improve convergence.") A = np.ones((2, 2)) with pytest.warns(ConvergenceWarning, match=convergence_warning): - NMF(solver=solver, max_iter=1).fit(A) + NMF(solver=solver, regularization=regularization, max_iter=1).fit(A) def test_initialize_nn_output(): @@ -44,6 +46,8 @@ def test_parameter_checking(): assert_raise_message(ValueError, msg, NMF(solver=name).fit, A) msg = "Invalid init parameter: got 'spam' instead of one of" assert_raise_message(ValueError, msg, NMF(init=name).fit, A) + msg = "Invalid regularization parameter: got 'spam' instead of one of" + assert_raise_message(ValueError, msg, NMF(regularization=name).fit, A) msg = "Invalid beta_loss parameter: got 'spam' instead of one" assert_raise_message(ValueError, msg, NMF(solver='mu', beta_loss=name).fit, A) @@ -97,36 +101,43 @@ def test_initialize_variants(): # ignore UserWarning raised when both solver='mu' and init='nndsvd' @ignore_warnings(category=UserWarning) -def test_nmf_fit_nn_output(): [email protected]('solver', ('cd', 'mu')) [email protected]('init', + (None, 'nndsvd', 'nndsvda', 'nndsvdar', 'random')) [email protected]('regularization', + (None, 'both', 'components', 'transformation')) +def test_nmf_fit_nn_output(solver, init, regularization): # Test that the decomposition does not contain negative values A = np.c_[5. - np.arange(1, 6), 5. + np.arange(1, 6)] - for solver in ('cd', 'mu'): - for init in (None, 'nndsvd', 'nndsvda', 'nndsvdar', 'random'): - model = NMF(n_components=2, solver=solver, init=init, - random_state=0) - transf = model.fit_transform(A) - assert not((model.components_ < 0).any() or - (transf < 0).any()) + model = NMF(n_components=2, solver=solver, init=init, + regularization=regularization, random_state=0) + transf = model.fit_transform(A) + assert not((model.components_ < 0).any() or + (transf < 0).any()) @pytest.mark.parametrize('solver', ('cd', 'mu')) -def test_nmf_fit_close(solver): [email protected]('regularization', + (None, 'both', 'components', 'transformation')) +def test_nmf_fit_close(solver, regularization): rng = np.random.mtrand.RandomState(42) # Test that the fit is not too far away pnmf = NMF(5, solver=solver, init='nndsvdar', random_state=0, - max_iter=600) + regularization=regularization, max_iter=600) X = np.abs(rng.randn(6, 5)) assert pnmf.fit(X).reconstruction_err_ < 0.1 @pytest.mark.parametrize('solver', ('cd', 'mu')) -def test_nmf_transform(solver): [email protected]('regularization', + (None, 'both', 'components', 'transformation')) +def test_nmf_transform(solver, regularization): # Test that NMF.transform returns close values rng = np.random.mtrand.RandomState(42) A = np.abs(rng.randn(6, 5)) m = NMF(solver=solver, n_components=3, init='random', - random_state=0, tol=1e-5) + regularization=regularization, random_state=0, tol=1e-5) ft = m.fit_transform(A) t = m.transform(A) assert_array_almost_equal(ft, t, decimal=2) @@ -148,12 +159,14 @@ def test_nmf_transform_custom_init(): @pytest.mark.parametrize('solver', ('cd', 'mu')) -def test_nmf_inverse_transform(solver): [email protected]('regularization', + (None, 'both', 'components', 'transformation')) +def test_nmf_inverse_transform(solver, regularization): # Test that NMF.inverse_transform returns close values random_state = np.random.RandomState(0) A = np.abs(random_state.randn(6, 4)) m = NMF(solver=solver, n_components=4, init='random', random_state=0, - max_iter=1000) + regularization=regularization, max_iter=1000) ft = m.fit_transform(A) A_new = m.inverse_transform(ft) assert_array_almost_equal(A, A_new, decimal=2) @@ -167,7 +180,9 @@ def test_n_components_greater_n_features(): @pytest.mark.parametrize('solver', ['cd', 'mu']) -def test_nmf_sparse_input(solver): [email protected]('regularization', + [None, 'both', 'components', 'transformation']) +def test_nmf_sparse_input(solver, regularization): # Test that sparse matrices are accepted as input from scipy.sparse import csc_matrix @@ -177,7 +192,8 @@ def test_nmf_sparse_input(solver): A_sparse = csc_matrix(A) est1 = NMF(solver=solver, n_components=5, init='random', - random_state=0, tol=1e-2) + regularization=regularization, random_state=0, + tol=1e-2) est2 = clone(est1) W1 = est1.fit_transform(A) @@ -204,28 +220,32 @@ def test_nmf_sparse_transform(): assert_array_almost_equal(A_fit_tr, A_tr, decimal=1) -def test_non_negative_factorization_consistency(): [email protected]('init', ['random', 'nndsvd']) [email protected]('solver', ('cd', 'mu')) [email protected]('regularization', + (None, 'both', 'components', 'transformation')) +def test_non_negative_factorization_consistency(init, solver, regularization): # Test that the function is called in the same way, either directly # or through the NMF class rng = np.random.mtrand.RandomState(42) A = np.abs(rng.randn(10, 10)) A[:, 2 * np.arange(5)] = 0 - for init in ['random', 'nndsvd']: - for solver in ('cd', 'mu'): - W_nmf, H, _ = non_negative_factorization( - A, init=init, solver=solver, random_state=1, tol=1e-2) - W_nmf_2, _, _ = non_negative_factorization( - A, H=H, update_H=False, init=init, solver=solver, - random_state=1, tol=1e-2) + W_nmf, H, _ = non_negative_factorization( + A, init=init, solver=solver, + regularization=regularization, random_state=1, tol=1e-2) + W_nmf_2, _, _ = non_negative_factorization( + A, H=H, update_H=False, init=init, solver=solver, + regularization=regularization, random_state=1, tol=1e-2) - model_class = NMF(init=init, solver=solver, random_state=1, - tol=1e-2) - W_cls = model_class.fit_transform(A) - W_cls_2 = model_class.transform(A) + model_class = NMF(init=init, solver=solver, + regularization=regularization, + random_state=1, tol=1e-2) + W_cls = model_class.fit_transform(A) + W_cls_2 = model_class.transform(A) - assert_array_almost_equal(W_nmf, W_cls, decimal=10) - assert_array_almost_equal(W_nmf_2, W_cls_2, decimal=10) + assert_array_almost_equal(W_nmf, W_cls, decimal=10) + assert_array_almost_equal(W_nmf_2, W_cls_2, decimal=10) def test_non_negative_factorization_checking(): @@ -515,11 +535,13 @@ def test_nmf_underflow(): (np.int32, np.float64), (np.int64, np.float64)]) @pytest.mark.parametrize("solver", ["cd", "mu"]) -def test_nmf_dtype_match(dtype_in, dtype_out, solver): [email protected]("regularization", + (None, "both", "components", "transformation")) +def test_nmf_dtype_match(dtype_in, dtype_out, solver, regularization): # Check that NMF preserves dtype (float32 and float64) X = np.random.RandomState(0).randn(20, 15).astype(dtype_in, copy=False) np.abs(X, out=X) - nmf = NMF(solver=solver) + nmf = NMF(solver=solver, regularization=regularization) assert nmf.fit(X).transform(X).dtype == dtype_out assert nmf.fit_transform(X).dtype == dtype_out @@ -527,13 +549,15 @@ def test_nmf_dtype_match(dtype_in, dtype_out, solver): @pytest.mark.parametrize("solver", ["cd", "mu"]) -def test_nmf_float32_float64_consistency(solver): [email protected]("regularization", + (None, "both", "components", "transformation")) +def test_nmf_float32_float64_consistency(solver, regularization): # Check that the result of NMF is the same between float32 and float64 X = np.random.RandomState(0).randn(50, 7) np.abs(X, out=X) - nmf32 = NMF(solver=solver, random_state=0) + nmf32 = NMF(solver=solver, regularization=regularization, random_state=0) W32 = nmf32.fit_transform(X.astype(np.float32)) - nmf64 = NMF(solver=solver, random_state=0) + nmf64 = NMF(solver=solver, regularization=regularization, random_state=0) W64 = nmf64.fit_transform(X) assert_allclose(W32, W64, rtol=1e-6, atol=1e-5)
[ { "path": "doc/modules/decomposition.rst", "old_path": "a/doc/modules/decomposition.rst", "new_path": "b/doc/modules/decomposition.rst", "metadata": "diff --git a/doc/modules/decomposition.rst b/doc/modules/decomposition.rst\nindex 6d441004f8ae6..7e8e79d9d8bdd 100644\n--- a/doc/modules/decomposition.rst\n+++ b/doc/modules/decomposition.rst\n@@ -759,9 +759,9 @@ and the regularized objective function is:\n + \\frac{\\alpha(1-\\rho)}{2} ||W||_{\\mathrm{Fro}} ^ 2\n + \\frac{\\alpha(1-\\rho)}{2} ||H||_{\\mathrm{Fro}} ^ 2\n \n-:class:`NMF` regularizes both W and H. The public function\n-:func:`non_negative_factorization` allows a finer control through the\n-:attr:`regularization` attribute, and may regularize only W, only H, or both.\n+:class:`NMF` regularizes both W and H by default. The :attr:`regularization`\n+parameter allows for finer control, with which only W, only H,\n+or both can be regularized.\n \n NMF with a beta-divergence\n --------------------------\n" }, { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex 217e0ed61cfde..c46bb51793ad1 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -114,6 +114,12 @@ Changelog\n argument `rotation`, which can take the value `None`, `'varimax'` or `'quartimax'.`\n :pr:`11064` by :user:`Jona Sassenhagen <jona-sassenhagen>`.\n \n+- |Enhancement| :class:`decomposition.NMF` now supports the optional parameter\n+ `regularization`, which can take the values `None`, `components`,\n+ `transformation` or `both`, in accordance with\n+ :func:`decomposition.NMF.non_negative_factorization`.\n+ :pr:`17414` by :user:`Bharat Raghunathan <Bharat123rox>`.\n+\n :mod:`sklearn.ensemble`\n .......................\n \n" } ]
0.24
b2a7d3646d406b50dd46bab0cc685971601a3de3
[ "sklearn/decomposition/tests/test_nmf.py::test_special_sparse_dot", "sklearn/decomposition/tests/test_nmf.py::test_beta_divergence", "sklearn/decomposition/tests/test_nmf.py::test_nmf_multiplicative_update_sparse", "sklearn/decomposition/tests/test_nmf.py::test_nmf_negative_beta_loss", "sklearn/decomposition/tests/test_nmf.py::test_nmf_decreasing", "sklearn/decomposition/tests/test_nmf.py::test_nmf_custom_init_dtype_error", "sklearn/decomposition/tests/test_nmf.py::test_nmf_underflow", "sklearn/decomposition/tests/test_nmf.py::test_non_negative_factorization_checking", "sklearn/decomposition/tests/test_nmf.py::test_nmf_regularization", "sklearn/decomposition/tests/test_nmf.py::test_initialize_variants", "sklearn/decomposition/tests/test_nmf.py::test_nmf_sparse_transform", "sklearn/decomposition/tests/test_nmf.py::test_initialize_nn_output", "sklearn/decomposition/tests/test_nmf.py::test_initialize_close", "sklearn/decomposition/tests/test_nmf.py::test_nmf_transform_custom_init", "sklearn/decomposition/tests/test_nmf.py::test_n_components_greater_n_features" ]
[ "sklearn/decomposition/tests/test_nmf.py::test_parameter_checking", "sklearn/decomposition/tests/test_nmf.py::test_nmf_sparse_input[both-mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_inverse_transform[components-mu]", "sklearn/decomposition/tests/test_nmf.py::test_non_negative_factorization_consistency[components-mu-nndsvd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[None-cd-int64-float64]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[both-nndsvd-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_sparse_input[components-mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_sparse_input[transformation-mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_inverse_transform[components-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_float32_float64_consistency[None-mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_float32_float64_consistency[both-mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_inverse_transform[None-mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[None-None-cd]", "sklearn/decomposition/tests/test_nmf.py::test_non_negative_factorization_consistency[transformation-cd-nndsvd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_transform[transformation-mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_sparse_input[None-mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_close[transformation-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[None-random-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_close[transformation-mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_sparse_input[both-cd]", "sklearn/decomposition/tests/test_nmf.py::test_non_negative_factorization_consistency[components-cd-nndsvd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[None-nndsvdar-mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[both-mu-float64-float64]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[transformation-mu-float64-float64]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[None-None-mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[None-cd-float32-float32]", "sklearn/decomposition/tests/test_nmf.py::test_non_negative_factorization_consistency[both-cd-nndsvd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[components-nndsvdar-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[both-nndsvdar-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[both-cd-int64-float64]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_transform[components-mu]", "sklearn/decomposition/tests/test_nmf.py::test_convergence_warning[components-mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[transformation-nndsvda-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[both-nndsvda-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[both-nndsvda-mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_float32_float64_consistency[None-cd]", "sklearn/decomposition/tests/test_nmf.py::test_convergence_warning[transformation-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_close[components-cd]", "sklearn/decomposition/tests/test_nmf.py::test_non_negative_factorization_consistency[both-cd-random]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[both-None-mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[components-cd-int64-float64]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[both-nndsvdar-mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[None-mu-int64-float64]", "sklearn/decomposition/tests/test_nmf.py::test_non_negative_factorization_consistency[components-mu-random]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_float32_float64_consistency[components-cd]", "sklearn/decomposition/tests/test_nmf.py::test_non_negative_factorization_consistency[transformation-mu-nndsvd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_inverse_transform[transformation-mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_transform[both-mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_inverse_transform[both-mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[components-nndsvd-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[both-cd-float64-float64]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_float32_float64_consistency[components-mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[None-cd-int32-float64]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[transformation-None-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[transformation-mu-int32-float64]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_close[None-mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[None-nndsvdar-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_sparse_input[transformation-cd]", "sklearn/decomposition/tests/test_nmf.py::test_non_negative_factorization_consistency[None-mu-random]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[both-None-cd]", "sklearn/decomposition/tests/test_nmf.py::test_non_negative_factorization_consistency[components-cd-random]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[both-random-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[components-random-mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[None-random-mu]", "sklearn/decomposition/tests/test_nmf.py::test_convergence_warning[both-mu]", "sklearn/decomposition/tests/test_nmf.py::test_non_negative_factorization_consistency[both-mu-random]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[None-mu-float32-float32]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[None-nndsvd-mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[None-nndsvd-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[transformation-mu-float32-float32]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[both-nndsvd-mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[components-cd-float64-float64]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[components-random-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[transformation-cd-int32-float64]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[transformation-nndsvdar-mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_sparse_input[None-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[components-nndsvda-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[components-mu-int32-float64]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[components-mu-int64-float64]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[None-mu-int32-float64]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[transformation-nndsvda-mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[transformation-None-mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[components-None-mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[transformation-random-mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_close[both-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[both-mu-float32-float32]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_transform[None-mu]", "sklearn/decomposition/tests/test_nmf.py::test_non_negative_factorization_consistency[None-cd-nndsvd]", "sklearn/decomposition/tests/test_nmf.py::test_convergence_warning[None-mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[transformation-nndsvd-mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[both-random-mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[None-nndsvda-mu]", "sklearn/decomposition/tests/test_nmf.py::test_non_negative_factorization_consistency[transformation-mu-random]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_sparse_input[components-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_float32_float64_consistency[transformation-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[None-cd-float64-float64]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[components-nndsvdar-mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_transform[components-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_inverse_transform[None-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[components-cd-float32-float32]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[transformation-random-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_inverse_transform[both-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[None-mu-float64-float64]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[components-nndsvd-mu]", "sklearn/decomposition/tests/test_nmf.py::test_non_negative_factorization_consistency[both-mu-nndsvd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[transformation-cd-int64-float64]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[components-mu-float64-float64]", "sklearn/decomposition/tests/test_nmf.py::test_convergence_warning[None-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[transformation-cd-float64-float64]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_close[components-mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_transform[None-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[transformation-cd-float32-float32]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[transformation-nndsvd-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[transformation-nndsvdar-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[both-cd-int32-float64]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_float32_float64_consistency[both-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_close[both-mu]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_transform[both-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[components-None-cd]", "sklearn/decomposition/tests/test_nmf.py::test_convergence_warning[transformation-mu]", "sklearn/decomposition/tests/test_nmf.py::test_non_negative_factorization_consistency[None-cd-random]", "sklearn/decomposition/tests/test_nmf.py::test_convergence_warning[both-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[components-cd-int32-float64]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_transform[transformation-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[both-mu-int32-float64]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_close[None-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[both-mu-int64-float64]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_float32_float64_consistency[transformation-mu]", "sklearn/decomposition/tests/test_nmf.py::test_non_negative_factorization_consistency[None-mu-nndsvd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_inverse_transform[transformation-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[components-mu-float32-float32]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[transformation-mu-int64-float64]", "sklearn/decomposition/tests/test_nmf.py::test_non_negative_factorization_consistency[transformation-cd-random]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[components-nndsvda-mu]", "sklearn/decomposition/tests/test_nmf.py::test_convergence_warning[components-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_fit_nn_output[None-nndsvda-cd]", "sklearn/decomposition/tests/test_nmf.py::test_nmf_dtype_match[both-cd-float32-float32]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/modules/decomposition.rst", "old_path": "a/doc/modules/decomposition.rst", "new_path": "b/doc/modules/decomposition.rst", "metadata": "diff --git a/doc/modules/decomposition.rst b/doc/modules/decomposition.rst\nindex 6d441004f8ae6..7e8e79d9d8bdd 100644\n--- a/doc/modules/decomposition.rst\n+++ b/doc/modules/decomposition.rst\n@@ -759,9 +759,9 @@ and the regularized objective function is:\n + \\frac{\\alpha(1-\\rho)}{2} ||W||_{\\mathrm{Fro}} ^ 2\n + \\frac{\\alpha(1-\\rho)}{2} ||H||_{\\mathrm{Fro}} ^ 2\n \n-:class:`NMF` regularizes both W and H. The public function\n-:func:`non_negative_factorization` allows a finer control through the\n-:attr:`regularization` attribute, and may regularize only W, only H, or both.\n+:class:`NMF` regularizes both W and H by default. The :attr:`regularization`\n+parameter allows for finer control, with which only W, only H,\n+or both can be regularized.\n \n NMF with a beta-divergence\n --------------------------\n" }, { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex 217e0ed61cfde..c46bb51793ad1 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -114,6 +114,12 @@ Changelog\n argument `rotation`, which can take the value `None`, `'varimax'` or `'quartimax'.`\n :pr:`<PRID>` by :user:`<NAME>`.\n \n+- |Enhancement| :class:`decomposition.NMF` now supports the optional parameter\n+ `regularization`, which can take the values `None`, `components`,\n+ `transformation` or `both`, in accordance with\n+ :func:`decomposition.NMF.non_negative_factorization`.\n+ :pr:`<PRID>` by :user:`<NAME>`.\n+\n :mod:`sklearn.ensemble`\n .......................\n \n" } ]
diff --git a/doc/modules/decomposition.rst b/doc/modules/decomposition.rst index 6d441004f8ae6..7e8e79d9d8bdd 100644 --- a/doc/modules/decomposition.rst +++ b/doc/modules/decomposition.rst @@ -759,9 +759,9 @@ and the regularized objective function is: + \frac{\alpha(1-\rho)}{2} ||W||_{\mathrm{Fro}} ^ 2 + \frac{\alpha(1-\rho)}{2} ||H||_{\mathrm{Fro}} ^ 2 -:class:`NMF` regularizes both W and H. The public function -:func:`non_negative_factorization` allows a finer control through the -:attr:`regularization` attribute, and may regularize only W, only H, or both. +:class:`NMF` regularizes both W and H by default. The :attr:`regularization` +parameter allows for finer control, with which only W, only H, +or both can be regularized. NMF with a beta-divergence -------------------------- diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index 217e0ed61cfde..c46bb51793ad1 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -114,6 +114,12 @@ Changelog argument `rotation`, which can take the value `None`, `'varimax'` or `'quartimax'.` :pr:`<PRID>` by :user:`<NAME>`. +- |Enhancement| :class:`decomposition.NMF` now supports the optional parameter + `regularization`, which can take the values `None`, `components`, + `transformation` or `both`, in accordance with + :func:`decomposition.NMF.non_negative_factorization`. + :pr:`<PRID>` by :user:`<NAME>`. + :mod:`sklearn.ensemble` .......................
scikit-learn/scikit-learn
scikit-learn__scikit-learn-20619
https://github.com/scikit-learn/scikit-learn/pull/20619
diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index 2f7e7590a1c6b..6685ca582428a 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -488,6 +488,9 @@ Changelog :pr:`18649` by :user:`Leandro Hermida <hermidalc>` and :user:`Rodion Martynov <marrodion>`. +- |Enhancement| warn only once in the main process for per-split fit failures + in cross-validation. :pr:`20619` by :user:`Loïc Estève <lesteve>` + :mod:`sklearn.naive_bayes` .......................... diff --git a/sklearn/model_selection/_search.py b/sklearn/model_selection/_search.py index decb88212933a..93e481ba0b77d 100644 --- a/sklearn/model_selection/_search.py +++ b/sklearn/model_selection/_search.py @@ -31,6 +31,7 @@ from ._validation import _aggregate_score_dicts from ._validation import _insert_error_scores from ._validation import _normalize_score_results +from ._validation import _warn_about_fit_failures from ..exceptions import NotFittedError from joblib import Parallel from ..utils import check_random_state @@ -793,14 +794,18 @@ def evaluate_candidates(candidate_params, cv=None, more_results=None): "splits, got {}".format(n_splits, len(out) // n_candidates) ) + _warn_about_fit_failures(out, self.error_score) + # For callable self.scoring, the return type is only know after # calling. If the return type is a dictionary, the error scores # can now be inserted with the correct key. The type checking # of out will be done in `_insert_error_scores`. if callable(self.scoring): _insert_error_scores(out, self.error_score) + all_candidate_params.extend(candidate_params) all_out.extend(out) + if more_results is not None: for key, value in more_results.items(): all_more_results[key].extend(value) diff --git a/sklearn/model_selection/_validation.py b/sklearn/model_selection/_validation.py index 90fd8963bb8ae..8650997c50f55 100644 --- a/sklearn/model_selection/_validation.py +++ b/sklearn/model_selection/_validation.py @@ -15,6 +15,7 @@ import time from traceback import format_exc from contextlib import suppress +from collections import Counter import numpy as np import scipy.sparse as sp @@ -281,6 +282,8 @@ def cross_validate( for train, test in cv.split(X, y, groups) ) + _warn_about_fit_failures(results, error_score) + # For callabe scoring, the return type is only know after calling. If the # return type is a dictionary, the error scores can now be inserted with # the correct key. @@ -318,7 +321,7 @@ def _insert_error_scores(results, error_score): successful_score = None failed_indices = [] for i, result in enumerate(results): - if result["fit_failed"]: + if result["fit_error"] is not None: failed_indices.append(i) elif successful_score is None: successful_score = result["test_scores"] @@ -343,6 +346,31 @@ def _normalize_score_results(scores, scaler_score_key="score"): return {scaler_score_key: scores} +def _warn_about_fit_failures(results, error_score): + fit_errors = [ + result["fit_error"] for result in results if result["fit_error"] is not None + ] + if fit_errors: + num_failed_fits = len(fit_errors) + num_fits = len(results) + fit_errors_counter = Counter(fit_errors) + delimiter = "-" * 80 + "\n" + fit_errors_summary = "\n".join( + f"{delimiter}{n} fits failed with the following error:\n{error}" + for error, n in fit_errors_counter.items() + ) + + some_fits_failed_message = ( + f"\n{num_failed_fits} fits failed out of a total of {num_fits}.\n" + "The score on these train-test partitions for these parameters" + f" will be set to {error_score}.\n" + "If these failures are not expected, you can try to debug them " + "by setting error_score='raise'.\n\n" + f"Below are more details about the failures:\n{fit_errors_summary}" + ) + warnings.warn(some_fits_failed_message, FitFailedWarning) + + def cross_val_score( estimator, X, @@ -598,8 +626,8 @@ def _fit_and_score( The parameters that have been evaluated. estimator : estimator object The fitted estimator. - fit_failed : bool - The estimator failed to fit. + fit_error : str or None + Traceback str if the fit failed, None if the fit succeeded. """ if not isinstance(error_score, numbers.Number) and error_score != "raise": raise ValueError( @@ -666,15 +694,9 @@ def _fit_and_score( test_scores = error_score if return_train_score: train_scores = error_score - warnings.warn( - "Estimator fit failed. The score on this train-test" - " partition for these parameters will be set to %f. " - "Details: \n%s" % (error_score, format_exc()), - FitFailedWarning, - ) - result["fit_failed"] = True + result["fit_error"] = format_exc() else: - result["fit_failed"] = False + result["fit_error"] = None fit_time = time.time() - start_time test_scores = _score(estimator, X_test, y_test, scorer, error_score)
diff --git a/sklearn/model_selection/tests/test_search.py b/sklearn/model_selection/tests/test_search.py index e878eca519467..5c9048658faba 100644 --- a/sklearn/model_selection/tests/test_search.py +++ b/sklearn/model_selection/tests/test_search.py @@ -1565,9 +1565,13 @@ def test_grid_search_failing_classifier(): refit=False, error_score=0.0, ) - warning_message = ( - "Estimator fit failed. The score on this train-test partition " - "for these parameters will be set to 0.0.*." + + warning_message = re.compile( + "5 fits failed.+total of 15.+The score on these" + r" train-test partitions for these parameters will be set to 0\.0.+" + "5 fits failed with the following error.+ValueError.+Failing classifier failed" + " as required", + flags=re.DOTALL, ) with pytest.warns(FitFailedWarning, match=warning_message): gs.fit(X, y) @@ -1598,9 +1602,12 @@ def get_cand_scores(i): refit=False, error_score=float("nan"), ) - warning_message = ( - "Estimator fit failed. The score on this train-test partition " - "for these parameters will be set to nan." + warning_message = re.compile( + "5 fits failed.+total of 15.+The score on these" + r" train-test partitions for these parameters will be set to nan.+" + "5 fits failed with the following error.+ValueError.+Failing classifier failed" + " as required", + flags=re.DOTALL, ) with pytest.warns(FitFailedWarning, match=warning_message): gs.fit(X, y) @@ -2112,7 +2119,12 @@ def custom_scorer(est, X, y): error_score=0.1, ) - with pytest.warns(FitFailedWarning, match="Estimator fit failed"): + warning_message = re.compile( + "5 fits failed.+total of 15.+The score on these" + r" train-test partitions for these parameters will be set to 0\.1", + flags=re.DOTALL, + ) + with pytest.warns(FitFailedWarning, match=warning_message): gs.fit(X, y) assert_allclose(gs.cv_results_["mean_test_acc"], [1, 1, 0.1]) @@ -2135,9 +2147,10 @@ def custom_scorer(est, X, y): error_score=0.1, ) - with pytest.warns(FitFailedWarning, match="Estimator fit failed"), pytest.raises( - NotFittedError, match="All estimators failed to fit" - ): + with pytest.warns( + FitFailedWarning, + match="15 fits failed.+total of 15", + ), pytest.raises(NotFittedError, match="All estimators failed to fit"): gs.fit(X, y) diff --git a/sklearn/model_selection/tests/test_validation.py b/sklearn/model_selection/tests/test_validation.py index e9252715a8a64..ebfbfec1092f7 100644 --- a/sklearn/model_selection/tests/test_validation.py +++ b/sklearn/model_selection/tests/test_validation.py @@ -2082,37 +2082,6 @@ def test_fit_and_score_failing(): y = np.ones(9) fit_and_score_args = [failing_clf, X, None, dict(), None, None, 0, None, None] # passing error score to trigger the warning message - fit_and_score_kwargs = {"error_score": 0} - # check if the warning message type is as expected - warning_message = ( - "Estimator fit failed. The score on this train-test partition for " - "these parameters will be set to %f." % (fit_and_score_kwargs["error_score"]) - ) - with pytest.warns(FitFailedWarning, match=warning_message): - _fit_and_score(*fit_and_score_args, **fit_and_score_kwargs) - # since we're using FailingClassfier, our error will be the following - error_message = "ValueError: Failing classifier failed as required" - # the warning message we're expecting to see - warning_message = ( - "Estimator fit failed. The score on this train-test " - "partition for these parameters will be set to %f. " - "Details: \n%s" % (fit_and_score_kwargs["error_score"], error_message) - ) - - def test_warn_trace(msg): - assert "Traceback (most recent call last):\n" in msg - split = msg.splitlines() # note: handles more than '\n' - mtb = split[0] + "\n" + split[-1] - return warning_message in mtb - - # check traceback is included - warning_message = ( - "Estimator fit failed. The score on this train-test partition for " - "these parameters will be set to %f." % (fit_and_score_kwargs["error_score"]) - ) - with pytest.warns(FitFailedWarning, match=warning_message): - _fit_and_score(*fit_and_score_args, **fit_and_score_kwargs) - fit_and_score_kwargs = {"error_score": "raise"} # check if exception was raised, with default error_score='raise' with pytest.raises(ValueError, match="Failing classifier failed as required"): @@ -2161,6 +2130,41 @@ def test_fit_and_score_working(): assert result["parameters"] == fit_and_score_kwargs["parameters"] [email protected]("error_score", [np.nan, 0]) +def test_cross_validate_failing_fits_warnings(error_score): + # Create a failing classifier to deliberately fail + failing_clf = FailingClassifier(FailingClassifier.FAILING_PARAMETER) + # dummy X data + X = np.arange(1, 10) + y = np.ones(9) + # fit_and_score_args = [failing_clf, X, None, dict(), None, None, 0, None, None] + # passing error score to trigger the warning message + cross_validate_args = [failing_clf, X, y] + cross_validate_kwargs = {"cv": 7, "error_score": error_score} + # check if the warning message type is as expected + warning_message = re.compile( + "7 fits failed.+total of 7.+The score on these" + " train-test partitions for these parameters will be set to" + f" {cross_validate_kwargs['error_score']}.", + flags=re.DOTALL, + ) + + with pytest.warns(FitFailedWarning, match=warning_message): + cross_validate(*cross_validate_args, **cross_validate_kwargs) + + # since we're using FailingClassfier, our error will be the following + error_message = "ValueError: Failing classifier failed as required" + + # check traceback is included + warning_message = re.compile( + "The score on these train-test partitions for these parameters will be set" + f" to {cross_validate_kwargs['error_score']}.+{error_message}", + re.DOTALL, + ) + with pytest.warns(FitFailedWarning, match=warning_message): + cross_validate(*cross_validate_args, **cross_validate_kwargs) + + def _failing_scorer(estimator, X, y, error_msg): raise ValueError(error_msg)
[ { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 2f7e7590a1c6b..6685ca582428a 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -488,6 +488,9 @@ Changelog\n :pr:`18649` by :user:`Leandro Hermida <hermidalc>` and\n :user:`Rodion Martynov <marrodion>`.\n \n+- |Enhancement| warn only once in the main process for per-split fit failures\n+ in cross-validation. :pr:`20619` by :user:`Loïc Estève <lesteve>`\n+\n :mod:`sklearn.naive_bayes`\n ..........................\n \n" } ]
1.00
39f37bb63d395dd2b97be7f8231ddd2113825c42
[ "sklearn/model_selection/tests/test_search.py::test_callable_multimetric_same_as_list_of_strings", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_predict_proba_shape", "sklearn/model_selection/tests/test_search.py::test_SearchCV_with_fit_params[RandomizedSearchCV]", "sklearn/model_selection/tests/test_search.py::test_search_default_iid[GridSearchCV-specialized_params0]", "sklearn/model_selection/tests/test_search.py::test_y_as_list", "sklearn/model_selection/tests/test_search.py::test_scalar_fit_param[GridSearchCV-param_search0]", "sklearn/model_selection/tests/test_search.py::test_search_cv_pairwise_property_delegated_to_base_estimator[True]", "sklearn/model_selection/tests/test_validation.py::test_score_memmap", "sklearn/model_selection/tests/test_search.py::test_scalar_fit_param_compat[RandomizedSearchCV-param_search1]", "sklearn/model_selection/tests/test_search.py::test_random_search_bad_cv", "sklearn/model_selection/tests/test_search.py::test_searchcv_raise_warning_with_non_finite_score[GridSearchCV-specialized_params0-False]", "sklearn/model_selection/tests/test_search.py::test_X_as_list", "sklearn/model_selection/tests/test_validation.py::test_validation_curve_clone_estimator", "sklearn/model_selection/tests/test_search.py::test_search_cv_using_minimal_compatible_estimator[MinimalRegressor-RandomizedSearchCV]", "sklearn/model_selection/tests/test_search.py::test_grid_search_error", "sklearn/model_selection/tests/test_search.py::test_search_cv_using_minimal_compatible_estimator[MinimalClassifier-GridSearchCV]", "sklearn/model_selection/tests/test_search.py::test_grid_search_precomputed_kernel_error_nonsquare", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[True-True-0]", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[False-False-nan]", "sklearn/model_selection/tests/test_search.py::test_search_cv_results_none_param", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_pandas", "sklearn/model_selection/tests/test_validation.py::test_fit_and_score_verbosity[False-scorer2-10-split_prg2-cdt_prg2-\\\\[CV 2/3; 1/1\\\\] END ....... sc1: \\\\(test=3.421\\\\) sc2: \\\\(test=3.421\\\\) total time= 0.\\\\ds]", "sklearn/model_selection/tests/test_search.py::test_validate_parameter_input[input2-TypeError-Parameter.* value is not iterable .*\\\\(key='foo', value=0\\\\)-ParameterGrid]", "sklearn/model_selection/tests/test_search.py::test__custom_fit_no_run_search", "sklearn/model_selection/tests/test_search.py::test_grid_search_cv_splits_consistency", "sklearn/model_selection/tests/test_search.py::test_callable_single_metric_same_as_single_string", "sklearn/model_selection/tests/test_search.py::test_pickle", "sklearn/model_selection/tests/test_search.py::test_predict_proba_disabled", "sklearn/model_selection/tests/test_search.py::test_n_features_in", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_sparse_fit_params", "sklearn/model_selection/tests/test_validation.py::test_validation_curve_cv_splits_consistency", "sklearn/model_selection/tests/test_search.py::test_search_cv_score_samples_error[search_cv0]", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_verbose", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[True-False-raise]", "sklearn/model_selection/tests/test_search.py::test_refit_callable", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_invalid_scoring_param", "sklearn/model_selection/tests/test_search.py::test_grid_search_bad_param_grid", "sklearn/model_selection/tests/test_search.py::test_search_cv_timing", "sklearn/model_selection/tests/test_search.py::test_grid_search_cv_results", "sklearn/model_selection/tests/test_search.py::test_callable_multimetric_error_on_invalid_key", "sklearn/model_selection/tests/test_search.py::test_transform_inverse_transform_round_trip", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_score_func", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_y_none", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_batch_and_incremental_learning_are_equal", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_class_subset", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_failing_scorer[raise]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_with_method", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_predict_groups", "sklearn/model_selection/tests/test_validation.py::test_permutation_test_score_pandas", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_failing_scorer[0]", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[False-True-nan]", "sklearn/model_selection/tests/test_validation.py::test_fit_and_score_working", "sklearn/model_selection/tests/test_search.py::test_refit_callable_out_bound[RandomizedSearchCV-2]", "sklearn/model_selection/tests/test_validation.py::test_permutation_test_score_allow_nans", "sklearn/model_selection/tests/test_validation.py::test_fit_and_score_failing", "sklearn/model_selection/tests/test_search.py::test_refit_callable_multi_metric", "sklearn/model_selection/tests/test_search.py::test_trivial_cv_results_attr", "sklearn/model_selection/tests/test_search.py::test_search_cv_verbose_3[True]", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_many_jobs", "sklearn/model_selection/tests/test_validation.py::test_fit_and_score_verbosity[True-scorer1-3-split_prg1-cdt_prg1-\\\\[CV 2/3\\\\] END sc1: \\\\(train=3.421, test=3.421\\\\) sc2: \\\\(train=3.421, test=3.421\\\\) total time= 0.\\\\ds]", "sklearn/model_selection/tests/test_search.py::test_grid_search_one_grid_point", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_fit_params", "sklearn/model_selection/tests/test_search.py::test_search_cv__pairwise_property_delegated_to_base_estimator", "sklearn/model_selection/tests/test_search.py::test_no_refit", "sklearn/model_selection/tests/test_search.py::test_grid_search_sparse", "sklearn/model_selection/tests/test_validation.py::test_permutation_score", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_allow_nans", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_with_score_func_regression", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_nested_estimator", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_with_method_multilabel_ovr", "sklearn/model_selection/tests/test_search.py::test_validate_parameter_input[input1-TypeError-Parameter .* is not a dict \\\\(0\\\\)-klass1]", "sklearn/model_selection/tests/test_validation.py::test_gridsearchcv_cross_val_predict_with_method", "sklearn/model_selection/tests/test_search.py::test_search_default_iid[RandomizedSearchCV-specialized_params1]", "sklearn/model_selection/tests/test_validation.py::test_cross_validate", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_n_sample_range_out_of_bounds", "sklearn/model_selection/tests/test_search.py::test_gridsearch_no_predict", "sklearn/model_selection/tests/test_search.py::test_param_sampler", "sklearn/model_selection/tests/test_validation.py::test_learning_curve", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_with_method_rare_class", "sklearn/model_selection/tests/test_search.py::test_grid_search_groups", "sklearn/model_selection/tests/test_search.py::test_gridsearch_nd", "sklearn/model_selection/tests/test_validation.py::test_score", "sklearn/model_selection/tests/test_search.py::test_callable_multimetric_confusion_matrix", "sklearn/model_selection/tests/test_search.py::test_searchcv_raise_warning_with_non_finite_score[RandomizedSearchCV-specialized_params1-True]", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_incremental_learning", "sklearn/model_selection/tests/test_search.py::test_refit_callable_out_bound[RandomizedSearchCV--1]", "sklearn/model_selection/tests/test_search.py::test_scalar_fit_param[RandomizedSearchCV-param_search1]", "sklearn/model_selection/tests/test_search.py::test_refit", "sklearn/model_selection/tests/test_search.py::test_grid_search_with_multioutput_data", "sklearn/model_selection/tests/test_validation.py::test_callable_multimetric_confusion_matrix_cross_validate", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[False-False-raise]", "sklearn/model_selection/tests/test_search.py::test_validate_parameter_input[input2-TypeError-Parameter.* value is not iterable .*\\\\(key='foo', value=0\\\\)-klass1]", "sklearn/model_selection/tests/test_search.py::test_search_cv_pairwise_property_equivalence_of_precomputed", "sklearn/model_selection/tests/test_search.py::test_unsupervised_grid_search", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_decision_function_shape", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_with_shuffle", "sklearn/model_selection/tests/test_validation.py::test_validation_curve_fit_params", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_incremental_learning_unsupervised", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_precomputed", "sklearn/model_selection/tests/test_search.py::test_grid_search_precomputed_kernel", "sklearn/model_selection/tests/test_search.py::test_validate_parameter_input[0-TypeError-Parameter .* is not a dict or a list \\\\(0\\\\)-ParameterGrid]", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[False-True-0]", "sklearn/model_selection/tests/test_validation.py::test_permutation_test_score_fit_params", "sklearn/model_selection/tests/test_search.py::test_SearchCV_with_fit_params[GridSearchCV]", "sklearn/model_selection/tests/test_search.py::test_validate_parameter_input[input1-TypeError-Parameter .* is not a dict \\\\(0\\\\)-ParameterGrid]", "sklearn/model_selection/tests/test_validation.py::test_check_is_permutation", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_incremental_learning_fit_params", "sklearn/model_selection/tests/test_search.py::test_refit_callable_out_bound[GridSearchCV--1]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_with_score_func_classification", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_with_method_multilabel_rf", "sklearn/model_selection/tests/test_search.py::test_random_search_cv_results", "sklearn/model_selection/tests/test_search.py::test_search_train_scores_set_to_false", "sklearn/model_selection/tests/test_search.py::test_custom_run_search", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_pandas", "sklearn/model_selection/tests/test_search.py::test_refit_callable_out_bound[GridSearchCV-2]", "sklearn/model_selection/tests/test_search.py::test_classes__property", "sklearn/model_selection/tests/test_search.py::test_search_cv_using_minimal_compatible_estimator[MinimalClassifier-RandomizedSearchCV]", "sklearn/model_selection/tests/test_search.py::test_grid_search_when_param_grid_includes_range", "sklearn/model_selection/tests/test_search.py::test_grid_search_sparse_scoring", "sklearn/model_selection/tests/test_search.py::test_grid_search_cv_results_multimetric", "sklearn/model_selection/tests/test_validation.py::test_fit_and_score_verbosity[False-three_params_scorer-2-split_prg0-cdt_prg0-\\\\[CV\\\\] END .................................................... total time= 0.\\\\ds]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_multilabel", "sklearn/model_selection/tests/test_search.py::test_grid_search_allows_nans", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_unsupervised", "sklearn/model_selection/tests/test_search.py::test_grid_search_failing_classifier_raise", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_predict_log_proba_shape", "sklearn/model_selection/tests/test_search.py::test_scalar_fit_param_compat[GridSearchCV-param_search0]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_input_types", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_with_method_multilabel_rf_rare_class", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_fit_params", "sklearn/model_selection/tests/test_search.py::test_stochastic_gradient_loss_param", "sklearn/model_selection/tests/test_search.py::test_grid_search_no_score", "sklearn/model_selection/tests/test_search.py::test_refit_callable_invalid_type", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_mask", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_with_boolean_indices", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[True-False-0]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_errors", "sklearn/model_selection/tests/test_search.py::test_search_cv_pairwise_property_delegated_to_base_estimator[False]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_sparse_prediction", "sklearn/model_selection/tests/test_search.py::test_validate_parameter_input[0-TypeError-Parameter .* is not a dict or a list \\\\(0\\\\)-klass1]", "sklearn/model_selection/tests/test_search.py::test_search_cv_verbose_3[False]", "sklearn/model_selection/tests/test_search.py::test_grid_search_pipeline_steps", "sklearn/model_selection/tests/test_search.py::test_parameter_grid", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_incremental_learning_not_possible", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[True-False-nan]", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[False-False-0]", "sklearn/model_selection/tests/test_search.py::test_grid_search", "sklearn/model_selection/tests/test_search.py::test_searchcv_raise_warning_with_non_finite_score[GridSearchCV-specialized_params0-True]", "sklearn/model_selection/tests/test_search.py::test_search_cv_using_minimal_compatible_estimator[MinimalRegressor-GridSearchCV]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_method_checking", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[False-True-raise]", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_remove_duplicate_sample_sizes", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_failing_scorer[nan]", "sklearn/model_selection/tests/test_search.py::test_grid_search_correct_score_results", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_unbalanced", "sklearn/model_selection/tests/test_search.py::test_parameters_sampler_replacement", "sklearn/model_selection/tests/test_validation.py::test_validation_curve", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[True-True-raise]", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[True-True-nan]", "sklearn/model_selection/tests/test_search.py::test_search_cv_results_rank_tie_breaking", "sklearn/model_selection/tests/test_search.py::test_searchcv_raise_warning_with_non_finite_score[RandomizedSearchCV-specialized_params1-False]", "sklearn/model_selection/tests/test_search.py::test_grid_search_score_method", "sklearn/model_selection/tests/test_search.py::test_pandas_input", "sklearn/model_selection/tests/test_search.py::test_search_cv_score_samples_method[search_cv0]", "sklearn/model_selection/tests/test_search.py::test_search_cv_score_samples_method[search_cv1]", "sklearn/model_selection/tests/test_search.py::test_empty_cv_iterator_error", "sklearn/model_selection/tests/test_search.py::test_random_search_cv_results_multimetric", "sklearn/model_selection/tests/test_search.py::test_search_cv_score_samples_error[search_cv1]" ]
[ "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_fits_warnings[nan]", "sklearn/model_selection/tests/test_search.py::test_callable_multimetric_clf_all_fails", "sklearn/model_selection/tests/test_search.py::test_grid_search_failing_classifier", "sklearn/model_selection/tests/test_search.py::test_callable_multimetric_error_failing_clf", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_fits_warnings[0]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 2f7e7590a1c6b..6685ca582428a 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -488,6 +488,9 @@ Changelog\n :pr:`<PRID>` by :user:`<NAME>` and\n :user:`<NAME>`.\n \n+- |Enhancement| warn only once in the main process for per-split fit failures\n+ in cross-validation. :pr:`<PRID>` by :user:`<NAME>`\n+\n :mod:`sklearn.naive_bayes`\n ..........................\n \n" } ]
diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index 2f7e7590a1c6b..6685ca582428a 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -488,6 +488,9 @@ Changelog :pr:`<PRID>` by :user:`<NAME>` and :user:`<NAME>`. +- |Enhancement| warn only once in the main process for per-split fit failures + in cross-validation. :pr:`<PRID>` by :user:`<NAME>` + :mod:`sklearn.naive_bayes` ..........................
scikit-learn/scikit-learn
scikit-learn__scikit-learn-17367
https://github.com/scikit-learn/scikit-learn/pull/17367
diff --git a/doc/modules/feature_extraction.rst b/doc/modules/feature_extraction.rst index cedc43c23c16c..5091930ec0348 100644 --- a/doc/modules/feature_extraction.rst +++ b/doc/modules/feature_extraction.rst @@ -56,6 +56,27 @@ is a traditional numerical feature:: >>> vec.get_feature_names() ['city=Dubai', 'city=London', 'city=San Francisco', 'temperature'] +:class:`DictVectorizer` accepts multiple string values for one +feature, like, e.g., multiple categories for a movie. + +Assume a database classifies each movie using some categories (not mandatories) +and its year of release. + + >>> movie_entry = [{'category': ['thriller', 'drama'], 'year': 2003}, + ... {'category': ['animation', 'family'], 'year': 2011}, + ... {'year': 1974}] + >>> vec.fit_transform(movie_entry).toarray() + array([[0.000e+00, 1.000e+00, 0.000e+00, 1.000e+00, 2.003e+03], + [1.000e+00, 0.000e+00, 1.000e+00, 0.000e+00, 2.011e+03], + [0.000e+00, 0.000e+00, 0.000e+00, 0.000e+00, 1.974e+03]]) + >>> vec.get_feature_names() == ['category=animation', 'category=drama', + ... 'category=family', 'category=thriller', + ... 'year'] + True + >>> vec.transform({'category': ['thriller'], + ... 'unseen_feature': '3'}).toarray() + array([[0., 0., 0., 1., 0.]]) + :class:`DictVectorizer` is also a useful representation transformation for training sequence classifiers in Natural Language Processing models that typically work by extracting feature windows around a particular diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index 53cbe13161151..de236edc0187c 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -162,6 +162,13 @@ Changelog :class:`exceptions.NonBLASDotWarning` are deprecated and will be removed in v0.26, :pr:`17804` by `Adrin Jalali`_. +:mod:`sklearn.feature_extraction` +................................. + +- |Enhancement| :class:`feature_extraction.DictVectorizer` accepts multiple + values for one categorical feature. :pr:`17367` by :user:`Peng Yu <yupbank>` + and :user:`Chiara Marmo <cmarmo>` + :mod:`sklearn.feature_selection` ................................ diff --git a/sklearn/feature_extraction/_dict_vectorizer.py b/sklearn/feature_extraction/_dict_vectorizer.py index 1e7d53aa3c5a0..bd6486a9b1717 100644 --- a/sklearn/feature_extraction/_dict_vectorizer.py +++ b/sklearn/feature_extraction/_dict_vectorizer.py @@ -3,8 +3,9 @@ # License: BSD 3 clause from array import array -from collections.abc import Mapping +from collections.abc import Mapping, Iterable from operator import itemgetter +from numbers import Number import numpy as np import scipy.sparse as sp @@ -35,10 +36,15 @@ class DictVectorizer(TransformerMixin, BaseEstimator): a feature "f" that can take on the values "ham" and "spam" will become two features in the output, one signifying "f=ham", the other "f=spam". + If a feature value is a sequence or set of strings, this transformer + will iterate over the values and will count the occurrences of each string + value. + However, note that this transformer will only do a binary one-hot encoding when feature values are of type string. If categorical features are - represented as numeric values such as int, the DictVectorizer can be - followed by :class:`~sklearn.preprocessing.OneHotEncoder` to complete + represented as numeric values such as int or iterables of strings, the + DictVectorizer can be followed by + :class:`~sklearn.preprocessing.OneHotEncoder` to complete binary one-hot encoding. Features that do not occur in a sample (mapping) will have a zero value @@ -78,8 +84,8 @@ class DictVectorizer(TransformerMixin, BaseEstimator): >>> X array([[2., 0., 1.], [0., 1., 3.]]) - >>> v.inverse_transform(X) == \ - [{'bar': 2.0, 'foo': 1.0}, {'baz': 1.0, 'foo': 3.0}] + >>> v.inverse_transform(X) == [{'bar': 2.0, 'foo': 1.0}, + ... {'baz': 1.0, 'foo': 3.0}] True >>> v.transform({'foo': 4, 'unseen_feature': 3}) array([[0., 0., 4.]]) @@ -98,6 +104,28 @@ def __init__(self, *, dtype=np.float64, separator="=", sparse=True, self.sparse = sparse self.sort = sort + def _add_iterable_element(self, f, v, feature_names, vocab, *, + fitting=True, transforming=False, + indices=None, values=None): + """Add feature names for iterable of strings""" + for vv in v: + if isinstance(vv, str): + feature_name = "%s%s%s" % (f, self.separator, vv) + vv = 1 + else: + raise TypeError(f'Unsupported type {type(vv)} in iterable ' + 'value. Only iterables of string are ' + 'supported.') + if fitting and feature_name not in vocab: + vocab[feature_name] = len(feature_names) + feature_names.append(feature_name) + + if transforming and feature_name in vocab: + indices.append(vocab[feature_name]) + values.append(self.dtype(vv)) + + return + def fit(self, X, y=None): """Learn a list of feature name -> indices mappings. @@ -106,6 +134,10 @@ def fit(self, X, y=None): X : Mapping or iterable over Mappings Dict(s) or Mapping(s) from feature names (arbitrary Python objects) to feature values (strings or convertible to dtype). + + .. versionchanged:: 0.24 + Accepts multiple string values for one categorical feature. + y : (ignored) Returns @@ -118,10 +150,22 @@ def fit(self, X, y=None): for x in X: for f, v in x.items(): if isinstance(v, str): - f = "%s%s%s" % (f, self.separator, v) - if f not in vocab: - feature_names.append(f) - vocab[f] = len(vocab) + feature_name = "%s%s%s" % (f, self.separator, v) + v = 1 + elif isinstance(v, Number) or (v is None): + feature_name = f + elif isinstance(v, Mapping): + raise TypeError(f'Unsupported value type {type(v)} ' + f'for {f}: {v}.\n' + 'Mapping objects are not supported.') + elif isinstance(v, Iterable): + feature_name = None + self._add_iterable_element(f, v, feature_names, vocab) + + if feature_name is not None: + if feature_name not in vocab: + vocab[feature_name] = len(feature_names) + feature_names.append(feature_name) if self.sort: feature_names.sort() @@ -150,6 +194,8 @@ def _transform(self, X, fitting): feature_names = self.feature_names_ vocab = self.vocabulary_ + transforming = True + # Process everything as sparse regardless of setting X = [X] if isinstance(X, Mapping) else X @@ -164,17 +210,29 @@ def _transform(self, X, fitting): for x in X: for f, v in x.items(): if isinstance(v, str): - f = "%s%s%s" % (f, self.separator, v) + feature_name = "%s%s%s" % (f, self.separator, v) v = 1 - if f in vocab: - indices.append(vocab[f]) - values.append(dtype(v)) - else: - if fitting: - feature_names.append(f) - vocab[f] = len(vocab) - indices.append(vocab[f]) - values.append(dtype(v)) + elif isinstance(v, Number) or (v is None): + feature_name = f + elif isinstance(v, Mapping): + raise TypeError(f'Unsupported value Type {type(v)} ' + f'for {f}: {v}.\n' + 'Mapping objects are not supported.') + elif isinstance(v, Iterable): + feature_name = None + self._add_iterable_element(f, v, feature_names, vocab, + fitting=fitting, + transforming=transforming, + indices=indices, values=values) + + if feature_name is not None: + if fitting and feature_name not in vocab: + vocab[feature_name] = len(feature_names) + feature_names.append(feature_name) + + if feature_name in vocab: + indices.append(vocab[feature_name]) + values.append(self.dtype(v)) indptr.append(len(indices)) @@ -218,6 +276,10 @@ def fit_transform(self, X, y=None): X : Mapping or iterable over Mappings Dict(s) or Mapping(s) from feature names (arbitrary Python objects) to feature values (strings or convertible to dtype). + + .. versionchanged:: 0.24 + Accepts multiple string values for one categorical feature. + y : (ignored) Returns
diff --git a/sklearn/feature_extraction/tests/test_dict_vectorizer.py b/sklearn/feature_extraction/tests/test_dict_vectorizer.py index 22a7402908cf1..519201b580598 100644 --- a/sklearn/feature_extraction/tests/test_dict_vectorizer.py +++ b/sklearn/feature_extraction/tests/test_dict_vectorizer.py @@ -76,6 +76,52 @@ def test_one_of_k(): assert "version" not in names +def test_iterable_value(): + D_names = ['ham', 'spam', 'version=1', 'version=2', 'version=3'] + X_expected = [[2.0, 0.0, 2.0, 1.0, 0.0], + [0.0, 0.3, 0.0, 1.0, 0.0], + [0.0, -1.0, 0.0, 0.0, 1.0]] + D_in = [{"version": ["1", "2", "1"], "ham": 2}, + {"version": "2", "spam": .3}, + {"version=3": True, "spam": -1}] + v = DictVectorizer() + X = v.fit_transform(D_in) + X = X.toarray() + assert_array_equal(X, X_expected) + + D_out = v.inverse_transform(X) + assert D_out[0] == {"version=1": 2, "version=2": 1, "ham": 2} + + names = v.get_feature_names() + + assert names == D_names + + +def test_iterable_not_string_error(): + error_value = ("Unsupported type <class 'int'> in iterable value. " + "Only iterables of string are supported.") + D2 = [{'foo': '1', 'bar': '2'}, + {'foo': '3', 'baz': '1'}, + {'foo': [1, 'three']}] + v = DictVectorizer(sparse=False) + with pytest.raises(TypeError) as error: + v.fit(D2) + assert str(error.value) == error_value + + +def test_mapping_error(): + error_value = ("Unsupported value type <class 'dict'> " + "for foo: {'one': 1, 'three': 3}.\n" + "Mapping objects are not supported.") + D2 = [{'foo': '1', 'bar': '2'}, + {'foo': '3', 'baz': '1'}, + {'foo': {'one': 1, 'three': 3}}] + v = DictVectorizer(sparse=False) + with pytest.raises(TypeError) as error: + v.fit(D2) + assert str(error.value) == error_value + + def test_unseen_or_no_features(): D = [{"camelot": 0, "spamalot": 1}] for sparse in [True, False]:
[ { "path": "doc/modules/feature_extraction.rst", "old_path": "a/doc/modules/feature_extraction.rst", "new_path": "b/doc/modules/feature_extraction.rst", "metadata": "diff --git a/doc/modules/feature_extraction.rst b/doc/modules/feature_extraction.rst\nindex cedc43c23c16c..5091930ec0348 100644\n--- a/doc/modules/feature_extraction.rst\n+++ b/doc/modules/feature_extraction.rst\n@@ -56,6 +56,27 @@ is a traditional numerical feature::\n >>> vec.get_feature_names()\n ['city=Dubai', 'city=London', 'city=San Francisco', 'temperature']\n \n+:class:`DictVectorizer` accepts multiple string values for one\n+feature, like, e.g., multiple categories for a movie.\n+\n+Assume a database classifies each movie using some categories (not mandatories)\n+and its year of release.\n+\n+ >>> movie_entry = [{'category': ['thriller', 'drama'], 'year': 2003},\n+ ... {'category': ['animation', 'family'], 'year': 2011},\n+ ... {'year': 1974}]\n+ >>> vec.fit_transform(movie_entry).toarray()\n+ array([[0.000e+00, 1.000e+00, 0.000e+00, 1.000e+00, 2.003e+03],\n+ [1.000e+00, 0.000e+00, 1.000e+00, 0.000e+00, 2.011e+03],\n+ [0.000e+00, 0.000e+00, 0.000e+00, 0.000e+00, 1.974e+03]])\n+ >>> vec.get_feature_names() == ['category=animation', 'category=drama',\n+ ... 'category=family', 'category=thriller',\n+ ... 'year']\n+ True\n+ >>> vec.transform({'category': ['thriller'],\n+ ... 'unseen_feature': '3'}).toarray()\n+ array([[0., 0., 0., 1., 0.]])\n+\n :class:`DictVectorizer` is also a useful representation transformation\n for training sequence classifiers in Natural Language Processing models\n that typically work by extracting feature windows around a particular\n" }, { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex 53cbe13161151..de236edc0187c 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -162,6 +162,13 @@ Changelog\n :class:`exceptions.NonBLASDotWarning` are deprecated and will be removed in\n v0.26, :pr:`17804` by `Adrin Jalali`_.\n \n+:mod:`sklearn.feature_extraction`\n+.................................\n+\n+- |Enhancement| :class:`feature_extraction.DictVectorizer` accepts multiple\n+ values for one categorical feature. :pr:`17367` by :user:`Peng Yu <yupbank>`\n+ and :user:`Chiara Marmo <cmarmo>`\n+\n :mod:`sklearn.feature_selection`\n ................................\n \n" } ]
0.24
e087f8a395f9db97145654c2429b7bdd107fd440
[ "sklearn/feature_extraction/tests/test_dict_vectorizer.py::test_dictvectorizer[True-True-int16-False]", "sklearn/feature_extraction/tests/test_dict_vectorizer.py::test_dictvectorizer[False-False-int-False]", "sklearn/feature_extraction/tests/test_dict_vectorizer.py::test_dictvectorizer[False-True-float32-False]", "sklearn/feature_extraction/tests/test_dict_vectorizer.py::test_unseen_or_no_features", "sklearn/feature_extraction/tests/test_dict_vectorizer.py::test_feature_selection", "sklearn/feature_extraction/tests/test_dict_vectorizer.py::test_dictvectorizer[False-False-float32-False]", "sklearn/feature_extraction/tests/test_dict_vectorizer.py::test_dictvectorizer[False-False-int16-False]", "sklearn/feature_extraction/tests/test_dict_vectorizer.py::test_dictvectorizer[True-True-int16-True]", "sklearn/feature_extraction/tests/test_dict_vectorizer.py::test_dictvectorizer[True-True-float32-False]", "sklearn/feature_extraction/tests/test_dict_vectorizer.py::test_dictvectorizer[True-False-float32-True]", "sklearn/feature_extraction/tests/test_dict_vectorizer.py::test_one_of_k", "sklearn/feature_extraction/tests/test_dict_vectorizer.py::test_deterministic_vocabulary", "sklearn/feature_extraction/tests/test_dict_vectorizer.py::test_dictvectorizer[False-False-int16-True]", "sklearn/feature_extraction/tests/test_dict_vectorizer.py::test_dictvectorizer[True-True-int-True]", "sklearn/feature_extraction/tests/test_dict_vectorizer.py::test_n_features_in", "sklearn/feature_extraction/tests/test_dict_vectorizer.py::test_dictvectorizer[True-True-int-False]", "sklearn/feature_extraction/tests/test_dict_vectorizer.py::test_dictvectorizer[False-True-int-True]", "sklearn/feature_extraction/tests/test_dict_vectorizer.py::test_dictvectorizer[True-False-int16-False]", "sklearn/feature_extraction/tests/test_dict_vectorizer.py::test_dictvectorizer[True-False-int-True]", "sklearn/feature_extraction/tests/test_dict_vectorizer.py::test_dictvectorizer[False-False-float32-True]", "sklearn/feature_extraction/tests/test_dict_vectorizer.py::test_dictvectorizer[False-True-float32-True]", "sklearn/feature_extraction/tests/test_dict_vectorizer.py::test_dictvectorizer[False-True-int16-True]", "sklearn/feature_extraction/tests/test_dict_vectorizer.py::test_dictvectorizer[True-False-float32-False]", "sklearn/feature_extraction/tests/test_dict_vectorizer.py::test_dictvectorizer[False-True-int-False]", "sklearn/feature_extraction/tests/test_dict_vectorizer.py::test_dictvectorizer[True-True-float32-True]", "sklearn/feature_extraction/tests/test_dict_vectorizer.py::test_dictvectorizer[True-False-int-False]", "sklearn/feature_extraction/tests/test_dict_vectorizer.py::test_dictvectorizer[True-False-int16-True]", "sklearn/feature_extraction/tests/test_dict_vectorizer.py::test_dictvectorizer[False-False-int-True]", "sklearn/feature_extraction/tests/test_dict_vectorizer.py::test_dictvectorizer[False-True-int16-False]" ]
[ "sklearn/feature_extraction/tests/test_dict_vectorizer.py::test_mapping_error", "sklearn/feature_extraction/tests/test_dict_vectorizer.py::test_iterable_not_string_error", "sklearn/feature_extraction/tests/test_dict_vectorizer.py::test_iterable_value" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/modules/feature_extraction.rst", "old_path": "a/doc/modules/feature_extraction.rst", "new_path": "b/doc/modules/feature_extraction.rst", "metadata": "diff --git a/doc/modules/feature_extraction.rst b/doc/modules/feature_extraction.rst\nindex cedc43c23c16c..5091930ec0348 100644\n--- a/doc/modules/feature_extraction.rst\n+++ b/doc/modules/feature_extraction.rst\n@@ -56,6 +56,27 @@ is a traditional numerical feature::\n >>> vec.get_feature_names()\n ['city=Dubai', 'city=London', 'city=San Francisco', 'temperature']\n \n+:class:`DictVectorizer` accepts multiple string values for one\n+feature, like, e.g., multiple categories for a movie.\n+\n+Assume a database classifies each movie using some categories (not mandatories)\n+and its year of release.\n+\n+ >>> movie_entry = [{'category': ['thriller', 'drama'], 'year': 2003},\n+ ... {'category': ['animation', 'family'], 'year': 2011},\n+ ... {'year': 1974}]\n+ >>> vec.fit_transform(movie_entry).toarray()\n+ array([[0.000e+00, 1.000e+00, 0.000e+00, 1.000e+00, 2.003e+03],\n+ [1.000e+00, 0.000e+00, 1.000e+00, 0.000e+00, 2.011e+03],\n+ [0.000e+00, 0.000e+00, 0.000e+00, 0.000e+00, 1.974e+03]])\n+ >>> vec.get_feature_names() == ['category=animation', 'category=drama',\n+ ... 'category=family', 'category=thriller',\n+ ... 'year']\n+ True\n+ >>> vec.transform({'category': ['thriller'],\n+ ... 'unseen_feature': '3'}).toarray()\n+ array([[0., 0., 0., 1., 0.]])\n+\n :class:`DictVectorizer` is also a useful representation transformation\n for training sequence classifiers in Natural Language Processing models\n that typically work by extracting feature windows around a particular\n" }, { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex 53cbe13161151..de236edc0187c 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -162,6 +162,13 @@ Changelog\n :class:`exceptions.NonBLASDotWarning` are deprecated and will be removed in\n v0.26, :pr:`<PRID>` by `<NAME>`_.\n \n+:mod:`sklearn.feature_extraction`\n+.................................\n+\n+- |Enhancement| :class:`feature_extraction.DictVectorizer` accepts multiple\n+ values for one categorical feature. :pr:`<PRID>` by :user:`<NAME>`\n+ and :user:`<NAME>`\n+\n :mod:`sklearn.feature_selection`\n ................................\n \n" } ]
diff --git a/doc/modules/feature_extraction.rst b/doc/modules/feature_extraction.rst index cedc43c23c16c..5091930ec0348 100644 --- a/doc/modules/feature_extraction.rst +++ b/doc/modules/feature_extraction.rst @@ -56,6 +56,27 @@ is a traditional numerical feature:: >>> vec.get_feature_names() ['city=Dubai', 'city=London', 'city=San Francisco', 'temperature'] +:class:`DictVectorizer` accepts multiple string values for one +feature, like, e.g., multiple categories for a movie. + +Assume a database classifies each movie using some categories (not mandatories) +and its year of release. + + >>> movie_entry = [{'category': ['thriller', 'drama'], 'year': 2003}, + ... {'category': ['animation', 'family'], 'year': 2011}, + ... {'year': 1974}] + >>> vec.fit_transform(movie_entry).toarray() + array([[0.000e+00, 1.000e+00, 0.000e+00, 1.000e+00, 2.003e+03], + [1.000e+00, 0.000e+00, 1.000e+00, 0.000e+00, 2.011e+03], + [0.000e+00, 0.000e+00, 0.000e+00, 0.000e+00, 1.974e+03]]) + >>> vec.get_feature_names() == ['category=animation', 'category=drama', + ... 'category=family', 'category=thriller', + ... 'year'] + True + >>> vec.transform({'category': ['thriller'], + ... 'unseen_feature': '3'}).toarray() + array([[0., 0., 0., 1., 0.]]) + :class:`DictVectorizer` is also a useful representation transformation for training sequence classifiers in Natural Language Processing models that typically work by extracting feature windows around a particular diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index 53cbe13161151..de236edc0187c 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -162,6 +162,13 @@ Changelog :class:`exceptions.NonBLASDotWarning` are deprecated and will be removed in v0.26, :pr:`<PRID>` by `<NAME>`_. +:mod:`sklearn.feature_extraction` +................................. + +- |Enhancement| :class:`feature_extraction.DictVectorizer` accepts multiple + values for one categorical feature. :pr:`<PRID>` by :user:`<NAME>` + and :user:`<NAME>` + :mod:`sklearn.feature_selection` ................................
scikit-learn/scikit-learn
scikit-learn__scikit-learn-17379
https://github.com/scikit-learn/scikit-learn/pull/17379
diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index 9e31762d62c29..b5d0145af4822 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -158,6 +158,9 @@ Changelog :pr:`16289` by :user:`Masashi Kishimoto <kishimoto-banana>` and :user:`Olivier Grisel <ogrisel>`. +- |Enhancement| :class:`isotonic.IsotonicRegression` now accepts 2darray with 1 feature as + input array. :pr:`17379` by :user:`Jiaxiang <fujiaxiang>`. + :mod:`sklearn.metrics` ...................... diff --git a/sklearn/isotonic.py b/sklearn/isotonic.py index 50fa0654f7585..905528d3b25f0 100644 --- a/sklearn/isotonic.py +++ b/sklearn/isotonic.py @@ -211,7 +211,7 @@ class IsotonicRegression(RegressorMixin, TransformerMixin, BaseEstimator): >>> from sklearn.datasets import make_regression >>> from sklearn.isotonic import IsotonicRegression >>> X, y = make_regression(n_samples=10, n_features=1, random_state=41) - >>> iso_reg = IsotonicRegression().fit(X.flatten(), y) + >>> iso_reg = IsotonicRegression().fit(X, y) >>> iso_reg.predict([.1, .2]) array([1.8628..., 3.7256...]) """ @@ -223,9 +223,11 @@ def __init__(self, *, y_min=None, y_max=None, increasing=True, self.increasing = increasing self.out_of_bounds = out_of_bounds - def _check_fit_data(self, X, y, sample_weight=None): - if len(X.shape) != 1: - raise ValueError("X should be a 1d array") + def _check_input_data_shape(self, X): + if not (X.ndim == 1 or (X.ndim == 2 and X.shape[1] == 1)): + msg = "Isotonic regression input X should be a 1d array or " \ + "2d array with 1 feature" + raise ValueError(msg) def _build_f(self, X, y): """Build the f_ interp1d function.""" @@ -246,7 +248,8 @@ def _build_f(self, X, y): def _build_y(self, X, y, sample_weight, trim_duplicates=True): """Build the y_ IsotonicRegression.""" - self._check_fit_data(X, y, sample_weight) + self._check_input_data_shape(X) + X = X.reshape(-1) # use 1d view # Determine increasing if auto-determination requested if self.increasing == 'auto': @@ -295,7 +298,7 @@ def fit(self, X, y, sample_weight=None): Parameters ---------- - X : array-like of shape (n_samples,) + X : array-like of shape (n_samples,) or (n_samples, 1) Training data. y : array-like of shape (n_samples,) @@ -339,7 +342,7 @@ def transform(self, T): Parameters ---------- - T : array-like of shape (n_samples,) + T : array-like of shape (n_samples,) or (n_samples, 1) Data to transform. Returns @@ -355,8 +358,8 @@ def transform(self, T): T = check_array(T, dtype=dtype, ensure_2d=False) - if len(T.shape) != 1: - raise ValueError("Isotonic regression input should be a 1d array") + self._check_input_data_shape(T) + T = T.reshape(-1) # use 1d view # Handle the out_of_bounds argument by clipping if needed if self.out_of_bounds not in ["raise", "nan", "clip"]: @@ -379,7 +382,7 @@ def predict(self, T): Parameters ---------- - T : array-like of shape (n_samples,) + T : array-like of shape (n_samples,) or (n_samples, 1) Data to transform. Returns
diff --git a/sklearn/tests/test_isotonic.py b/sklearn/tests/test_isotonic.py index 3da76c1f0bb88..66892370f06f0 100644 --- a/sklearn/tests/test_isotonic.py +++ b/sklearn/tests/test_isotonic.py @@ -9,7 +9,8 @@ IsotonicRegression, _make_unique) from sklearn.utils.validation import check_array -from sklearn.utils._testing import (assert_raises, assert_array_equal, +from sklearn.utils._testing import (assert_raises, assert_allclose, + assert_array_equal, assert_array_almost_equal, assert_warns_message, assert_no_warnings) from sklearn.utils import shuffle @@ -535,3 +536,43 @@ def test_isotonic_thresholds(increasing): assert all(np.diff(y_thresholds) >= 0) else: assert all(np.diff(y_thresholds) <= 0) + + +def test_input_shape_validation(): + # Test from #15012 + # Check that IsotonicRegression can handle 2darray with only 1 feature + X = np.arange(10) + X_2d = X.reshape(-1, 1) + y = np.arange(10) + + iso_reg = IsotonicRegression().fit(X, y) + iso_reg_2d = IsotonicRegression().fit(X_2d, y) + + assert iso_reg.X_max_ == iso_reg_2d.X_max_ + assert iso_reg.X_min_ == iso_reg_2d.X_min_ + assert iso_reg.y_max == iso_reg_2d.y_max + assert iso_reg.y_min == iso_reg_2d.y_min + assert_array_equal(iso_reg.X_thresholds_, iso_reg_2d.X_thresholds_) + assert_array_equal(iso_reg.y_thresholds_, iso_reg_2d.y_thresholds_) + + y_pred1 = iso_reg.predict(X) + y_pred2 = iso_reg_2d.predict(X_2d) + assert_allclose(y_pred1, y_pred2) + + +def test_isotonic_2darray_more_than_1_feature(): + # Ensure IsotonicRegression raises error if input has more than 1 feature + X = np.arange(10) + X_2d = np.c_[X, X] + y = np.arange(10) + + msg = "should be a 1d array or 2d array with 1 feature" + with pytest.raises(ValueError, match=msg): + IsotonicRegression().fit(X_2d, y) + + iso_reg = IsotonicRegression().fit(X, y) + with pytest.raises(ValueError, match=msg): + iso_reg.predict(X_2d) + + with pytest.raises(ValueError, match=msg): + iso_reg.transform(X_2d)
[ { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex 9e31762d62c29..b5d0145af4822 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -158,6 +158,9 @@ Changelog\n :pr:`16289` by :user:`Masashi Kishimoto <kishimoto-banana>` and\n :user:`Olivier Grisel <ogrisel>`.\n \n+- |Enhancement| :class:`isotonic.IsotonicRegression` now accepts 2darray with 1 feature as\n+ input array. :pr:`17379` by :user:`Jiaxiang <fujiaxiang>`.\n+\n :mod:`sklearn.metrics`\n ......................\n \n" } ]
0.24
3a49e5f209f08c00f73d8895cf27d228fbae25f1
[ "sklearn/tests/test_isotonic.py::test_isotonic_regression_oob_bad", "sklearn/tests/test_isotonic.py::test_check_increasing_down_extreme", "sklearn/tests/test_isotonic.py::test_isotonic_thresholds[True]", "sklearn/tests/test_isotonic.py::test_isotonic_sample_weight_parameter_default_value", "sklearn/tests/test_isotonic.py::test_isotonic_sample_weight", "sklearn/tests/test_isotonic.py::test_isotonic_regression_oob_raise", "sklearn/tests/test_isotonic.py::test_check_increasing_down", "sklearn/tests/test_isotonic.py::test_isotonic_regression_oob_nan", "sklearn/tests/test_isotonic.py::test_isotonic_regression_oob_clip", "sklearn/tests/test_isotonic.py::test_isotonic_regression_pickle", "sklearn/tests/test_isotonic.py::test_isotonic_ymin_ymax", "sklearn/tests/test_isotonic.py::test_make_unique_dtype", "sklearn/tests/test_isotonic.py::test_isotonic_regression_auto_decreasing", "sklearn/tests/test_isotonic.py::test_isotonic_mismatched_dtype[float64]", "sklearn/tests/test_isotonic.py::test_check_increasing_up_extreme", "sklearn/tests/test_isotonic.py::test_isotonic_zero_weight_loop", "sklearn/tests/test_isotonic.py::test_check_increasing_up", "sklearn/tests/test_isotonic.py::test_isotonic_mismatched_dtype[int32]", "sklearn/tests/test_isotonic.py::test_isotonic_mismatched_dtype[float32]", "sklearn/tests/test_isotonic.py::test_isotonic_duplicate_min_entry", "sklearn/tests/test_isotonic.py::test_isotonic_min_max_boundaries", "sklearn/tests/test_isotonic.py::test_assert_raises_exceptions", "sklearn/tests/test_isotonic.py::test_check_ci_warn", "sklearn/tests/test_isotonic.py::test_isotonic_copy_before_fit", "sklearn/tests/test_isotonic.py::test_isotonic_mismatched_dtype[int64]", "sklearn/tests/test_isotonic.py::test_isotonic_regression", "sklearn/tests/test_isotonic.py::test_isotonic_regression_ties_secondary_", "sklearn/tests/test_isotonic.py::test_isotonic_regression_with_ties_in_differently_sized_groups", "sklearn/tests/test_isotonic.py::test_fast_predict", "sklearn/tests/test_isotonic.py::test_isotonic_thresholds[False]", "sklearn/tests/test_isotonic.py::test_permutation_invariance", "sklearn/tests/test_isotonic.py::test_check_increasing_small_number_of_samples", "sklearn/tests/test_isotonic.py::test_isotonic_regression_ties_max", "sklearn/tests/test_isotonic.py::test_isotonic_dtype", "sklearn/tests/test_isotonic.py::test_isotonic_regression_reversed", "sklearn/tests/test_isotonic.py::test_isotonic_regression_ties_min", "sklearn/tests/test_isotonic.py::test_isotonic_regression_oob_bad_after", "sklearn/tests/test_isotonic.py::test_isotonic_regression_auto_increasing" ]
[ "sklearn/tests/test_isotonic.py::test_input_shape_validation", "sklearn/tests/test_isotonic.py::test_isotonic_2darray_more_than_1_feature" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex 9e31762d62c29..b5d0145af4822 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -158,6 +158,9 @@ Changelog\n :pr:`<PRID>` by :user:`<NAME>` and\n :user:`<NAME>`.\n \n+- |Enhancement| :class:`isotonic.IsotonicRegression` now accepts 2darray with 1 feature as\n+ input array. :pr:`<PRID>` by :user:`<NAME>`.\n+\n :mod:`sklearn.metrics`\n ......................\n \n" } ]
diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index 9e31762d62c29..b5d0145af4822 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -158,6 +158,9 @@ Changelog :pr:`<PRID>` by :user:`<NAME>` and :user:`<NAME>`. +- |Enhancement| :class:`isotonic.IsotonicRegression` now accepts 2darray with 1 feature as + input array. :pr:`<PRID>` by :user:`<NAME>`. + :mod:`sklearn.metrics` ......................
scikit-learn/scikit-learn
scikit-learn__scikit-learn-16906
https://github.com/scikit-learn/scikit-learn/pull/16906
diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index fcdd2b77c3c8c..07b59a7bed715 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -174,6 +174,10 @@ Changelog ``kind`` parameter. :pr:`16619` by :user:`Madhura Jayratne <madhuracj>`. +- |Feature| Add `sample_weight` parameter to + :func:`inspection.permutation_importance`. :pr:`16906` by + :user:`Roei Kahny <RoeiKa>`. + :mod:`sklearn.isotonic` ....................... diff --git a/sklearn/inspection/_permutation_importance.py b/sklearn/inspection/_permutation_importance.py index 8aa8766b727aa..616073194aa90 100644 --- a/sklearn/inspection/_permutation_importance.py +++ b/sklearn/inspection/_permutation_importance.py @@ -10,8 +10,14 @@ from ..utils.validation import _deprecate_positional_args -def _calculate_permutation_scores(estimator, X, y, col_idx, random_state, - n_repeats, scorer): +def _weights_scorer(scorer, estimator, X, y, sample_weight): + if sample_weight is not None: + return scorer(estimator, X, y, sample_weight) + return scorer(estimator, X, y) + + +def _calculate_permutation_scores(estimator, X, y, sample_weight, col_idx, + random_state, n_repeats, scorer): """Calculate score when `col_idx` is permuted.""" random_state = check_random_state(random_state) @@ -32,7 +38,9 @@ def _calculate_permutation_scores(estimator, X, y, col_idx, random_state, X_permuted.iloc[:, col_idx] = col else: X_permuted[:, col_idx] = X_permuted[shuffling_idx, col_idx] - feature_score = scorer(estimator, X_permuted, y) + feature_score = _weights_scorer( + scorer, estimator, X_permuted, y, sample_weight + ) scores[n_round] = feature_score return scores @@ -40,7 +48,7 @@ def _calculate_permutation_scores(estimator, X, y, col_idx, random_state, @_deprecate_positional_args def permutation_importance(estimator, X, y, *, scoring=None, n_repeats=5, - n_jobs=None, random_state=None): + n_jobs=None, random_state=None, sample_weight=None): """Permutation importance for feature evaluation [BRE]_. The :term:`estimator` is required to be a fitted estimator. `X` can be the @@ -87,6 +95,9 @@ def permutation_importance(estimator, X, y, *, scoring=None, n_repeats=5, Pass an int to get reproducible results across function calls. See :term: `Glossary <random_state>`. + sample_weight : array-like of shape (n_samples,), default=None + Sample weights used in scoring. + Returns ------- result : :class:`~sklearn.utils.Bunch` @@ -131,10 +142,10 @@ def permutation_importance(estimator, X, y, *, scoring=None, n_repeats=5, random_seed = random_state.randint(np.iinfo(np.int32).max + 1) scorer = check_scoring(estimator, scoring=scoring) - baseline_score = scorer(estimator, X, y) + baseline_score = _weights_scorer(scorer, estimator, X, y, sample_weight) scores = Parallel(n_jobs=n_jobs)(delayed(_calculate_permutation_scores)( - estimator, X, y, col_idx, random_seed, n_repeats, scorer + estimator, X, y, sample_weight, col_idx, random_seed, n_repeats, scorer ) for col_idx in range(X.shape[1])) importances = baseline_score - np.array(scores)
diff --git a/sklearn/inspection/tests/test_permutation_importance.py b/sklearn/inspection/tests/test_permutation_importance.py index 2b381e9a20b1a..99a1d09f4a7bf 100644 --- a/sklearn/inspection/tests/test_permutation_importance.py +++ b/sklearn/inspection/tests/test_permutation_importance.py @@ -351,3 +351,87 @@ def test_permutation_importance_large_memmaped_data(input_type): # permutating feature should not change the predictions expected_importances = np.zeros((n_features, n_repeats)) assert_allclose(expected_importances, r.importances) + + +def test_permutation_importance_sample_weight(): + # Creating data with 2 features and 1000 samples, where the target + # variable is a linear combination of the two features, such that + # in half of the samples the impact of feature 1 is twice the impact of + # feature 2, and vice versa on the other half of the samples. + rng = np.random.RandomState(1) + n_samples = 1000 + n_features = 2 + n_half_samples = n_samples // 2 + x = rng.normal(0.0, 0.001, (n_samples, n_features)) + y = np.zeros(n_samples) + y[:n_half_samples] = 2 * x[:n_half_samples, 0] + x[:n_half_samples, 1] + y[n_half_samples:] = x[n_half_samples:, 0] + 2 * x[n_half_samples:, 1] + + # Fitting linear regression with perfect prediction + lr = LinearRegression(fit_intercept=False) + lr.fit(x, y) + + # When all samples are weighted with the same weights, the ratio of + # the two features importance should equal to 1 on expectation (when using + # mean absolutes error as the loss function). + pi = permutation_importance(lr, x, y, random_state=1, + scoring='neg_mean_absolute_error', + n_repeats=200) + x1_x2_imp_ratio_w_none = pi.importances_mean[0] / pi.importances_mean[1] + assert x1_x2_imp_ratio_w_none == pytest.approx(1, 0.01) + + # When passing a vector of ones as the sample_weight, results should be + # the same as in the case that sample_weight=None. + w = np.ones(n_samples) + pi = permutation_importance(lr, x, y, random_state=1, + scoring='neg_mean_absolute_error', + n_repeats=200, sample_weight=w) + x1_x2_imp_ratio_w_ones = pi.importances_mean[0] / pi.importances_mean[1] + assert x1_x2_imp_ratio_w_ones == pytest.approx( + x1_x2_imp_ratio_w_none, 0.01) + + # When the ratio between the weights of the first half of the samples and + # the second half of the samples approaches to infinity, the ratio of + # the two features importance should equal to 2 on expectation (when using + # mean absolutes error as the loss function). + w = np.hstack([np.repeat(10.0 ** 10, n_half_samples), + np.repeat(1.0, n_half_samples)]) + lr.fit(x, y, w) + pi = permutation_importance(lr, x, y, random_state=1, + scoring='neg_mean_absolute_error', + n_repeats=200, + sample_weight=w) + x1_x2_imp_ratio_w = pi.importances_mean[0] / pi.importances_mean[1] + assert x1_x2_imp_ratio_w / x1_x2_imp_ratio_w_none == pytest.approx(2, 0.01) + + +def test_permutation_importance_no_weights_scoring_function(): + # Creating a scorer function that does not takes sample_weight + def my_scorer(estimator, X, y): + return 1 + + # Creating some data and estimator for the permutation test + x = np.array([[1, 2], [3, 4]]) + y = np.array([1, 2]) + w = np.array([1, 1]) + lr = LinearRegression() + lr.fit(x, y) + + # test that permutation_importance does not return error when + # sample_weight is None + try: + permutation_importance(lr, x, y, random_state=1, + scoring=my_scorer, + n_repeats=1) + except TypeError: + pytest.fail("permutation_test raised an error when using a scorer " + "function that does not accept sample_weight even though " + "sample_weight was None") + + # test that permutation_importance raise exception when sample_weight is + # not None + with pytest.raises(TypeError): + permutation_importance(lr, x, y, random_state=1, + scoring=my_scorer, + n_repeats=1, + sample_weight=w)
[ { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex fcdd2b77c3c8c..07b59a7bed715 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -174,6 +174,10 @@ Changelog\n ``kind`` parameter.\n :pr:`16619` by :user:`Madhura Jayratne <madhuracj>`.\n \n+- |Feature| Add `sample_weight` parameter to\n+ :func:`inspection.permutation_importance`. :pr:`16906` by\n+ :user:`Roei Kahny <RoeiKa>`.\n+\n :mod:`sklearn.isotonic`\n .......................\n \n" } ]
0.24
b4678ca8aa0687575e1e1d2809355aa6c6975b16
[ "sklearn/inspection/tests/test_permutation_importance.py::test_permutation_importance_no_weights_scoring_function", "sklearn/inspection/tests/test_permutation_importance.py::test_permutation_importance_correlated_feature_regression_pandas[1]", "sklearn/inspection/tests/test_permutation_importance.py::test_permutation_importance_correlated_feature_regression_pandas[2]", "sklearn/inspection/tests/test_permutation_importance.py::test_permutation_importance_large_memmaped_data[array]", "sklearn/inspection/tests/test_permutation_importance.py::test_permutation_importance_mixed_types_pandas", "sklearn/inspection/tests/test_permutation_importance.py::test_permutation_importance_equivalence_array_dataframe[2]", "sklearn/inspection/tests/test_permutation_importance.py::test_permutation_importance_large_memmaped_data[dataframe]", "sklearn/inspection/tests/test_permutation_importance.py::test_permutation_importance_correlated_feature_regression[2]", "sklearn/inspection/tests/test_permutation_importance.py::test_permutation_importance_linear_regresssion", "sklearn/inspection/tests/test_permutation_importance.py::test_permutation_importance_equivalence_array_dataframe[1]", "sklearn/inspection/tests/test_permutation_importance.py::test_permutation_importance_correlated_feature_regression[1]", "sklearn/inspection/tests/test_permutation_importance.py::test_permutation_importance_mixed_types", "sklearn/inspection/tests/test_permutation_importance.py::test_robustness_to_high_cardinality_noisy_feature[1]", "sklearn/inspection/tests/test_permutation_importance.py::test_permutation_importance_equivalence_array_dataframe[None]", "sklearn/inspection/tests/test_permutation_importance.py::test_robustness_to_high_cardinality_noisy_feature[2]", "sklearn/inspection/tests/test_permutation_importance.py::test_permutation_importance_equivalence_sequential_parallel" ]
[ "sklearn/inspection/tests/test_permutation_importance.py::test_permutation_importance_sample_weight" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex fcdd2b77c3c8c..07b59a7bed715 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -174,6 +174,10 @@ Changelog\n ``kind`` parameter.\n :pr:`<PRID>` by :user:`<NAME>`.\n \n+- |Feature| Add `sample_weight` parameter to\n+ :func:`inspection.permutation_importance`. :pr:`<PRID>` by\n+ :user:`<NAME>`.\n+\n :mod:`sklearn.isotonic`\n .......................\n \n" } ]
diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index fcdd2b77c3c8c..07b59a7bed715 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -174,6 +174,10 @@ Changelog ``kind`` parameter. :pr:`<PRID>` by :user:`<NAME>`. +- |Feature| Add `sample_weight` parameter to + :func:`inspection.permutation_importance`. :pr:`<PRID>` by + :user:`<NAME>`. + :mod:`sklearn.isotonic` .......................
scikit-learn/scikit-learn
scikit-learn__scikit-learn-17578
https://github.com/scikit-learn/scikit-learn/pull/17578
diff --git a/doc/modules/linear_model.rst b/doc/modules/linear_model.rst index c4767d0cb2d64..0120f0f69fafd 100644 --- a/doc/modules/linear_model.rst +++ b/doc/modules/linear_model.rst @@ -43,6 +43,8 @@ and will store the coefficients :math:`w` of the linear model in its >>> from sklearn import linear_model >>> reg = linear_model.LinearRegression() + >>> reg.fit ([[0, 0], [1, 1], [2, 2]], [0, 1, 2]) + LinearRegression() >>> reg.fit([[0, 0], [1, 1], [2, 2]], [0, 1, 2]) LinearRegression() >>> reg.coef_ @@ -61,6 +63,19 @@ example, when data are collected without an experimental design. * :ref:`sphx_glr_auto_examples_linear_model_plot_ols.py` +Non-Negative Least Squares +-------------------------- + +It is possible to constrain all the coefficients to be non-negative, which may +be useful when they represent some physical or naturally non-negative +quantities (e.g., frequency counts or prices of goods). +:class:`LinearRegression` accepts a boolean ``positive`` +parameter: when set to `True` `Non Negative Least Squares +<https://en.wikipedia.org/wiki/Non-negative_least_squares>`_ are then applied. + +.. topic:: Examples: + + * :ref:`sphx_glr_auto_examples_linear_model_plot_nnls.py` Ordinary Least Squares Complexity --------------------------------- diff --git a/doc/tutorial/statistical_inference/supervised_learning.rst b/doc/tutorial/statistical_inference/supervised_learning.rst index 9913829f8f054..18a7f1336da11 100644 --- a/doc/tutorial/statistical_inference/supervised_learning.rst +++ b/doc/tutorial/statistical_inference/supervised_learning.rst @@ -173,7 +173,7 @@ Linear models: :math:`y = X\beta + \epsilon` >>> regr = linear_model.LinearRegression() >>> regr.fit(diabetes_X_train, diabetes_y_train) LinearRegression() - >>> print(regr.coef_) # doctest: +SKIP + >>> print(regr.coef_) [ 0.30349955 -237.63931533 510.53060544 327.73698041 -814.13170937 492.81458798 102.84845219 184.60648906 743.51961675 76.09517222] diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index a1a81b7571e28..b67004f1e8b00 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -203,6 +203,14 @@ Changelog - |Enhancement| :class:`isotonic.IsotonicRegression` now accepts 2darray with 1 feature as input array. :pr:`17379` by :user:`Jiaxiang <fujiaxiang>`. +:mod:`sklearn.linear_model` +........................... + +- |Feature| :class:`linear_model.LinearRegression` now forces coefficients + to be all positive when ``positive`` is set to ``True``. + :pr:`17578` by :user:`Joseph Knox <jknox13>`, :user:`Nelle Varoquaux <NelleV>` + and :user:`Chiara Marmo <cmarmo>`. + :mod:`sklearn.manifold` ....................... diff --git a/examples/linear_model/plot_nnls.py b/examples/linear_model/plot_nnls.py new file mode 100644 index 0000000000000..56f357c4214a6 --- /dev/null +++ b/examples/linear_model/plot_nnls.py @@ -0,0 +1,67 @@ +""" +========================== +Non-negative least squares +========================== + +In this example, we fit a linear model with positive constraints on the +regression coefficients and compare the estimated coefficients to a classic +linear regression. +""" +print(__doc__) +import numpy as np +import matplotlib.pyplot as plt +from sklearn.metrics import r2_score + +# %% +# Generate some random data +np.random.seed(42) + +n_samples, n_features = 200, 50 +X = np.random.randn(n_samples, n_features) +true_coef = 3 * np.random.randn(n_features) +# Threshold coefficients to render them non-negative +true_coef[true_coef < 0] = 0 +y = np.dot(X, true_coef) + +# Add some noise +y += 5 * np.random.normal(size=(n_samples, )) + +# %% +# Split the data in train set and test set +from sklearn.model_selection import train_test_split + +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5) + +# %% +# Fit the Non-Negative least squares. +from sklearn.linear_model import LinearRegression + +reg_nnls = LinearRegression(positive=True) +y_pred_nnls = reg_nnls.fit(X_train, y_train).predict(X_test) +r2_score_nnls = r2_score(y_test, y_pred_nnls) +print("NNLS R2 score", r2_score_nnls) + +# %% +# Fit an OLS. +reg_ols = LinearRegression() +y_pred_ols = reg_ols.fit(X_train, y_train).predict(X_test) +r2_score_ols = r2_score(y_test, y_pred_ols) +print("OLS R2 score", r2_score_ols) + + +# %% +# Comparing the regression coefficients between OLS and NNLS, we can observe +# they are highly correlated (the dashed line is the identity relation), +# but the non-negative constraint shrinks some to 0. +# The Non-Negative Least squares inherently yield sparse results. + +fig, ax = plt.subplots() +ax.plot(reg_ols.coef_, reg_nnls.coef_, linewidth=0, marker=".") + +low_x, high_x = ax.get_xlim() +low_y, high_y = ax.get_ylim() +low = max(low_x, low_y) +high = min(high_x, high_y) +ax.plot([low, high], [low, high], ls="--", c=".3", alpha=.5) +ax.set_xlabel("OLS regression coefficients", fontweight="bold") +ax.set_ylabel("NNLS regression coefficients", fontweight="bold") diff --git a/sklearn/linear_model/_base.py b/sklearn/linear_model/_base.py index 4ab797578dbde..d39308c97866e 100644 --- a/sklearn/linear_model/_base.py +++ b/sklearn/linear_model/_base.py @@ -20,6 +20,7 @@ import numpy as np import scipy.sparse as sp from scipy import linalg +from scipy import optimize from scipy import sparse from scipy.special import expit from joblib import Parallel, delayed @@ -419,6 +420,12 @@ class LinearRegression(MultiOutputMixin, RegressorMixin, LinearModel): ``-1`` means using all processors. See :term:`Glossary <n_jobs>` for more details. + positive : bool, default=False + When set to ``True``, forces the coefficients to be positive. This + option is only supported for dense arrays. + + .. versionadded:: 0.24 + Attributes ---------- coef_ : array of shape (n_features, ) or (n_targets, n_features) @@ -451,7 +458,8 @@ class LinearRegression(MultiOutputMixin, RegressorMixin, LinearModel): Notes ----- From the implementation point of view, this is just plain Ordinary - Least Squares (scipy.linalg.lstsq) wrapped as a predictor object. + Least Squares (scipy.linalg.lstsq) or Non Negative Least Squares + (scipy.optimize.nnls) wrapped as a predictor object. Examples -------- @@ -472,11 +480,12 @@ class LinearRegression(MultiOutputMixin, RegressorMixin, LinearModel): """ @_deprecate_positional_args def __init__(self, *, fit_intercept=True, normalize=False, copy_X=True, - n_jobs=None): + n_jobs=None, positive=False): self.fit_intercept = fit_intercept self.normalize = normalize self.copy_X = copy_X self.n_jobs = n_jobs + self.positive = positive def fit(self, X, y, sample_weight=None): """ @@ -502,7 +511,10 @@ def fit(self, X, y, sample_weight=None): """ n_jobs_ = self.n_jobs - X, y = self._validate_data(X, y, accept_sparse=['csr', 'csc', 'coo'], + + accept_sparse = False if self.positive else ['csr', 'csc', 'coo'] + + X, y = self._validate_data(X, y, accept_sparse=accept_sparse, y_numeric=True, multi_output=True) if sample_weight is not None: @@ -518,7 +530,16 @@ def fit(self, X, y, sample_weight=None): # Sample weight can be implemented via a simple rescaling. X, y = _rescale_data(X, y, sample_weight) - if sp.issparse(X): + if self.positive: + if y.ndim < 2: + self.coef_, self._residues = optimize.nnls(X, y) + else: + # scipy.optimize.nnls cannot handle y with shape (M, K) + outs = Parallel(n_jobs=n_jobs_)( + delayed(optimize.nnls)(X, y[:, j]) + for j in range(y.shape[1])) + self.coef_, self._residues = map(np.vstack, zip(*outs)) + elif sp.issparse(X): X_offset_scale = X_offset / X_scale def matvec(b):
diff --git a/sklearn/linear_model/tests/test_base.py b/sklearn/linear_model/tests/test_base.py index af76826715241..c7990bfde8bd9 100644 --- a/sklearn/linear_model/tests/test_base.py +++ b/sklearn/linear_model/tests/test_base.py @@ -13,13 +13,13 @@ from sklearn.utils._testing import assert_array_equal from sklearn.utils._testing import assert_almost_equal from sklearn.utils._testing import assert_allclose +from sklearn.utils import check_random_state from sklearn.utils.fixes import parse_version from sklearn.linear_model import LinearRegression from sklearn.linear_model._base import _preprocess_data from sklearn.linear_model._base import _rescale_data from sklearn.linear_model._base import make_dataset -from sklearn.utils import check_random_state from sklearn.datasets import make_sparse_uncorrelated from sklearn.datasets import make_regression from sklearn.datasets import load_iris @@ -94,6 +94,18 @@ def test_linear_regression_sample_weights(): assert_almost_equal(inter1, coefs2[0]) +def test_raises_value_error_if_positive_and_sparse(): + error_msg = ('A sparse matrix was passed, ' + 'but dense data is required.') + # X must not be sparse if positive == True + X = sparse.eye(10) + y = np.ones(10) + + reg = LinearRegression(positive=True) + + with pytest.raises(TypeError, match=error_msg): + reg.fit(X, y) + def test_raises_value_error_if_sample_weights_greater_than_1d(): # Sample weights must be either scalar or 1D @@ -206,6 +218,74 @@ def test_linear_regression_sparse_multiple_outcome(random_state=0): assert_array_almost_equal(np.vstack((y_pred, y_pred)).T, Y_pred, decimal=3) +def test_linear_regression_positive(): + # Test nonnegative LinearRegression on a simple dataset. + X = [[1], [2]] + y = [1, 2] + + reg = LinearRegression(positive=True) + reg.fit(X, y) + + assert_array_almost_equal(reg.coef_, [1]) + assert_array_almost_equal(reg.intercept_, [0]) + assert_array_almost_equal(reg.predict(X), [1, 2]) + + # test it also for degenerate input + X = [[1]] + y = [0] + + reg = LinearRegression(positive=True) + reg.fit(X, y) + assert_allclose(reg.coef_, [0]) + assert_allclose(reg.intercept_, [0]) + assert_allclose(reg.predict(X), [0]) + + +def test_linear_regression_positive_multiple_outcome(random_state=0): + # Test multiple-outcome nonnegative linear regressions + random_state = check_random_state(random_state) + X, y = make_sparse_uncorrelated(random_state=random_state) + Y = np.vstack((y, y)).T + n_features = X.shape[1] + + ols = LinearRegression(positive=True) + ols.fit(X, Y) + assert ols.coef_.shape == (2, n_features) + assert np.all(ols.coef_ >= 0.) + Y_pred = ols.predict(X) + ols.fit(X, y.ravel()) + y_pred = ols.predict(X) + assert_allclose(np.vstack((y_pred, y_pred)).T, Y_pred) + + +def test_linear_regression_positive_vs_nonpositive(): + # Test differences with LinearRegression when positive=False. + X, y = make_sparse_uncorrelated(random_state=0) + + reg = LinearRegression(positive=True) + reg.fit(X, y) + regn = LinearRegression(positive=False) + regn.fit(X, y) + + assert np.mean((reg.coef_ - regn.coef_)**2) > 1e-3 + + +def test_linear_regression_positive_vs_nonpositive_when_positive(): + # Test LinearRegression fitted coefficients + # when the problem is positive. + n_samples = 200 + n_features = 4 + X = rng.rand(n_samples, n_features) + y = X[:, 0] + 2 * X[:, 1] + 3 * X[:, 2] + 1.5 * X[:, 3] + + reg = LinearRegression(positive=True) + reg.fit(X, y) + regn = LinearRegression(positive=False) + regn.fit(X, y) + + assert np.mean((reg.coef_ - regn.coef_)**2) < 1e-6 + + def test_linear_regression_pd_sparse_dataframe_warning(): pd = pytest.importorskip('pandas') # restrict the pd versions < '0.24.0' as they have a bug in is_sparse func
[ { "path": "doc/modules/linear_model.rst", "old_path": "a/doc/modules/linear_model.rst", "new_path": "b/doc/modules/linear_model.rst", "metadata": "diff --git a/doc/modules/linear_model.rst b/doc/modules/linear_model.rst\nindex c4767d0cb2d64..0120f0f69fafd 100644\n--- a/doc/modules/linear_model.rst\n+++ b/doc/modules/linear_model.rst\n@@ -43,6 +43,8 @@ and will store the coefficients :math:`w` of the linear model in its\n \n >>> from sklearn import linear_model\n >>> reg = linear_model.LinearRegression()\n+ >>> reg.fit ([[0, 0], [1, 1], [2, 2]], [0, 1, 2])\n+ LinearRegression()\n >>> reg.fit([[0, 0], [1, 1], [2, 2]], [0, 1, 2])\n LinearRegression()\n >>> reg.coef_\n@@ -61,6 +63,19 @@ example, when data are collected without an experimental design.\n \n * :ref:`sphx_glr_auto_examples_linear_model_plot_ols.py`\n \n+Non-Negative Least Squares\n+--------------------------\n+\n+It is possible to constrain all the coefficients to be non-negative, which may\n+be useful when they represent some physical or naturally non-negative\n+quantities (e.g., frequency counts or prices of goods).\n+:class:`LinearRegression` accepts a boolean ``positive``\n+parameter: when set to `True` `Non Negative Least Squares\n+<https://en.wikipedia.org/wiki/Non-negative_least_squares>`_ are then applied.\n+\n+.. topic:: Examples:\n+\n+ * :ref:`sphx_glr_auto_examples_linear_model_plot_nnls.py`\n \n Ordinary Least Squares Complexity\n ---------------------------------\n" }, { "path": "doc/tutorial/statistical_inference/supervised_learning.rst", "old_path": "a/doc/tutorial/statistical_inference/supervised_learning.rst", "new_path": "b/doc/tutorial/statistical_inference/supervised_learning.rst", "metadata": "diff --git a/doc/tutorial/statistical_inference/supervised_learning.rst b/doc/tutorial/statistical_inference/supervised_learning.rst\nindex 9913829f8f054..18a7f1336da11 100644\n--- a/doc/tutorial/statistical_inference/supervised_learning.rst\n+++ b/doc/tutorial/statistical_inference/supervised_learning.rst\n@@ -173,7 +173,7 @@ Linear models: :math:`y = X\\beta + \\epsilon`\n >>> regr = linear_model.LinearRegression()\n >>> regr.fit(diabetes_X_train, diabetes_y_train)\n LinearRegression()\n- >>> print(regr.coef_) # doctest: +SKIP\n+ >>> print(regr.coef_)\n [ 0.30349955 -237.63931533 510.53060544 327.73698041 -814.13170937\n 492.81458798 102.84845219 184.60648906 743.51961675 76.09517222]\n \n" }, { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex a1a81b7571e28..b67004f1e8b00 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -203,6 +203,14 @@ Changelog\n - |Enhancement| :class:`isotonic.IsotonicRegression` now accepts 2darray with 1 feature as\n input array. :pr:`17379` by :user:`Jiaxiang <fujiaxiang>`.\n \n+:mod:`sklearn.linear_model`\n+...........................\n+\n+- |Feature| :class:`linear_model.LinearRegression` now forces coefficients\n+ to be all positive when ``positive`` is set to ``True``.\n+ :pr:`17578` by :user:`Joseph Knox <jknox13>`, :user:`Nelle Varoquaux <NelleV>`\n+ and :user:`Chiara Marmo <cmarmo>`.\n+\n :mod:`sklearn.manifold`\n .......................\n \n" } ]
0.24
febdd191f554555c3dfc9728e40766f178296ee5
[ "sklearn/linear_model/tests/test_base.py::test_linear_regression_multiple_outcome", "sklearn/linear_model/tests/test_base.py::test_preprocess_copy_data_no_checks[True-False]", "sklearn/linear_model/tests/test_base.py::test_preprocess_data", "sklearn/linear_model/tests/test_base.py::test_preprocess_copy_data_no_checks[True-True]", "sklearn/linear_model/tests/test_base.py::test_preprocess_data_weighted", "sklearn/linear_model/tests/test_base.py::test_linear_regression_sparse_equal_dense[False-True]", "sklearn/linear_model/tests/test_base.py::test_fit_intercept", "sklearn/linear_model/tests/test_base.py::test_linear_regression_sparse_equal_dense[True-True]", "sklearn/linear_model/tests/test_base.py::test_preprocess_data_multioutput", "sklearn/linear_model/tests/test_base.py::test_linear_regression_sparse_equal_dense[False-False]", "sklearn/linear_model/tests/test_base.py::test_fused_types_make_dataset", "sklearn/linear_model/tests/test_base.py::test_csr_preprocess_data", "sklearn/linear_model/tests/test_base.py::test_linear_regression_sample_weights", "sklearn/linear_model/tests/test_base.py::test_sparse_preprocess_data_with_return_mean", "sklearn/linear_model/tests/test_base.py::test_dtype_preprocess_data", "sklearn/linear_model/tests/test_base.py::test_preprocess_copy_data_no_checks[False-True]", "sklearn/linear_model/tests/test_base.py::test_linear_regression_sparse_multiple_outcome", "sklearn/linear_model/tests/test_base.py::test_rescale_data_dense[None]", "sklearn/linear_model/tests/test_base.py::test_raises_value_error_if_sample_weights_greater_than_1d", "sklearn/linear_model/tests/test_base.py::test_linear_regression_sparse", "sklearn/linear_model/tests/test_base.py::test_linear_regression_sparse_equal_dense[True-False]", "sklearn/linear_model/tests/test_base.py::test_preprocess_copy_data_no_checks[False-False]", "sklearn/linear_model/tests/test_base.py::test_linear_regression", "sklearn/linear_model/tests/test_base.py::test_rescale_data_dense[2]" ]
[ "sklearn/linear_model/tests/test_base.py::test_raises_value_error_if_positive_and_sparse", "sklearn/linear_model/tests/test_base.py::test_linear_regression_positive_multiple_outcome", "sklearn/linear_model/tests/test_base.py::test_linear_regression_positive", "sklearn/linear_model/tests/test_base.py::test_linear_regression_positive_vs_nonpositive_when_positive", "sklearn/linear_model/tests/test_base.py::test_linear_regression_positive_vs_nonpositive" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [ { "type": "file", "name": "examples/linear_model/plot_nnls.py" } ] }
[ { "path": "doc/modules/linear_model.rst", "old_path": "a/doc/modules/linear_model.rst", "new_path": "b/doc/modules/linear_model.rst", "metadata": "diff --git a/doc/modules/linear_model.rst b/doc/modules/linear_model.rst\nindex c4767d0cb2d64..0120f0f69fafd 100644\n--- a/doc/modules/linear_model.rst\n+++ b/doc/modules/linear_model.rst\n@@ -43,6 +43,8 @@ and will store the coefficients :math:`w` of the linear model in its\n \n >>> from sklearn import linear_model\n >>> reg = linear_model.LinearRegression()\n+ >>> reg.fit ([[0, 0], [1, 1], [2, 2]], [0, 1, 2])\n+ LinearRegression()\n >>> reg.fit([[0, 0], [1, 1], [2, 2]], [0, 1, 2])\n LinearRegression()\n >>> reg.coef_\n@@ -61,6 +63,19 @@ example, when data are collected without an experimental design.\n \n * :ref:`sphx_glr_auto_examples_linear_model_plot_ols.py`\n \n+Non-Negative Least Squares\n+--------------------------\n+\n+It is possible to constrain all the coefficients to be non-negative, which may\n+be useful when they represent some physical or naturally non-negative\n+quantities (e.g., frequency counts or prices of goods).\n+:class:`LinearRegression` accepts a boolean ``positive``\n+parameter: when set to `True` `Non Negative Least Squares\n+<https://en.wikipedia.org/wiki/Non-negative_least_squares>`_ are then applied.\n+\n+.. topic:: Examples:\n+\n+ * :ref:`sphx_glr_auto_examples_linear_model_plot_nnls.py`\n \n Ordinary Least Squares Complexity\n ---------------------------------\n" }, { "path": "doc/tutorial/statistical_inference/supervised_learning.rst", "old_path": "a/doc/tutorial/statistical_inference/supervised_learning.rst", "new_path": "b/doc/tutorial/statistical_inference/supervised_learning.rst", "metadata": "diff --git a/doc/tutorial/statistical_inference/supervised_learning.rst b/doc/tutorial/statistical_inference/supervised_learning.rst\nindex 9913829f8f054..18a7f1336da11 100644\n--- a/doc/tutorial/statistical_inference/supervised_learning.rst\n+++ b/doc/tutorial/statistical_inference/supervised_learning.rst\n@@ -173,7 +173,7 @@ Linear models: :math:`y = X\\beta + \\epsilon`\n >>> regr = linear_model.LinearRegression()\n >>> regr.fit(diabetes_X_train, diabetes_y_train)\n LinearRegression()\n- >>> print(regr.coef_) # doctest: +SKIP\n+ >>> print(regr.coef_)\n [ 0.30349955 -237.63931533 510.53060544 327.73698041 -814.13170937\n 492.81458798 102.84845219 184.60648906 743.51961675 76.09517222]\n \n" }, { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex a1a81b7571e28..b67004f1e8b00 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -203,6 +203,14 @@ Changelog\n - |Enhancement| :class:`isotonic.IsotonicRegression` now accepts 2darray with 1 feature as\n input array. :pr:`<PRID>` by :user:`<NAME>`.\n \n+:mod:`sklearn.linear_model`\n+...........................\n+\n+- |Feature| :class:`linear_model.LinearRegression` now forces coefficients\n+ to be all positive when ``positive`` is set to ``True``.\n+ :pr:`<PRID>` by :user:`<NAME>`, :user:`<NAME>`\n+ and :user:`<NAME>`.\n+\n :mod:`sklearn.manifold`\n .......................\n \n" } ]
diff --git a/doc/modules/linear_model.rst b/doc/modules/linear_model.rst index c4767d0cb2d64..0120f0f69fafd 100644 --- a/doc/modules/linear_model.rst +++ b/doc/modules/linear_model.rst @@ -43,6 +43,8 @@ and will store the coefficients :math:`w` of the linear model in its >>> from sklearn import linear_model >>> reg = linear_model.LinearRegression() + >>> reg.fit ([[0, 0], [1, 1], [2, 2]], [0, 1, 2]) + LinearRegression() >>> reg.fit([[0, 0], [1, 1], [2, 2]], [0, 1, 2]) LinearRegression() >>> reg.coef_ @@ -61,6 +63,19 @@ example, when data are collected without an experimental design. * :ref:`sphx_glr_auto_examples_linear_model_plot_ols.py` +Non-Negative Least Squares +-------------------------- + +It is possible to constrain all the coefficients to be non-negative, which may +be useful when they represent some physical or naturally non-negative +quantities (e.g., frequency counts or prices of goods). +:class:`LinearRegression` accepts a boolean ``positive`` +parameter: when set to `True` `Non Negative Least Squares +<https://en.wikipedia.org/wiki/Non-negative_least_squares>`_ are then applied. + +.. topic:: Examples: + + * :ref:`sphx_glr_auto_examples_linear_model_plot_nnls.py` Ordinary Least Squares Complexity --------------------------------- diff --git a/doc/tutorial/statistical_inference/supervised_learning.rst b/doc/tutorial/statistical_inference/supervised_learning.rst index 9913829f8f054..18a7f1336da11 100644 --- a/doc/tutorial/statistical_inference/supervised_learning.rst +++ b/doc/tutorial/statistical_inference/supervised_learning.rst @@ -173,7 +173,7 @@ Linear models: :math:`y = X\beta + \epsilon` >>> regr = linear_model.LinearRegression() >>> regr.fit(diabetes_X_train, diabetes_y_train) LinearRegression() - >>> print(regr.coef_) # doctest: +SKIP + >>> print(regr.coef_) [ 0.30349955 -237.63931533 510.53060544 327.73698041 -814.13170937 492.81458798 102.84845219 184.60648906 743.51961675 76.09517222] diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index a1a81b7571e28..b67004f1e8b00 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -203,6 +203,14 @@ Changelog - |Enhancement| :class:`isotonic.IsotonicRegression` now accepts 2darray with 1 feature as input array. :pr:`<PRID>` by :user:`<NAME>`. +:mod:`sklearn.linear_model` +........................... + +- |Feature| :class:`linear_model.LinearRegression` now forces coefficients + to be all positive when ``positive`` is set to ``True``. + :pr:`<PRID>` by :user:`<NAME>`, :user:`<NAME>` + and :user:`<NAME>`. + :mod:`sklearn.manifold` ....................... If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names: [{'type': 'file', 'name': 'examples/linear_model/plot_nnls.py'}]
scikit-learn/scikit-learn
scikit-learn__scikit-learn-6624
https://github.com/scikit-learn/scikit-learn/pull/6624
diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index b67004f1e8b00..94328dafdeaa2 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -211,6 +211,12 @@ Changelog :pr:`17578` by :user:`Joseph Knox <jknox13>`, :user:`Nelle Varoquaux <NelleV>` and :user:`Chiara Marmo <cmarmo>`. +- |Enhancement| :class:`linear_model.RidgeCV` now supports finding an optimal + regularization value `alpha` for each target separately by setting + ``alpha_per_target=True``. This is only supported when using the default + efficient leave-one-out cross-validation scheme ``cv=None``. :pr:`6624` by + :user:`Marijn van Vliet <wmvanvliet>`. + :mod:`sklearn.manifold` ....................... diff --git a/sklearn/linear_model/_ridge.py b/sklearn/linear_model/_ridge.py index cd8d18b6e53bc..544d330caad42 100644 --- a/sklearn/linear_model/_ridge.py +++ b/sklearn/linear_model/_ridge.py @@ -1120,7 +1120,7 @@ def __init__(self, alphas=(0.1, 1.0, 10.0), *, fit_intercept=True, normalize=False, scoring=None, copy_X=True, gcv_mode=None, store_cv_values=False, - is_clf=False): + is_clf=False, alpha_per_target=False): self.alphas = np.asarray(alphas) self.fit_intercept = fit_intercept self.normalize = normalize @@ -1129,6 +1129,7 @@ def __init__(self, alphas=(0.1, 1.0, 10.0), *, self.gcv_mode = gcv_mode self.store_cv_values = store_cv_values self.is_clf = is_clf + self.alpha_per_target = alpha_per_target @staticmethod def _decomp_diag(v_prime, Q): @@ -1456,6 +1457,11 @@ def fit(self, X, y, sample_weight=None): dtype=[np.float64], multi_output=True, y_numeric=True) + # alpha_per_target cannot be used in classifier mode. All subclasses + # of _RidgeGCV that are classifiers keep alpha_per_target at its + # default value: False, so the condition below should never happen. + assert not (self.is_clf and self.alpha_per_target) + if sample_weight is not None: sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype) @@ -1496,19 +1502,23 @@ def fit(self, X, y, sample_weight=None): error = scorer is None n_y = 1 if len(y.shape) == 1 else y.shape[1] + n_alphas = 1 if np.ndim(self.alphas) == 0 else len(self.alphas) if self.store_cv_values: self.cv_values_ = np.empty( - (n_samples * n_y, len(self.alphas)), dtype=X.dtype) + (n_samples * n_y, n_alphas), dtype=X.dtype) best_coef, best_score, best_alpha = None, None, None - for i, alpha in enumerate(self.alphas): + for i, alpha in enumerate(np.atleast_1d(self.alphas)): G_inverse_diag, c = solve( float(alpha), y, sqrt_sw, X_mean, *decomposition) if error: squared_errors = (c / G_inverse_diag) ** 2 - alpha_score = -squared_errors.mean() + if self.alpha_per_target: + alpha_score = -squared_errors.mean(axis=0) + else: + alpha_score = -squared_errors.mean() if self.store_cv_values: self.cv_values_[:, i] = squared_errors.ravel() else: @@ -1520,15 +1530,40 @@ def fit(self, X, y, sample_weight=None): identity_estimator = _IdentityClassifier( classes=np.arange(n_y) ) - predictions_, y_ = predictions, y.argmax(axis=1) + alpha_score = scorer(identity_estimator, + predictions, y.argmax(axis=1)) else: identity_estimator = _IdentityRegressor() - predictions_, y_ = predictions.ravel(), y.ravel() - - alpha_score = scorer(identity_estimator, predictions_, y_) - - if (best_score is None) or (alpha_score > best_score): - best_coef, best_score, best_alpha = c, alpha_score, alpha + if self.alpha_per_target: + alpha_score = np.array([ + scorer(identity_estimator, + predictions[:, j], y[:, j]) + for j in range(n_y) + ]) + else: + alpha_score = scorer(identity_estimator, + predictions.ravel(), y.ravel()) + + # Keep track of the best model + if best_score is None: + # initialize + if self.alpha_per_target and n_y > 1: + best_coef = c + best_score = np.atleast_1d(alpha_score) + best_alpha = np.full(n_y, alpha) + else: + best_coef = c + best_score = alpha_score + best_alpha = alpha + else: + # update + if self.alpha_per_target and n_y > 1: + to_update = alpha_score > best_score + best_coef[:, to_update] = c[:, to_update] + best_score[to_update] = alpha_score[to_update] + best_alpha[to_update] = alpha + elif alpha_score > best_score: + best_coef, best_score, best_alpha = c, alpha_score, alpha self.alpha_ = best_alpha self.best_score_ = best_score @@ -1540,9 +1575,9 @@ def fit(self, X, y, sample_weight=None): if self.store_cv_values: if len(y.shape) == 1: - cv_values_shape = n_samples, len(self.alphas) + cv_values_shape = n_samples, n_alphas else: - cv_values_shape = n_samples, n_y, len(self.alphas) + cv_values_shape = n_samples, n_y, n_alphas self.cv_values_ = self.cv_values_.reshape(cv_values_shape) return self @@ -1552,8 +1587,8 @@ class _BaseRidgeCV(LinearModel): @_deprecate_positional_args def __init__(self, alphas=(0.1, 1.0, 10.0), *, fit_intercept=True, normalize=False, scoring=None, - cv=None, gcv_mode=None, - store_cv_values=False): + cv=None, gcv_mode=None, store_cv_values=False, + alpha_per_target=False): self.alphas = np.asarray(alphas) self.fit_intercept = fit_intercept self.normalize = normalize @@ -1561,6 +1596,7 @@ def __init__(self, alphas=(0.1, 1.0, 10.0), *, self.cv = cv self.gcv_mode = gcv_mode self.store_cv_values = store_cv_values + self.alpha_per_target = alpha_per_target def fit(self, X, y, sample_weight=None): """Fit Ridge regression model with cv. @@ -1598,7 +1634,8 @@ def fit(self, X, y, sample_weight=None): scoring=self.scoring, gcv_mode=self.gcv_mode, store_cv_values=self.store_cv_values, - is_clf=is_classifier(self)) + is_clf=is_classifier(self), + alpha_per_target=self.alpha_per_target) estimator.fit(X, y, sample_weight=sample_weight) self.alpha_ = estimator.alpha_ self.best_score_ = estimator.best_score_ @@ -1606,7 +1643,10 @@ def fit(self, X, y, sample_weight=None): self.cv_values_ = estimator.cv_values_ else: if self.store_cv_values: - raise ValueError("cv!=None and store_cv_values=True " + raise ValueError("cv!=None and store_cv_values=True" + " are incompatible") + if self.alpha_per_target: + raise ValueError("cv!=None and alpha_per_target=True" " are incompatible") parameters = {'alpha': self.alphas} solver = 'sparse_cg' if sparse.issparse(X) else 'auto' @@ -1704,14 +1744,21 @@ class RidgeCV(MultiOutputMixin, RegressorMixin, _BaseRidgeCV): below). This flag is only compatible with ``cv=None`` (i.e. using Generalized Cross-Validation). + alpha_per_target : bool, default=False + Flag indicating whether to optimize the alpha value (picked from the + `alphas` parameter list) for each target separately (for multi-output + settings: multiple prediction targets). When set to `True`, after + fitting, the `alpha_` attribute will contain a value for each target. + When set to `False`, a single alpha is used for all targets. + Attributes ---------- cv_values_ : ndarray of shape (n_samples, n_alphas) or \ shape (n_samples, n_targets, n_alphas), optional - Cross-validation values for each alpha (only available if \ - ``store_cv_values=True`` and ``cv=None``). After ``fit()`` has been \ - called, this attribute will contain the mean squared errors \ - (by default) or the values of the ``{loss,score}_func`` function \ + Cross-validation values for each alpha (only available if + ``store_cv_values=True`` and ``cv=None``). After ``fit()`` has been + called, this attribute will contain the mean squared errors + (by default) or the values of the ``{loss,score}_func`` function (if provided in the constructor). coef_ : ndarray of shape (n_features) or (n_targets, n_features) @@ -1721,11 +1768,13 @@ class RidgeCV(MultiOutputMixin, RegressorMixin, _BaseRidgeCV): Independent term in decision function. Set to 0.0 if ``fit_intercept = False``. - alpha_ : float - Estimated regularization parameter. + alpha_ : float or ndarray of shape (n_targets,) + Estimated regularization parameter, or, if ``alpha_per_target=True``, + the estimated regularization parameter for each target. - best_score_ : float - Score of base estimator with best alpha. + best_score_ : float or ndarray of shape (n_targets,) + Score of base estimator with best alpha, or, if + ``alpha_per_target=True``, a score for each target. Examples --------
diff --git a/sklearn/linear_model/tests/test_ridge.py b/sklearn/linear_model/tests/test_ridge.py index 0a10e5f23f562..7d52de903aee5 100644 --- a/sklearn/linear_model/tests/test_ridge.py +++ b/sklearn/linear_model/tests/test_ridge.py @@ -37,7 +37,10 @@ from sklearn.datasets import make_classification from sklearn.model_selection import GridSearchCV -from sklearn.model_selection import KFold, GroupKFold, cross_val_predict +from sklearn.model_selection import KFold +from sklearn.model_selection import GroupKFold +from sklearn.model_selection import cross_val_predict +from sklearn.model_selection import LeaveOneOut from sklearn.utils import check_random_state from sklearn.datasets import make_multilabel_classification @@ -693,6 +696,74 @@ def test_ridge_best_score(ridge, make_dataset, cv): assert isinstance(ridge.best_score_, float) +def test_ridge_cv_individual_penalties(): + # Tests the ridge_cv object optimizing individual penalties for each target + + rng = np.random.RandomState(42) + + # Create random dataset with multiple targets. Each target should have + # a different optimal alpha. + n_samples, n_features, n_targets = 20, 5, 3 + y = rng.randn(n_samples, n_targets) + X = (np.dot(y[:, [0]], np.ones((1, n_features))) + + np.dot(y[:, [1]], 0.05 * np.ones((1, n_features))) + + np.dot(y[:, [2]], 0.001 * np.ones((1, n_features))) + + rng.randn(n_samples, n_features)) + + alphas = (1, 100, 1000) + + # Find optimal alpha for each target + optimal_alphas = [RidgeCV(alphas=alphas).fit(X, target).alpha_ + for target in y.T] + + # Find optimal alphas for all targets simultaneously + ridge_cv = RidgeCV(alphas=alphas, alpha_per_target=True).fit(X, y) + assert_array_equal(optimal_alphas, ridge_cv.alpha_) + + # The resulting regression weights should incorporate the different + # alpha values. + assert_array_almost_equal(Ridge(alpha=ridge_cv.alpha_).fit(X, y).coef_, + ridge_cv.coef_) + + # Test shape of alpha_ and cv_values_ + ridge_cv = RidgeCV(alphas=alphas, alpha_per_target=True, + store_cv_values=True).fit(X, y) + assert ridge_cv.alpha_.shape == (n_targets,) + assert ridge_cv.best_score_.shape == (n_targets,) + assert ridge_cv.cv_values_.shape == (n_samples, len(alphas), n_targets) + + # Test edge case of there being only one alpha value + ridge_cv = RidgeCV(alphas=1, alpha_per_target=True, + store_cv_values=True).fit(X, y) + assert ridge_cv.alpha_.shape == (n_targets,) + assert ridge_cv.best_score_.shape == (n_targets,) + assert ridge_cv.cv_values_.shape == (n_samples, n_targets, 1) + + # Test edge case of there being only one target + ridge_cv = RidgeCV(alphas=alphas, alpha_per_target=True, + store_cv_values=True).fit(X, y[:, 0]) + assert np.isscalar(ridge_cv.alpha_) + assert np.isscalar(ridge_cv.best_score_) + assert ridge_cv.cv_values_.shape == (n_samples, len(alphas)) + + # Try with a custom scoring function + ridge_cv = RidgeCV(alphas=alphas, alpha_per_target=True, + scoring='r2').fit(X, y) + assert_array_equal(optimal_alphas, ridge_cv.alpha_) + assert_array_almost_equal(Ridge(alpha=ridge_cv.alpha_).fit(X, y).coef_, + ridge_cv.coef_) + + # Using a custom CV object should throw an error in combination with + # alpha_per_target=True + ridge_cv = RidgeCV(alphas=alphas, cv=LeaveOneOut(), alpha_per_target=True) + msg = "cv!=None and alpha_per_target=True are incompatible" + with pytest.raises(ValueError, match=msg): + ridge_cv.fit(X, y) + ridge_cv = RidgeCV(alphas=alphas, cv=6, alpha_per_target=True) + with pytest.raises(ValueError, match=msg): + ridge_cv.fit(X, y) + + def _test_ridge_diabetes(filter_): ridge = Ridge(fit_intercept=False) ridge.fit(filter_(X_diabetes), y_diabetes)
[ { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex b67004f1e8b00..94328dafdeaa2 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -211,6 +211,12 @@ Changelog\n :pr:`17578` by :user:`Joseph Knox <jknox13>`, :user:`Nelle Varoquaux <NelleV>`\n and :user:`Chiara Marmo <cmarmo>`.\n \n+- |Enhancement| :class:`linear_model.RidgeCV` now supports finding an optimal\n+ regularization value `alpha` for each target separately by setting\n+ ``alpha_per_target=True``. This is only supported when using the default\n+ efficient leave-one-out cross-validation scheme ``cv=None``. :pr:`6624` by\n+ :user:`Marijn van Vliet <wmvanvliet>`.\n+\n :mod:`sklearn.manifold`\n .......................\n \n" } ]
0.24
075d4245681110386cb4312cbdbd0c82776290ac
[ "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape0-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_class_weights", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape0-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-csr_matrix-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape0-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape1-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge[svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-40-float32-1.0-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-csr_matrix-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge[sparse_cg]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-cholesky]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape1-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape0-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[<lambda>1-cv1-accuracy]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_error[gcv]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-csr_matrix-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-array-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape0-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-8-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-csr_matrix-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape1-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-20-float32-0.1-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_custom_scoring[<lambda>0-None]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[True-shape2]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-20-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-20-float32-0.1-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-20-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_tolerance]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_no_support_multilabel", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-array-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape1-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[<lambda>1-None-None]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-array-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[False-shape0]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape1-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-20-float32-0.1-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_raises_value_error_if_sample_weights_greater_than_1d", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-20-float32-0.1-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape1-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_sample_weight", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape0-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[False-shape4]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape1-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape0-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_class_weight_vs_sample_weight[RidgeClassifierCV]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-8-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_multi_ridge_diabetes]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-8-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-8-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape1-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_custom_scoring[<lambda>0-cv1]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_shapes", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape1-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_error[5]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[eigen-eigen-eigen-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape1-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-csr_matrix-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-array-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-20-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-array-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-20-float32-0.1-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-20-float64-0.2-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-20-float64-0.2-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_X_CenterStackOp[n_col0]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-40-float32-1.0-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-csr_matrix-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[True-shape1]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[False-shape0]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[False-shape1]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-40-float32-1.0-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[None-svd-eigen-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape1-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-20-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_custom_scoring[<lambda>1-None]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape1-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-8-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-40-float32-1.0-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_X_CenterStackOp[n_col2]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-sparse_cg]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-csr_matrix-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-20-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_error[1]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape1-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-array-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape1-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-8-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_vs_lstsq", "sklearn/linear_model/tests/test_ridge.py::test_X_CenterStackOp[n_col1]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-20-float32-0.1-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-array-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-40-float32-1.0-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-40-float32-1.0-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_sparse_design_with_sample_weights", "sklearn/linear_model/tests/test_ridge.py::test_raises_value_error_if_solver_not_supported", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape0-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-20-float32-0.1-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-array-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape0-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[<lambda>1-None-_accuracy_callable]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-array-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-8-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_toy_ridge_object", "sklearn/linear_model/tests/test_ridge.py::test_ridge_fit_intercept_sparse_error[cholesky]", "sklearn/linear_model/tests/test_ridge.py::test_primal_dual_relationship", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape1-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-20-float32-0.1-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-array-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-csr_matrix-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_store_cv_values[None]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-20-float32-0.1-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[<lambda>1-cv1-None]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-20-float64-0.2-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-20-float64-0.2-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[False-shape2]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-40-float32-1.0-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_store_cv_values[neg_mean_squared_error]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[True-shape0]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[<lambda>0-None-accuracy]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape1-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-20-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-8-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape0-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_singular", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[saga]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[auto-svd-eigen-True]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[sag]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-20-float64-0.2-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-array-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-20-float64-0.2-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_cv_values_not_stored[ridge0-make_regression]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-csr_matrix-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[True-shape4]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[<lambda>0-None-_accuracy_callable]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_cv_store_cv_values[_accuracy_callable]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-20-float64-0.2-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-csr_matrix-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weights", "sklearn/linear_model/tests/test_ridge.py::test_ridge_best_score[3-ridge1-make_classification]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape0-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_ridge_loo]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-20-float32-0.1-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape1-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-20-float64-0.2-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-8-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-csr_matrix-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge[cholesky]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[True-shape0]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-20-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-20-float64-0.2-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-20-float32-0.1-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-40-float32-1.0-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-20-float64-0.2-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_n_iter", "sklearn/linear_model/tests/test_ridge.py::test_ridge_fit_intercept_sparse_error[svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape1-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_negative_alphas", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-array-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape0-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_custom_scoring[<lambda>1-cv1]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-20-float32-0.1-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-array-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-40-float32-1.0-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-20-float64-0.2-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_cv_values_not_stored[ridge1-make_classification]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-array-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-20-float64-0.2-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-20-float32-0.1-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-20-float32-0.1-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_ridge_classifiers]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[False-shape3]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-20-float64-0.2-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-8-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[None-svd-eigen-True]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[False-shape1]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_individual_penalties", "sklearn/linear_model/tests/test_ridge.py::test_sparse_cg_max_iter", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[<lambda>1-None-accuracy]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-csr_matrix-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-20-float32-0.1-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-20-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-20-float64-0.2-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-40-float32-1.0-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-40-float32-1.0-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-20-float32-0.1-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-40-float32-1.0-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-20-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sparse_svd", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[True-shape3]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-array-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-20-float64-0.2-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-40-float32-1.0-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-array-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-40-float32-1.0-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_cv_store_cv_values[None]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-20-float64-0.2-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape0-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_intercept", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape0-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_class_weights_cv", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[True-shape3]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-20-float32-0.1-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-8-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-40-float32-1.0-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-20-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-20-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[False-shape4]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-8-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-40-float32-1.0-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-20-float64-0.2-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape0-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-40-float32-1.0-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-csr_matrix-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[<lambda>0-cv1-_accuracy_callable]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-sag]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_fit_intercept_sparse_error[lsqr]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_best_score[None-ridge1-make_classification]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[True-shape2]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-40-float32-1.0-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-csr_matrix-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-20-float32-0.1-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape0-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape0-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape1-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-20-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sag_with_X_fortran", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-20-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-csr_matrix-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape0-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[sparse_cg]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_best_score[None-ridge0-make_regression]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-csr_matrix-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-saga]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-20-float64-0.2-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_error[bad]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-20-float32-0.1-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-20-float32-0.1-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-20-float64-0.2-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_loo_cv_asym_scoring", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape0-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-csr_matrix-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-20-float64-0.2-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape0-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-40-float32-1.0-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-csr_matrix-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-20-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[eigen-eigen-eigen-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-array-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-csr_matrix-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-20-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[<lambda>0-cv1-accuracy]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape1-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-array-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[True-shape4]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-20-float64-0.2-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_int_alphas", "sklearn/linear_model/tests/test_ridge.py::test_ridge_best_score[3-ridge0-make_regression]", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_ridge_cv_normalize]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-8-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-20-float64-0.2-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-40-float32-1.0-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-csr_matrix-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_convergence_fail", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape1-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-40-float32-1.0-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-array-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-20-float32-0.1-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-20-float32-0.1-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[cholesky]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[False-shape2]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[svd-svd-svd-False]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[True-shape1]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-20-float32-0.1-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-20-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-array-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_error[True]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[svd-svd-svd-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-csr_matrix-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-lsqr]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape1-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-20-float64-0.2-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-array-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[auto-svd-eigen-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-40-float32-1.0-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape0-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_store_cv_values[_mean_squared_error_callable]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-20-float32-0.1-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape1-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-8-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-20-float64-0.2-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match_cholesky", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-array-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-array-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-csr_matrix-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[False-shape3]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-40-float32-1.0-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-array-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-40-float32-1.0-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_ridge_diabetes]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_sample_weights", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_ridge_cv]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[<lambda>1-cv1-_accuracy_callable]", "sklearn/linear_model/tests/test_ridge.py::test_ridge[lsqr]", "sklearn/linear_model/tests/test_ridge.py::test_class_weight_vs_sample_weight[RidgeClassifier]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-8-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-csr_matrix-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_fit_intercept_sparse_error[saga]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[<lambda>0-cv1-None]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape0-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape0-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_cv_store_cv_values[accuracy]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[<lambda>0-None-None]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape1-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape0-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-8-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[lsqr]", "sklearn/linear_model/tests/test_ridge.py::test_ridge[sag]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-csr_matrix-None-False]" ]
[ "sklearn/linear_model/tests/test_ridge.py::test_ridge_cv_individual_penalties" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex b67004f1e8b00..94328dafdeaa2 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -211,6 +211,12 @@ Changelog\n :pr:`<PRID>` by :user:`<NAME>`, :user:`<NAME>`\n and :user:`<NAME>`.\n \n+- |Enhancement| :class:`linear_model.RidgeCV` now supports finding an optimal\n+ regularization value `alpha` for each target separately by setting\n+ ``alpha_per_target=True``. This is only supported when using the default\n+ efficient leave-one-out cross-validation scheme ``cv=None``. :pr:`<PRID>` by\n+ :user:`<NAME>`.\n+\n :mod:`sklearn.manifold`\n .......................\n \n" } ]
diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index b67004f1e8b00..94328dafdeaa2 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -211,6 +211,12 @@ Changelog :pr:`<PRID>` by :user:`<NAME>`, :user:`<NAME>` and :user:`<NAME>`. +- |Enhancement| :class:`linear_model.RidgeCV` now supports finding an optimal + regularization value `alpha` for each target separately by setting + ``alpha_per_target=True``. This is only supported when using the default + efficient leave-one-out cross-validation scheme ``cv=None``. :pr:`<PRID>` by + :user:`<NAME>`. + :mod:`sklearn.manifold` .......................
scikit-learn/scikit-learn
scikit-learn__scikit-learn-13003
https://github.com/scikit-learn/scikit-learn/pull/13003
diff --git a/benchmarks/bench_plot_polynomial_kernel_approximation.py b/benchmarks/bench_plot_polynomial_kernel_approximation.py new file mode 100644 index 0000000000000..2b7556f37320e --- /dev/null +++ b/benchmarks/bench_plot_polynomial_kernel_approximation.py @@ -0,0 +1,156 @@ +""" +======================================================================== +Benchmark for explicit feature map approximation of polynomial kernels +======================================================================== + +An example illustrating the approximation of the feature map +of an Homogeneous Polynomial kernel. + +.. currentmodule:: sklearn.kernel_approximation + +It shows how to use :class:`PolynomialCountSketch` and :class:`Nystroem` to +approximate the feature map of a polynomial kernel for +classification with an SVM on the digits dataset. Results using a linear +SVM in the original space, a linear SVM using the approximate mappings +and a kernelized SVM are compared. + +The first plot shows the classification accuracy of Nystroem [2] and +PolynomialCountSketch [1] as the output dimension (n_components) grows. +It also shows the accuracy of a linear SVM and a polynomial kernel SVM +on the same data. + +The second plot explores the scalability of PolynomialCountSketch +and Nystroem. For a sufficiently large output dimension, +PolynomialCountSketch should be faster as it is O(n(d+klog k)) +while Nystroem is O(n(dk+k^2)). In addition, Nystroem requires +a time-consuming training phase, while training is almost immediate +for PolynomialCountSketch, whose training phase boils down to +initializing some random variables (because is data-independent). + +[1] Pham, N., & Pagh, R. (2013, August). Fast and scalable polynomial +kernels via explicit feature maps. In Proceedings of the 19th ACM SIGKDD +international conference on Knowledge discovery and data mining (pp. 239-247) +(http://chbrown.github.io/kdd-2013-usb/kdd/p239.pdf) + +[2] Charikar, M., Chen, K., & Farach-Colton, M. (2002, July). Finding frequent +items in data streams. In International Colloquium on Automata, Languages, and +Programming (pp. 693-703). Springer, Berlin, Heidelberg. +(http://www.vldb.org/pvldb/1/1454225.pdf) + +""" +# Author: Daniel Lopez-Sanchez <[email protected]> +# License: BSD 3 clause + +# Load data manipulation functions +from sklearn.datasets import load_digits +from sklearn.model_selection import train_test_split + +# Some common libraries +import matplotlib.pyplot as plt +import numpy as np + +# Will use this for timing results +from time import time + +# Import SVM classifiers and feature map approximation algorithms +from sklearn.svm import LinearSVC, SVC +from sklearn.kernel_approximation import Nystroem, PolynomialCountSketch +from sklearn.pipeline import Pipeline + +# Split data in train and test sets +X, y = load_digits()["data"], load_digits()["target"] +X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.7) + +# Set the range of n_components for our experiments +out_dims = range(20, 400, 20) + +# Evaluate Linear SVM +lsvm = LinearSVC().fit(X_train, y_train) +lsvm_score = 100*lsvm.score(X_test, y_test) + +# Evaluate kernelized SVM +ksvm = SVC(kernel="poly", degree=2, gamma=1.).fit(X_train, y_train) +ksvm_score = 100*ksvm.score(X_test, y_test) + +# Evaluate PolynomialCountSketch + LinearSVM +ps_svm_scores = [] +n_runs = 5 + +# To compensate for the stochasticity of the method, we make n_tets runs +for k in out_dims: + score_avg = 0 + for _ in range(n_runs): + ps_svm = Pipeline([("PS", PolynomialCountSketch(degree=2, + n_components=k)), + ("SVM", LinearSVC())]) + score_avg += ps_svm.fit(X_train, y_train).score(X_test, y_test) + ps_svm_scores.append(100*score_avg/n_runs) + +# Evaluate Nystroem + LinearSVM +ny_svm_scores = [] +n_runs = 5 + +for k in out_dims: + score_avg = 0 + for _ in range(n_runs): + ny_svm = Pipeline([("NY", Nystroem(kernel="poly", gamma=1., degree=2, + coef0=0, n_components=k)), + ("SVM", LinearSVC())]) + score_avg += ny_svm.fit(X_train, y_train).score(X_test, y_test) + ny_svm_scores.append(100*score_avg/n_runs) + +# Show results +fig, ax = plt.subplots(figsize=(6, 4)) +ax.set_title("Accuracy results") +ax.plot(out_dims, ps_svm_scores, label="PolynomialCountSketch + linear SVM", + c="orange") +ax.plot(out_dims, ny_svm_scores, label="Nystroem + linear SVM", + c="blue") +ax.plot([out_dims[0], out_dims[-1]], [lsvm_score, lsvm_score], + label="Linear SVM", c="black", dashes=[2, 2]) +ax.plot([out_dims[0], out_dims[-1]], [ksvm_score, ksvm_score], + label="Poly-kernel SVM", c="red", dashes=[2, 2]) +ax.legend() +ax.set_xlabel("N_components for PolynomialCountSketch and Nystroem") +ax.set_ylabel("Accuracy (%)") +ax.set_xlim([out_dims[0], out_dims[-1]]) +fig.tight_layout() + +# Now lets evaluate the scalability of PolynomialCountSketch vs Nystroem +# First we generate some fake data with a lot of samples + +fakeData = np.random.randn(10000, 100) +fakeDataY = np.random.randint(0, high=10, size=(10000)) + +out_dims = range(500, 6000, 500) + +# Evaluate scalability of PolynomialCountSketch as n_components grows +ps_svm_times = [] +for k in out_dims: + ps = PolynomialCountSketch(degree=2, n_components=k) + + start = time() + ps.fit_transform(fakeData, None) + ps_svm_times.append(time() - start) + +# Evaluate scalability of Nystroem as n_components grows +# This can take a while due to the inefficient training phase +ny_svm_times = [] +for k in out_dims: + ny = Nystroem(kernel="poly", gamma=1., degree=2, coef0=0, n_components=k) + + start = time() + ny.fit_transform(fakeData, None) + ny_svm_times.append(time() - start) + +# Show results +fig, ax = plt.subplots(figsize=(6, 4)) +ax.set_title("Scalability results") +ax.plot(out_dims, ps_svm_times, label="PolynomialCountSketch", c="orange") +ax.plot(out_dims, ny_svm_times, label="Nystroem", c="blue") +ax.legend() +ax.set_xlabel("N_components for PolynomialCountSketch and Nystroem") +ax.set_ylabel("fit_transform time \n(s/10.000 samples)") +ax.set_xlim([out_dims[0], out_dims[-1]]) +fig.tight_layout() +plt.show() diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst index 2e54d000a13aa..70a5174629f37 100644 --- a/doc/modules/classes.rst +++ b/doc/modules/classes.rst @@ -706,6 +706,7 @@ Plotting kernel_approximation.AdditiveChi2Sampler kernel_approximation.Nystroem + kernel_approximation.PolynomialCountSketch kernel_approximation.RBFSampler kernel_approximation.SkewedChi2Sampler diff --git a/doc/modules/kernel_approximation.rst b/doc/modules/kernel_approximation.rst index fb3843c6bc045..4f5ee46a42057 100644 --- a/doc/modules/kernel_approximation.rst +++ b/doc/modules/kernel_approximation.rst @@ -149,6 +149,51 @@ above for the :class:`RBFSampler`. The only difference is in the free parameter, that is called :math:`c`. For a motivation for this mapping and the mathematical details see [LS2010]_. +.. _polynomial_kernel_approx: + +Polynomial Kernel Approximation via Tensor Sketch +------------------------------------------------- + +The :ref:`polynomial kernel <polynomial_kernel>` is a popular type of kernel +function given by: + +.. math:: + + k(x, y) = (\gamma x^\top y +c_0)^d + +where: + + * ``x``, ``y`` are the input vectors + * ``d`` is the kernel degree + +Intuitively, the feature space of the polynomial kernel of degree `d` +consists of all possible degree-`d` products among input features, which enables +learning algorithms using this kernel to account for interactions between features. + +The TensorSketch [PP2013]_ method, as implemented in :class:`PolynomialCountSketch`, is a +scalable, input data independent method for polynomial kernel approximation. +It is based on the concept of Count sketch [WIKICS]_ [CCF2002]_ , a dimensionality +reduction technique similar to feature hashing, which instead uses several +independent hash functions. TensorSketch obtains a Count Sketch of the outer product +of two vectors (or a vector with itself), which can be used as an approximation of the +polynomial kernel feature space. In particular, instead of explicitly computing +the outer product, TensorSketch computes the Count Sketch of the vectors and then +uses polynomial multiplication via the Fast Fourier Transform to compute the +Count Sketch of their outer product. + +Conveniently, the training phase of TensorSketch simply consists of initializing +some random variables. It is thus independent of the input data, i.e. it only +depends on the number of input features, but not the data values. +In addition, this method can transform samples in +:math:`\mathcal{O}(n_{\text{samples}}(n_{\text{features}} + n_{\text{components}} \log(n_{\text{components}})))` +time, where :math:`n_{\text{components}}` is the desired output dimension, +determined by ``n_components``. + +.. topic:: Examples: + + * :ref:`sphx_glr_auto_examples_plot_scalable_poly_kernels.py` + +.. _tensor_sketch_kernel_approx: Mathematical Details -------------------- @@ -201,3 +246,11 @@ or store training examples. .. [VVZ2010] `"Generalized RBF feature maps for Efficient Detection" <https://www.robots.ox.ac.uk/~vgg/publications/2010/Sreekanth10/sreekanth10.pdf>`_ Vempati, S. and Vedaldi, A. and Zisserman, A. and Jawahar, CV - 2010 + .. [PP2013] `"Fast and scalable polynomial kernels via explicit feature maps" + <https://doi.org/10.1145/2487575.2487591>`_ + Pham, N., & Pagh, R. - 2013 + .. [CCF2002] `"Finding frequent items in data streams" + <http://www.cs.princeton.edu/courses/archive/spring04/cos598B/bib/CharikarCF.pdf>`_ + Charikar, M., Chen, K., & Farach-Colton - 2002 + .. [WIKICS] `"Wikipedia: Count sketch" + <https://en.wikipedia.org/wiki/Count_sketch>`_ diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index 2682902a20983..c73f1a373a86b 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -221,6 +221,15 @@ Changelog - |Enhancement| :class:`isotonic.IsotonicRegression` now accepts 2darray with 1 feature as input array. :pr:`17379` by :user:`Jiaxiang <fujiaxiang>`. +:mod:`sklearn.kernel_approximation` +................................... + +- |Feature| Added class :class:`kernel_approximation.PolynomialCountSketch` + which implements the Tensor Sketch algorithm for polynomial kernel feature + map approximation. + :pr:`13003` by :user:`Daniel López Sánchez <lopeLH>`. + + :mod:`sklearn.linear_model` ........................... @@ -235,6 +244,7 @@ Changelog efficient leave-one-out cross-validation scheme ``cv=None``. :pr:`6624` by :user:`Marijn van Vliet <wmvanvliet>`. + :mod:`sklearn.manifold` ....................... diff --git a/examples/plot_scalable_poly_kernels.py b/examples/plot_scalable_poly_kernels.py new file mode 100644 index 0000000000000..845ba1fdf3050 --- /dev/null +++ b/examples/plot_scalable_poly_kernels.py @@ -0,0 +1,186 @@ +""" +======================================================= +Scalable learning with polynomial kernel aproximation +======================================================= + +This example illustrates the use of :class:`PolynomialCountSketch` to +efficiently generate polynomial kernel feature-space approximations. +This is used to train linear classifiers that approximate the accuracy +of kernelized ones. + +.. currentmodule:: sklearn.kernel_approximation + +We use the Covtype dataset [2], trying to reproduce the experiments on the +original paper of Tensor Sketch [1], i.e. the algorithm implemented by +:class:`PolynomialCountSketch`. + +First, we compute the accuracy of a linear classifier on the original +features. Then, we train linear classifiers on different numbers of +features (`n_components`) generated by :class:`PolynomialCountSketch`, +approximating the accuracy of a kernelized classifier in a scalable manner. +""" +print(__doc__) + +# Author: Daniel Lopez-Sanchez <[email protected]> +# License: BSD 3 clause +import matplotlib.pyplot as plt +from sklearn.datasets import fetch_covtype +from sklearn.model_selection import train_test_split +from sklearn.preprocessing import MinMaxScaler, Normalizer +from sklearn.svm import LinearSVC +from sklearn.kernel_approximation import PolynomialCountSketch +from sklearn.pipeline import Pipeline, make_pipeline +import time + +# %% +# Load the Covtype dataset, which contains 581,012 samples +# with 54 features each, distributed among 6 classes. The goal of this dataset +# is to predict forest cover type from cartographic variables only +# (no remotely sensed data). After loading, we transform it into a binary +# classification problem to match the version of the dataset in the +# LIBSVM webpage [2], which was the one used in [1]. + +X, y = fetch_covtype(return_X_y=True) + +y[y != 2] = 0 +y[y == 2] = 1 # We will try to separate class 2 from the other 6 classes. + +# %% +# Here we select 5,000 samples for training and 10,000 for testing. +# To actually reproduce the results in the original Tensor Sketch paper, +# select 100,000 for training. + +X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=5_000, + test_size=10_000, + random_state=42) + +# %% +# Now scale features to the range [0, 1] to match the format of the dataset in +# the LIBSVM webpage, and then normalize to unit length as done in the +# original Tensor Sketch paper [1]. + +mm = make_pipeline(MinMaxScaler(), Normalizer()) +X_train = mm.fit_transform(X_train) +X_test = mm.transform(X_test) + + +# %% +# As a baseline, train a linear SVM on the original features and print the +# accuracy. We also measure and store accuracies and training times to +# plot them latter. + +results = {} + +lsvm = LinearSVC() +start = time.time() +lsvm.fit(X_train, y_train) +lsvm_time = time.time() - start +lsvm_score = 100 * lsvm.score(X_test, y_test) + +results["LSVM"] = {"time": lsvm_time, "score": lsvm_score} +print(f"Linear SVM score on raw features: {lsvm_score:.2f}%") + +# %% +# Then we train linear SVMs on the features generated by +# :class:`PolynomialCountSketch` with different values for `n_components`, +# showing that these kernel feature approximations improve the accuracy +# of linear classification. In typical application scenarios, `n_components` +# should be larger than the number of features in the input representation +# in order to achieve an improvement with respect to linear classification. +# As a rule of thumb, the optimum of evaluation score / run time cost is +# typically achieved at around `n_components` = 10 * `n_features`, though this +# might depend on the specific dataset being handled. Note that, since the +# original samples have 54 features, the explicit feature map of the +# polynomial kernel of degree four would have approximately 8.5 million +# features (precisely, 54^4). Thanks to :class:`PolynomialCountSketch`, we can +# condense most of the discriminative information of that feature space into a +# much more compact representation. We repeat the experiment 5 times to +# compensate for the stochastic nature of :class:`PolynomialCountSketch`. + +n_runs = 3 +for n_components in [250, 500, 1000, 2000]: + + ps_lsvm_time = 0 + ps_lsvm_score = 0 + for _ in range(n_runs): + + pipeline = Pipeline(steps=[("kernel_approximator", + PolynomialCountSketch( + n_components=n_components, + degree=4)), + ("linear_classifier", LinearSVC())]) + + start = time.time() + pipeline.fit(X_train, y_train) + ps_lsvm_time += time.time() - start + ps_lsvm_score += 100 * pipeline.score(X_test, y_test) + + ps_lsvm_time /= n_runs + ps_lsvm_score /= n_runs + + results[f"LSVM + PS({n_components})"] = { + "time": ps_lsvm_time, "score": ps_lsvm_score + } + print(f"Linear SVM score on {n_components} PolynomialCountSketch " + + f"features: {ps_lsvm_score:.2f}%") + +# %% +# Train a kernelized SVM to see how well :class:`PolynomialCountSketch` +# is approximating the performance of the kernel. This, of course, may take +# some time, as the SVC class has a relatively poor scalability. This is the +# reason why kernel approximators are so useful: + +from sklearn.svm import SVC + +ksvm = SVC(C=500., kernel="poly", degree=4, coef0=0, gamma=1.) + +start = time.time() +ksvm.fit(X_train, y_train) +ksvm_time = time.time() - start +ksvm_score = 100 * ksvm.score(X_test, y_test) + +results["KSVM"] = {"time": ksvm_time, "score": ksvm_score} +print(f"Kernel-SVM score on raw featrues: {ksvm_score:.2f}%") + +# %% +# Finally, plot the resuts of the different methods against their training +# times. As we can see, the kernelized SVM achieves a higher accuracy, +# but its training time is much larger and, most importantly, will grow +# much faster if the number of training samples increases. + +N_COMPONENTS = [250, 500, 1000, 2000] + +fig, ax = plt.subplots(figsize=(7, 7)) +ax.scatter([results["LSVM"]["time"], ], [results["LSVM"]["score"], ], + label="Linear SVM", c="green", marker="^") + +ax.scatter([results["LSVM + PS(250)"]["time"], ], + [results["LSVM + PS(250)"]["score"], ], + label="Linear SVM + PolynomialCountSketch", c="blue") +for n_components in N_COMPONENTS: + ax.scatter([results[f"LSVM + PS({n_components})"]["time"], ], + [results[f"LSVM + PS({n_components})"]["score"], ], + c="blue") + ax.annotate(f"n_comp.={n_components}", + (results[f"LSVM + PS({n_components})"]["time"], + results[f"LSVM + PS({n_components})"]["score"]), + xytext=(-30, 10), textcoords="offset pixels") + +ax.scatter([results["KSVM"]["time"], ], [results["KSVM"]["score"], ], + label="Kernel SVM", c="red", marker="x") + +ax.set_xlabel("Training time (s)") +ax.set_ylabel("Accurary (%)") +ax.legend() +plt.show() + +# %% +# References +# ========== +# +# [1] Pham, Ninh and Rasmus Pagh. "Fast and scalable polynomial kernels via +# explicit feature maps." KDD '13 (2013). +# https://doi.org/10.1145/2487575.2487591 +# +# [2] LIBSVM binary datasets repository +# https://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/binary.html diff --git a/sklearn/kernel_approximation.py b/sklearn/kernel_approximation.py index 0310523e63213..19b2c432a758f 100644 --- a/sklearn/kernel_approximation.py +++ b/sklearn/kernel_approximation.py @@ -1,10 +1,11 @@ """ The :mod:`sklearn.kernel_approximation` module implements several -approximate kernel feature maps base on Fourier transforms. +approximate kernel feature maps based on Fourier transforms and Count Sketches. """ # Author: Andreas Mueller <[email protected]> -# +# Daniel Lopez-Sanchez (TensorSketch) <[email protected]> + # License: BSD 3 clause import warnings @@ -12,6 +13,10 @@ import numpy as np import scipy.sparse as sp from scipy.linalg import svd +try: + from scipy.fft import fft, ifft +except ImportError: # scipy < 1.4 + from scipy.fftpack import fft, ifft from .base import BaseEstimator from .base import TransformerMixin @@ -22,6 +27,171 @@ from .utils.validation import check_non_negative, _deprecate_positional_args +class PolynomialCountSketch(BaseEstimator, TransformerMixin): + """Polynomial kernel approximation via Tensor Sketch. + + Implements Tensor Sketch, which approximates the feature map + of the polynomial kernel:: + + K(X, Y) = (gamma * <X, Y> + coef0)^degree + + by efficiently computing a Count Sketch of the outer product of a + vector with itself using Fast Fourier Transforms (FFT). Read more in the + :ref:`User Guide <polynomial_kernel_approx>`. + + Parameters + ---------- + gamma : float, default=1.0 + Parameter of the polynomial kernel whose feature map + will be approximated. + + degree : int, default=2 + Degree of the polynomial kernel whose feature map + will be approximated. + + coef0 : int, default=0 + Constant term of the polynomial kernel whose feature map + will be approximated. + + n_components : int, default=100 + Dimensionality of the output feature space. Usually, n_components + should be greater than the number of features in input samples in + order to achieve good performance. The optimal score / run time + balance is typically achieved around n_components = 10 * n_features, + but this depends on the specific dataset being used. + + random_state : int, RandomState instance, default=None + Determines random number generation for indexHash and bitHash + initialization. Pass an int for reproducible results across multiple + function calls. See :term:`Glossary <random_state>`. + + Attributes + ---------- + indexHash_ : ndarray of shape (degree, n_features), dtype=int64 + Array of indexes in range [0, n_components) used to represent + the 2-wise independent hash functions for Count Sketch computation. + + bitHash_ : ndarray of shape (degree, n_features), dtype=float32 + Array with random entries in {+1, -1}, used to represent + the 2-wise independent hash functions for Count Sketch computation. + + Examples + -------- + >>> from sklearn.kernel_approximation import PolynomialCountSketch + >>> from sklearn.linear_model import SGDClassifier + >>> X = [[0, 0], [1, 1], [1, 0], [0, 1]] + >>> y = [0, 0, 1, 1] + >>> ps = PolynomialCountSketch(degree=3, random_state=1) + >>> X_features = ps.fit_transform(X) + >>> clf = SGDClassifier(max_iter=10, tol=1e-3) + >>> clf.fit(X_features, y) + SGDClassifier(max_iter=10) + >>> clf.score(X_features, y) + 1.0 + """ + + def __init__(self, *, gamma=1., degree=2, coef0=0, n_components=100, + random_state=None): + self.gamma = gamma + self.degree = degree + self.coef0 = coef0 + self.n_components = n_components + self.random_state = random_state + + def fit(self, X, y=None): + """Fit the model with X. + + Initializes the internal variables. The method needs no information + about the distribution of data, so we only care about n_features in X. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training data, where n_samples in the number of samples + and n_features is the number of features. + + Returns + ------- + self : object + Returns the transformer. + """ + if not self.degree >= 1: + raise ValueError(f"degree={self.degree} should be >=1.") + + X = self._validate_data(X, accept_sparse="csc") + random_state = check_random_state(self.random_state) + + n_features = X.shape[1] + if self.coef0 != 0: + n_features += 1 + + self.indexHash_ = random_state.randint(0, high=self.n_components, + size=(self.degree, n_features)) + + self.bitHash_ = random_state.choice(a=[-1, 1], + size=(self.degree, n_features)) + return self + + def transform(self, X): + """Generate the feature map approximation for X. + + Parameters + ---------- + X : {array-like}, shape (n_samples, n_features) + New data, where n_samples in the number of samples + and n_features is the number of features. + + Returns + ------- + X_new : array-like, shape (n_samples, n_components) + """ + + check_is_fitted(self) + X = self._validate_data(X, accept_sparse="csc") + + X_gamma = np.sqrt(self.gamma) * X + + if sp.issparse(X_gamma) and self.coef0 != 0: + X_gamma = sp.hstack([X_gamma, np.sqrt(self.coef0) * + np.ones((X_gamma.shape[0], 1))], + format="csc") + + elif not sp.issparse(X_gamma) and self.coef0 != 0: + X_gamma = np.hstack([X_gamma, np.sqrt(self.coef0) * + np.ones((X_gamma.shape[0], 1))]) + + if X_gamma.shape[1] != self.indexHash_.shape[1]: + raise ValueError("Number of features of test samples does not" + " match that of training samples.") + + count_sketches = np.zeros( + (X_gamma.shape[0], self.degree, self.n_components)) + + if sp.issparse(X_gamma): + for j in range(X_gamma.shape[1]): + for d in range(self.degree): + iHashIndex = self.indexHash_[d, j] + iHashBit = self.bitHash_[d, j] + count_sketches[:, d, iHashIndex] += \ + (iHashBit * X_gamma[:, j]).toarray().ravel() + + else: + for j in range(X_gamma.shape[1]): + for d in range(self.degree): + iHashIndex = self.indexHash_[d, j] + iHashBit = self.bitHash_[d, j] + count_sketches[:, d, iHashIndex] += \ + iHashBit * X_gamma[:, j] + + # For each same, compute a count sketch of phi(x) using the polynomial + # multiplication (via FFT) of p count sketches of x. + count_sketches_fft = fft(count_sketches, axis=2, overwrite_x=True) + count_sketches_fft_prod = np.prod(count_sketches_fft, axis=1) + data_sketch = np.real(ifft(count_sketches_fft_prod, overwrite_x=True)) + + return data_sketch + + class RBFSampler(TransformerMixin, BaseEstimator): """Approximates feature map of an RBF kernel by Monte Carlo approximation of its Fourier transform.
diff --git a/sklearn/tests/test_kernel_approximation.py b/sklearn/tests/test_kernel_approximation.py index 8d37ce218f227..0cee04f9f2d0a 100644 --- a/sklearn/tests/test_kernel_approximation.py +++ b/sklearn/tests/test_kernel_approximation.py @@ -10,6 +10,7 @@ from sklearn.kernel_approximation import AdditiveChi2Sampler from sklearn.kernel_approximation import SkewedChi2Sampler from sklearn.kernel_approximation import Nystroem +from sklearn.kernel_approximation import PolynomialCountSketch from sklearn.metrics.pairwise import polynomial_kernel, rbf_kernel, chi2_kernel # generate data @@ -20,6 +21,40 @@ Y /= Y.sum(axis=1)[:, np.newaxis] [email protected]('degree', [-1, 0]) +def test_polynomial_count_sketch_raises_if_degree_lower_than_one(degree): + with pytest.raises(ValueError, match=f'degree={degree} should be >=1.'): + ps_transform = PolynomialCountSketch(degree=degree) + ps_transform.fit(X, Y) + + [email protected]('X', [X, csr_matrix(X)]) [email protected]('Y', [Y, csr_matrix(Y)]) [email protected]('gamma', [0.1, 1, 2.5]) [email protected]('degree', [1, 2, 3]) [email protected]('coef0', [0, 1, 2.5]) +def test_polynomial_count_sketch(X, Y, gamma, degree, coef0): + # test that PolynomialCountSketch approximates polynomial + # kernel on random data + + # compute exact kernel + kernel = polynomial_kernel(X, Y, gamma=gamma, degree=degree, coef0=coef0) + + # approximate kernel mapping + ps_transform = PolynomialCountSketch(n_components=5000, gamma=gamma, + coef0=coef0, degree=degree, + random_state=42) + X_trans = ps_transform.fit_transform(X) + Y_trans = ps_transform.transform(Y) + kernel_approx = np.dot(X_trans, Y_trans.T) + + error = kernel - kernel_approx + assert np.abs(np.mean(error)) <= 0.05 # close to unbiased + np.abs(error, out=error) + assert np.max(error) <= 0.1 # nothing too far off + assert np.mean(error) <= 0.05 # mean is fairly close + + def _linear_kernel(X, Y): return np.dot(X, Y.T)
[ { "path": "doc/modules/classes.rst", "old_path": "a/doc/modules/classes.rst", "new_path": "b/doc/modules/classes.rst", "metadata": "diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst\nindex 2e54d000a13aa..70a5174629f37 100644\n--- a/doc/modules/classes.rst\n+++ b/doc/modules/classes.rst\n@@ -706,6 +706,7 @@ Plotting\n \n kernel_approximation.AdditiveChi2Sampler\n kernel_approximation.Nystroem\n+ kernel_approximation.PolynomialCountSketch\n kernel_approximation.RBFSampler\n kernel_approximation.SkewedChi2Sampler\n \n" }, { "path": "doc/modules/kernel_approximation.rst", "old_path": "a/doc/modules/kernel_approximation.rst", "new_path": "b/doc/modules/kernel_approximation.rst", "metadata": "diff --git a/doc/modules/kernel_approximation.rst b/doc/modules/kernel_approximation.rst\nindex fb3843c6bc045..4f5ee46a42057 100644\n--- a/doc/modules/kernel_approximation.rst\n+++ b/doc/modules/kernel_approximation.rst\n@@ -149,6 +149,51 @@ above for the :class:`RBFSampler`. The only difference is in the free\n parameter, that is called :math:`c`.\n For a motivation for this mapping and the mathematical details see [LS2010]_.\n \n+.. _polynomial_kernel_approx:\n+\n+Polynomial Kernel Approximation via Tensor Sketch\n+-------------------------------------------------\n+\n+The :ref:`polynomial kernel <polynomial_kernel>` is a popular type of kernel\n+function given by:\n+\n+.. math::\n+\n+ k(x, y) = (\\gamma x^\\top y +c_0)^d\n+\n+where:\n+\n+ * ``x``, ``y`` are the input vectors\n+ * ``d`` is the kernel degree\n+\n+Intuitively, the feature space of the polynomial kernel of degree `d`\n+consists of all possible degree-`d` products among input features, which enables\n+learning algorithms using this kernel to account for interactions between features.\n+\n+The TensorSketch [PP2013]_ method, as implemented in :class:`PolynomialCountSketch`, is a\n+scalable, input data independent method for polynomial kernel approximation.\n+It is based on the concept of Count sketch [WIKICS]_ [CCF2002]_ , a dimensionality\n+reduction technique similar to feature hashing, which instead uses several\n+independent hash functions. TensorSketch obtains a Count Sketch of the outer product\n+of two vectors (or a vector with itself), which can be used as an approximation of the\n+polynomial kernel feature space. In particular, instead of explicitly computing\n+the outer product, TensorSketch computes the Count Sketch of the vectors and then\n+uses polynomial multiplication via the Fast Fourier Transform to compute the\n+Count Sketch of their outer product.\n+\n+Conveniently, the training phase of TensorSketch simply consists of initializing\n+some random variables. It is thus independent of the input data, i.e. it only\n+depends on the number of input features, but not the data values.\n+In addition, this method can transform samples in\n+:math:`\\mathcal{O}(n_{\\text{samples}}(n_{\\text{features}} + n_{\\text{components}} \\log(n_{\\text{components}})))`\n+time, where :math:`n_{\\text{components}}` is the desired output dimension,\n+determined by ``n_components``.\n+\n+.. topic:: Examples:\n+\n+ * :ref:`sphx_glr_auto_examples_plot_scalable_poly_kernels.py`\n+\n+.. _tensor_sketch_kernel_approx:\n \n Mathematical Details\n --------------------\n@@ -201,3 +246,11 @@ or store training examples.\n .. [VVZ2010] `\"Generalized RBF feature maps for Efficient Detection\"\n <https://www.robots.ox.ac.uk/~vgg/publications/2010/Sreekanth10/sreekanth10.pdf>`_\n Vempati, S. and Vedaldi, A. and Zisserman, A. and Jawahar, CV - 2010\n+ .. [PP2013] `\"Fast and scalable polynomial kernels via explicit feature maps\"\n+ <https://doi.org/10.1145/2487575.2487591>`_\n+ Pham, N., & Pagh, R. - 2013\n+ .. [CCF2002] `\"Finding frequent items in data streams\"\n+ <http://www.cs.princeton.edu/courses/archive/spring04/cos598B/bib/CharikarCF.pdf>`_\n+ Charikar, M., Chen, K., & Farach-Colton - 2002\n+ .. [WIKICS] `\"Wikipedia: Count sketch\"\n+ <https://en.wikipedia.org/wiki/Count_sketch>`_\n" }, { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex 2682902a20983..c73f1a373a86b 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -221,6 +221,15 @@ Changelog\n - |Enhancement| :class:`isotonic.IsotonicRegression` now accepts 2darray with 1 feature as\n input array. :pr:`17379` by :user:`Jiaxiang <fujiaxiang>`.\n \n+:mod:`sklearn.kernel_approximation`\n+...................................\n+\n+- |Feature| Added class :class:`kernel_approximation.PolynomialCountSketch`\n+ which implements the Tensor Sketch algorithm for polynomial kernel feature\n+ map approximation.\n+ :pr:`13003` by :user:`Daniel López Sánchez <lopeLH>`.\n+\n+\n :mod:`sklearn.linear_model`\n ...........................\n \n@@ -235,6 +244,7 @@ Changelog\n efficient leave-one-out cross-validation scheme ``cv=None``. :pr:`6624` by\n :user:`Marijn van Vliet <wmvanvliet>`.\n \n+\n :mod:`sklearn.manifold`\n .......................\n \n" } ]
0.24
57bd85ed6a613028c2abb5e27dcf30263f0daa4b
[]
[ "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-1-2.5-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-3-1-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-1-0.1-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_nystroem_poly_kernel_params", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-3-2.5-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-3-0.1-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-3-1-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-2-1-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-1-0.1-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-3-1-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-1-1-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_skewed_chi2_sampler", "sklearn/tests/test_kernel_approximation.py::test_nystroem_singular_kernel", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-1-2.5-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-3-2.5-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-2-0.1-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-1-2.5-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-3-0.1-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-1-1-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-1-1-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-1-1-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-2-2.5-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-1-2.5-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_nystroem_precomputed_kernel", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-2-1-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-2-0.1-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-1-0.1-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-3-2.5-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-1-2.5-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-1-2.5-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-3-0.1-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-3-2.5-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-1-2.5-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-2-2.5-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-2-1-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-1-1-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-2-1-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-1-2.5-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-3-2.5-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-2-1-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-2-2.5-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-3-1-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-3-2.5-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-1-1-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-2-0.1-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-3-1-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-2-1-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-2-2.5-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-1-0.1-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-2-0.1-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-2-2.5-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-2-0.1-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-2-2.5-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-1-1-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch_raises_if_degree_lower_than_one[0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-3-1-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-3-1-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-2-0.1-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_rbf_sampler", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-3-0.1-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-2-0.1-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-2-2.5-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-1-0.1-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-2-1-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-3-1-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-2-2.5-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-1-0.1-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-3-0.1-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-2-1-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-1-2.5-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-2-2.5-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-3-1-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-3-1-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-1-1-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-2-0.1-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-2-0.1-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-1-0.1-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-1-0.1-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-3-0.1-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-3-2.5-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_additive_chi2_sampler", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-2-0.1-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_nystroem_callable", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-1-1-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-2-1-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-2-0.1-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-2-1-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-1-0.1-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-1-0.1-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-3-0.1-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-3-1-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-3-0.1-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_additive_chi2_sampler_exceptions", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-3-2.5-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-2-2.5-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-3-1-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-3-2.5-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-1-0.1-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-2-1-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-1-1-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-3-0.1-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_nystroem_default_parameters", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-3-0.1-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-1-0.1-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-2-1-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-3-2.5-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-2-0.1-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-3-0.1-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-1-2.5-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-3-0.1-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-3-2.5-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-1-2.5-Y1-X0]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[1-1-1-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-1-1-Y0-X0]", "sklearn/tests/test_kernel_approximation.py::test_input_validation", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-3-2.5-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-2-2.5-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[0-1-2.5-Y0-X1]", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch[2.5-2-2.5-Y1-X1]", "sklearn/tests/test_kernel_approximation.py::test_nystroem_approximation", "sklearn/tests/test_kernel_approximation.py::test_polynomial_count_sketch_raises_if_degree_lower_than_one[-1]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [ { "type": "file", "name": "benchmarks/bench_plot_polynomial_kernel_approximation.py" }, { "type": "file", "name": "examples/plot_scalable_poly_kernels.py" } ] }
[ { "path": "doc/modules/classes.rst", "old_path": "a/doc/modules/classes.rst", "new_path": "b/doc/modules/classes.rst", "metadata": "diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst\nindex 2e54d000a13aa..70a5174629f37 100644\n--- a/doc/modules/classes.rst\n+++ b/doc/modules/classes.rst\n@@ -706,6 +706,7 @@ Plotting\n \n kernel_approximation.AdditiveChi2Sampler\n kernel_approximation.Nystroem\n+ kernel_approximation.PolynomialCountSketch\n kernel_approximation.RBFSampler\n kernel_approximation.SkewedChi2Sampler\n \n" }, { "path": "doc/modules/kernel_approximation.rst", "old_path": "a/doc/modules/kernel_approximation.rst", "new_path": "b/doc/modules/kernel_approximation.rst", "metadata": "diff --git a/doc/modules/kernel_approximation.rst b/doc/modules/kernel_approximation.rst\nindex fb3843c6bc045..4f5ee46a42057 100644\n--- a/doc/modules/kernel_approximation.rst\n+++ b/doc/modules/kernel_approximation.rst\n@@ -149,6 +149,51 @@ above for the :class:`RBFSampler`. The only difference is in the free\n parameter, that is called :math:`c`.\n For a motivation for this mapping and the mathematical details see [LS2010]_.\n \n+.. _polynomial_kernel_approx:\n+\n+Polynomial Kernel Approximation via Tensor Sketch\n+-------------------------------------------------\n+\n+The :ref:`polynomial kernel <polynomial_kernel>` is a popular type of kernel\n+function given by:\n+\n+.. math::\n+\n+ k(x, y) = (\\gamma x^\\top y +c_0)^d\n+\n+where:\n+\n+ * ``x``, ``y`` are the input vectors\n+ * ``d`` is the kernel degree\n+\n+Intuitively, the feature space of the polynomial kernel of degree `d`\n+consists of all possible degree-`d` products among input features, which enables\n+learning algorithms using this kernel to account for interactions between features.\n+\n+The TensorSketch [PP2013]_ method, as implemented in :class:`PolynomialCountSketch`, is a\n+scalable, input data independent method for polynomial kernel approximation.\n+It is based on the concept of Count sketch [WIKICS]_ [CCF2002]_ , a dimensionality\n+reduction technique similar to feature hashing, which instead uses several\n+independent hash functions. TensorSketch obtains a Count Sketch of the outer product\n+of two vectors (or a vector with itself), which can be used as an approximation of the\n+polynomial kernel feature space. In particular, instead of explicitly computing\n+the outer product, TensorSketch computes the Count Sketch of the vectors and then\n+uses polynomial multiplication via the Fast Fourier Transform to compute the\n+Count Sketch of their outer product.\n+\n+Conveniently, the training phase of TensorSketch simply consists of initializing\n+some random variables. It is thus independent of the input data, i.e. it only\n+depends on the number of input features, but not the data values.\n+In addition, this method can transform samples in\n+:math:`\\mathcal{O}(n_{\\text{samples}}(n_{\\text{features}} + n_{\\text{components}} \\log(n_{\\text{components}})))`\n+time, where :math:`n_{\\text{components}}` is the desired output dimension,\n+determined by ``n_components``.\n+\n+.. topic:: Examples:\n+\n+ * :ref:`sphx_glr_auto_examples_plot_scalable_poly_kernels.py`\n+\n+.. _tensor_sketch_kernel_approx:\n \n Mathematical Details\n --------------------\n@@ -201,3 +246,11 @@ or store training examples.\n .. [VVZ2010] `\"Generalized RBF feature maps for Efficient Detection\"\n <https://www.robots.ox.ac.uk/~vgg/publications/2010/Sreekanth10/sreekanth10.pdf>`_\n Vempati, S. and Vedaldi, A. and Zisserman, A. and Jawahar, CV - 2010\n+ .. [PP2013] `\"Fast and scalable polynomial kernels via explicit feature maps\"\n+ <https://doi.org/10.1145/2487575.2487591>`_\n+ Pham, N., & Pagh, R. - 2013\n+ .. [CCF2002] `\"Finding frequent items in data streams\"\n+ <http://www.cs.princeton.edu/courses/archive/spring04/cos598B/bib/CharikarCF.pdf>`_\n+ Charikar, M., Chen, K., & Farach-Colton - 2002\n+ .. [WIKICS] `\"Wikipedia: Count sketch\"\n+ <https://en.wikipedia.org/wiki/Count_sketch>`_\n" }, { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex 2682902a20983..c73f1a373a86b 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -221,6 +221,15 @@ Changelog\n - |Enhancement| :class:`isotonic.IsotonicRegression` now accepts 2darray with 1 feature as\n input array. :pr:`<PRID>` by :user:`<NAME>`.\n \n+:mod:`sklearn.kernel_approximation`\n+...................................\n+\n+- |Feature| Added class :class:`kernel_approximation.PolynomialCountSketch`\n+ which implements the Tensor Sketch algorithm for polynomial kernel feature\n+ map approximation.\n+ :pr:`<PRID>` by :user:`<NAME>`.\n+\n+\n :mod:`sklearn.linear_model`\n ...........................\n \n@@ -235,6 +244,7 @@ Changelog\n efficient leave-one-out cross-validation scheme ``cv=None``. :pr:`<PRID>` by\n :user:`<NAME>`.\n \n+\n :mod:`sklearn.manifold`\n .......................\n \n" } ]
diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst index 2e54d000a13aa..70a5174629f37 100644 --- a/doc/modules/classes.rst +++ b/doc/modules/classes.rst @@ -706,6 +706,7 @@ Plotting kernel_approximation.AdditiveChi2Sampler kernel_approximation.Nystroem + kernel_approximation.PolynomialCountSketch kernel_approximation.RBFSampler kernel_approximation.SkewedChi2Sampler diff --git a/doc/modules/kernel_approximation.rst b/doc/modules/kernel_approximation.rst index fb3843c6bc045..4f5ee46a42057 100644 --- a/doc/modules/kernel_approximation.rst +++ b/doc/modules/kernel_approximation.rst @@ -149,6 +149,51 @@ above for the :class:`RBFSampler`. The only difference is in the free parameter, that is called :math:`c`. For a motivation for this mapping and the mathematical details see [LS2010]_. +.. _polynomial_kernel_approx: + +Polynomial Kernel Approximation via Tensor Sketch +------------------------------------------------- + +The :ref:`polynomial kernel <polynomial_kernel>` is a popular type of kernel +function given by: + +.. math:: + + k(x, y) = (\gamma x^\top y +c_0)^d + +where: + + * ``x``, ``y`` are the input vectors + * ``d`` is the kernel degree + +Intuitively, the feature space of the polynomial kernel of degree `d` +consists of all possible degree-`d` products among input features, which enables +learning algorithms using this kernel to account for interactions between features. + +The TensorSketch [PP2013]_ method, as implemented in :class:`PolynomialCountSketch`, is a +scalable, input data independent method for polynomial kernel approximation. +It is based on the concept of Count sketch [WIKICS]_ [CCF2002]_ , a dimensionality +reduction technique similar to feature hashing, which instead uses several +independent hash functions. TensorSketch obtains a Count Sketch of the outer product +of two vectors (or a vector with itself), which can be used as an approximation of the +polynomial kernel feature space. In particular, instead of explicitly computing +the outer product, TensorSketch computes the Count Sketch of the vectors and then +uses polynomial multiplication via the Fast Fourier Transform to compute the +Count Sketch of their outer product. + +Conveniently, the training phase of TensorSketch simply consists of initializing +some random variables. It is thus independent of the input data, i.e. it only +depends on the number of input features, but not the data values. +In addition, this method can transform samples in +:math:`\mathcal{O}(n_{\text{samples}}(n_{\text{features}} + n_{\text{components}} \log(n_{\text{components}})))` +time, where :math:`n_{\text{components}}` is the desired output dimension, +determined by ``n_components``. + +.. topic:: Examples: + + * :ref:`sphx_glr_auto_examples_plot_scalable_poly_kernels.py` + +.. _tensor_sketch_kernel_approx: Mathematical Details -------------------- @@ -201,3 +246,11 @@ or store training examples. .. [VVZ2010] `"Generalized RBF feature maps for Efficient Detection" <https://www.robots.ox.ac.uk/~vgg/publications/2010/Sreekanth10/sreekanth10.pdf>`_ Vempati, S. and Vedaldi, A. and Zisserman, A. and Jawahar, CV - 2010 + .. [PP2013] `"Fast and scalable polynomial kernels via explicit feature maps" + <https://doi.org/10.1145/2487575.2487591>`_ + Pham, N., & Pagh, R. - 2013 + .. [CCF2002] `"Finding frequent items in data streams" + <http://www.cs.princeton.edu/courses/archive/spring04/cos598B/bib/CharikarCF.pdf>`_ + Charikar, M., Chen, K., & Farach-Colton - 2002 + .. [WIKICS] `"Wikipedia: Count sketch" + <https://en.wikipedia.org/wiki/Count_sketch>`_ diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index 2682902a20983..c73f1a373a86b 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -221,6 +221,15 @@ Changelog - |Enhancement| :class:`isotonic.IsotonicRegression` now accepts 2darray with 1 feature as input array. :pr:`<PRID>` by :user:`<NAME>`. +:mod:`sklearn.kernel_approximation` +................................... + +- |Feature| Added class :class:`kernel_approximation.PolynomialCountSketch` + which implements the Tensor Sketch algorithm for polynomial kernel feature + map approximation. + :pr:`<PRID>` by :user:`<NAME>`. + + :mod:`sklearn.linear_model` ........................... @@ -235,6 +244,7 @@ Changelog efficient leave-one-out cross-validation scheme ``cv=None``. :pr:`<PRID>` by :user:`<NAME>`. + :mod:`sklearn.manifold` ....................... If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names: [{'type': 'file', 'name': 'benchmarks/bench_plot_polynomial_kernel_approximation.py'}, {'type': 'file', 'name': 'examples/plot_scalable_poly_kernels.py'}]
scikit-learn/scikit-learn
scikit-learn__scikit-learn-10591
https://github.com/scikit-learn/scikit-learn/pull/10591
diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst index 2e54d000a13aa..2fd1366e18434 100644 --- a/doc/modules/classes.rst +++ b/doc/modules/classes.rst @@ -946,6 +946,7 @@ details. metrics.cohen_kappa_score metrics.confusion_matrix metrics.dcg_score + metrics.detection_error_tradeoff_curve metrics.f1_score metrics.fbeta_score metrics.hamming_loss diff --git a/doc/modules/model_evaluation.rst b/doc/modules/model_evaluation.rst index f8874869a0274..decd0f42383eb 100644 --- a/doc/modules/model_evaluation.rst +++ b/doc/modules/model_evaluation.rst @@ -306,6 +306,7 @@ Some of these are restricted to the binary classification case: precision_recall_curve roc_curve + detection_error_tradeoff_curve Others also work in the multiclass case: @@ -1437,6 +1438,93 @@ to the given limit. In Data Mining, 2001. Proceedings IEEE International Conference, pp. 131-138. +.. _det_curve: + +Detection error tradeoff (DET) +------------------------------ + +The function :func:`detection_error_tradeoff_curve` computes the +detection error tradeoff curve (DET) curve [WikipediaDET2017]_. +Quoting Wikipedia: + + "A detection error tradeoff (DET) graph is a graphical plot of error rates for + binary classification systems, plotting false reject rate vs. false accept + rate. The x- and y-axes are scaled non-linearly by their standard normal + deviates (or just by logarithmic transformation), yielding tradeoff curves + that are more linear than ROC curves, and use most of the image area to + highlight the differences of importance in the critical operating region." + +DET curves are a variation of receiver operating characteristic (ROC) curves +where False Negative Rate is plotted on the ordinate instead of True Positive +Rate. +DET curves are commonly plotted in normal deviate scale by transformation with +:math:`\phi^{-1}` (with :math:`\phi` being the cumulative distribution +function). +The resulting performance curves explicitly visualize the tradeoff of error +types for given classification algorithms. +See [Martin1997]_ for examples and further motivation. + +This figure compares the ROC and DET curves of two example classifiers on the +same classification task: + +.. image:: ../auto_examples/model_selection/images/sphx_glr_plot_det_001.png + :target: ../auto_examples/model_selection/plot_det.html + :scale: 75 + :align: center + +**Properties:** + +* DET curves form a linear curve in normal deviate scale if the detection + scores are normally (or close-to normally) distributed. + It was shown by [Navratil2007]_ that the reverse it not necessarily true and even more + general distributions are able produce linear DET curves. + +* The normal deviate scale transformation spreads out the points such that a + comparatively larger space of plot is occupied. + Therefore curves with similar classification performance might be easier to + distinguish on a DET plot. + +* With False Negative Rate being "inverse" to True Positive Rate the point + of perfection for DET curves is the origin (in contrast to the top left corner + for ROC curves). + +**Applications and limitations:** + +DET curves are intuitive to read and hence allow quick visual assessment of a +classifier's performance. +Additionally DET curves can be consulted for threshold analysis and operating +point selection. +This is particularly helpful if a comparison of error types is required. + +One the other hand DET curves do not provide their metric as a single number. +Therefore for either automated evaluation or comparison to other +classification tasks metrics like the derived area under ROC curve might be +better suited. + +.. topic:: Examples: + + * See :ref:`sphx_glr_auto_examples_model_selection_plot_det.py` + for an example comparison between receiver operating characteristic (ROC) + curves and Detection error tradeoff (DET) curves. + +.. topic:: References: + + .. [WikipediaDET2017] Wikipedia contributors. Detection error tradeoff. + Wikipedia, The Free Encyclopedia. September 4, 2017, 23:33 UTC. + Available at: https://en.wikipedia.org/w/index.php?title=Detection_error_tradeoff&oldid=798982054. + Accessed February 19, 2018. + + .. [Martin1997] A. Martin, G. Doddington, T. Kamm, M. Ordowski, and M. Przybocki, + `The DET Curve in Assessment of Detection Task Performance + <http://www.dtic.mil/docs/citations/ADA530509>`_, + NIST 1997. + + .. [Navratil2007] J. Navractil and D. Klusacek, + "`On Linear DETs, + <http://www.research.ibm.com/CBG/papers/icassp07_navratil.pdf>`_" + 2007 IEEE International Conference on Acoustics, + Speech and Signal Processing - ICASSP '07, Honolulu, + HI, 2007, pp. IV-229-IV-232. .. _zero_one_loss: diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index cf3347c0ee8cd..ff8149142f3b3 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -212,6 +212,11 @@ Changelog :mod:`sklearn.metrics` ...................... +- |Feature| Added :func:`metrics.detection_error_tradeoff_curve` to compute + Detection Error Tradeoff curve classification metric. + :pr:`10591` by :user:`Jeremy Karnowski <jkarnows>` and + :user:`Daniel Mohns <dmohns>`. + - |Feature| Added :func:`metrics.mean_absolute_percentage_error` metric and the associated scorer for regression problems. :issue:`10708` fixed with the PR :pr:`15007` by :user:`Ashutosh Hathidara <ashutosh1919>`. The scorer and diff --git a/examples/model_selection/plot_det.py b/examples/model_selection/plot_det.py new file mode 100644 index 0000000000000..6cfac7e5ce0ca --- /dev/null +++ b/examples/model_selection/plot_det.py @@ -0,0 +1,145 @@ +""" +======================================= +Detection error tradeoff (DET) curve +======================================= + +In this example, we compare receiver operating characteristic (ROC) and +detection error tradeoff (DET) curves for different classification algorithms +for the same classification task. + +DET curves are commonly plotted in normal deviate scale. +To achieve this we transform the errors rates as returned by the +``detection_error_tradeoff_curve`` function and the axis scale using +``scipy.stats.norm``. + +The point of this example is to demonstrate two properties of DET curves, +namely: + +1. It might be easier to visually assess the overall performance of different + classification algorithms using DET curves over ROC curves. + Due to the linear scale used for plotting ROC curves, different classifiers + usually only differ in the top left corner of the graph and appear similar + for a large part of the plot. On the other hand, because DET curves + represent straight lines in normal deviate scale. As such, they tend to be + distinguishable as a whole and the area of interest spans a large part of + the plot. +2. DET curves give the user direct feedback of the detection error tradeoff to + aid in operating point analysis. + The user can deduct directly from the DET-curve plot at which rate + false-negative error rate will improve when willing to accept an increase in + false-positive error rate (or vice-versa). + +The plots in this example compare ROC curves on the left side to corresponding +DET curves on the right. +There is no particular reason why these classifiers have been chosen for the +example plot over other classifiers available in scikit-learn. + +.. note:: + + - See :func:`sklearn.metrics.roc_curve` for further information about ROC + curves. + + - See :func:`sklearn.metrics.detection_error_tradeoff_curve` for further + information about DET curves. + + - This example is loosely based on + :ref:`sphx_glr_auto_examples_classification_plot_classifier_comparison.py` + . + +""" +import matplotlib.pyplot as plt + +from sklearn.model_selection import train_test_split +from sklearn.preprocessing import StandardScaler +from sklearn.datasets import make_classification +from sklearn.svm import SVC +from sklearn.ensemble import RandomForestClassifier +from sklearn.metrics import detection_error_tradeoff_curve +from sklearn.metrics import roc_curve + +from scipy.stats import norm +from matplotlib.ticker import FuncFormatter + +N_SAMPLES = 1000 + +names = [ + "Linear SVM", + "Random Forest", +] + +classifiers = [ + SVC(kernel="linear", C=0.025), + RandomForestClassifier(max_depth=5, n_estimators=10, max_features=1), +] + +X, y = make_classification( + n_samples=N_SAMPLES, n_features=2, n_redundant=0, n_informative=2, + random_state=1, n_clusters_per_class=1) + +# preprocess dataset, split into training and test part +X = StandardScaler().fit_transform(X) + +X_train, X_test, y_train, y_test = train_test_split( + X, y, test_size=.4, random_state=0) + +# prepare plots +fig, [ax_roc, ax_det] = plt.subplots(1, 2, figsize=(10, 5)) + +# first prepare the ROC curve +ax_roc.set_title('Receiver Operating Characteristic (ROC) curves') +ax_roc.set_xlabel('False Positive Rate') +ax_roc.set_ylabel('True Positive Rate') +ax_roc.set_xlim(0, 1) +ax_roc.set_ylim(0, 1) +ax_roc.grid(linestyle='--') +ax_roc.yaxis.set_major_formatter( + FuncFormatter(lambda y, _: '{:.0%}'.format(y))) +ax_roc.xaxis.set_major_formatter( + FuncFormatter(lambda y, _: '{:.0%}'.format(y))) + +# second prepare the DET curve +ax_det.set_title('Detection Error Tradeoff (DET) curves') +ax_det.set_xlabel('False Positive Rate') +ax_det.set_ylabel('False Negative Rate') +ax_det.set_xlim(-3, 3) +ax_det.set_ylim(-3, 3) +ax_det.grid(linestyle='--') + +# customized ticks for DET curve plot to represent normal deviate scale +ticks = [0.001, 0.01, 0.05, 0.20, 0.5, 0.80, 0.95, 0.99, 0.999] +tick_locs = norm.ppf(ticks) +tick_lbls = [ + '{:.0%}'.format(s) if (100*s).is_integer() else '{:.1%}'.format(s) + for s in ticks +] +plt.sca(ax_det) +plt.xticks(tick_locs, tick_lbls) +plt.yticks(tick_locs, tick_lbls) + +# iterate over classifiers +for name, clf in zip(names, classifiers): + clf.fit(X_train, y_train) + + if hasattr(clf, "decision_function"): + y_score = clf.decision_function(X_test) + else: + y_score = clf.predict_proba(X_test)[:, 1] + + roc_fpr, roc_tpr, _ = roc_curve(y_test, y_score) + det_fpr, det_fnr, _ = detection_error_tradeoff_curve(y_test, y_score) + + ax_roc.plot(roc_fpr, roc_tpr) + + # transform errors into normal deviate scale + ax_det.plot( + norm.ppf(det_fpr), + norm.ppf(det_fnr) + ) + +# add a single legend +plt.sca(ax_det) +plt.legend(names, loc="upper right") + +# plot +plt.tight_layout() +plt.show() diff --git a/sklearn/metrics/__init__.py b/sklearn/metrics/__init__.py index be28005631963..a69d5c618c20f 100644 --- a/sklearn/metrics/__init__.py +++ b/sklearn/metrics/__init__.py @@ -7,6 +7,7 @@ from ._ranking import auc from ._ranking import average_precision_score from ._ranking import coverage_error +from ._ranking import detection_error_tradeoff_curve from ._ranking import dcg_score from ._ranking import label_ranking_average_precision_score from ._ranking import label_ranking_loss @@ -104,6 +105,7 @@ 'coverage_error', 'dcg_score', 'davies_bouldin_score', + 'detection_error_tradeoff_curve', 'euclidean_distances', 'explained_variance_score', 'f1_score', diff --git a/sklearn/metrics/_ranking.py b/sklearn/metrics/_ranking.py index e07f61a92d478..5c58920e3ffd4 100644 --- a/sklearn/metrics/_ranking.py +++ b/sklearn/metrics/_ranking.py @@ -218,6 +218,94 @@ def _binary_uninterpolated_average_precision( average, sample_weight=sample_weight) +def detection_error_tradeoff_curve(y_true, y_score, pos_label=None, + sample_weight=None): + """Compute error rates for different probability thresholds. + + Note: This metrics is used for ranking evaluation of a binary + classification task. + + Read more in the :ref:`User Guide <det_curve>`. + + Parameters + ---------- + y_true : array, shape = [n_samples] + True targets of binary classification in range {-1, 1} or {0, 1}. + + y_score : array, shape = [n_samples] + Estimated probabilities or decision function. + + pos_label : int, optional (default=None) + The label of the positive class + + sample_weight : array-like of shape = [n_samples], optional + Sample weights. + + Returns + ------- + fpr : array, shape = [n_thresholds] + False positive rate (FPR) such that element i is the false positive + rate of predictions with score >= thresholds[i]. This is occasionally + referred to as false acceptance propability or fall-out. + + fnr : array, shape = [n_thresholds] + False negative rate (FNR) such that element i is the false negative + rate of predictions with score >= thresholds[i]. This is occasionally + referred to as false rejection or miss rate. + + thresholds : array, shape = [n_thresholds] + Decreasing score values. + + See also + -------- + roc_curve : Compute Receiver operating characteristic (ROC) curve + precision_recall_curve : Compute precision-recall curve + + Examples + -------- + >>> import numpy as np + >>> from sklearn.metrics import detection_error_tradeoff_curve + >>> y_true = np.array([0, 0, 1, 1]) + >>> y_scores = np.array([0.1, 0.4, 0.35, 0.8]) + >>> fpr, fnr, thresholds = detection_error_tradeoff_curve(y_true, y_scores) + >>> fpr + array([0.5, 0.5, 0. ]) + >>> fnr + array([0. , 0.5, 0.5]) + >>> thresholds + array([0.35, 0.4 , 0.8 ]) + + """ + if len(np.unique(y_true)) != 2: + raise ValueError("Only one class present in y_true. Detection error " + "tradeoff curve is not defined in that case.") + + fps, tps, thresholds = _binary_clf_curve(y_true, y_score, + pos_label=pos_label, + sample_weight=sample_weight) + + fns = tps[-1] - tps + p_count = tps[-1] + n_count = fps[-1] + + # start with false positives zero + first_ind = ( + fps.searchsorted(fps[0], side='right') - 1 + if fps.searchsorted(fps[0], side='right') > 0 + else None + ) + # stop with false negatives zero + last_ind = tps.searchsorted(tps[-1]) + 1 + sl = slice(first_ind, last_ind) + + # reverse the output such that list of false positives is decreasing + return ( + fps[sl][::-1] / n_count, + fns[sl][::-1] / p_count, + thresholds[sl][::-1] + ) + + def _binary_roc_auc_score(y_true, y_score, sample_weight=None, max_fpr=None): """Binary roc auc score""" if len(np.unique(y_true)) != 2:
diff --git a/sklearn/metrics/tests/test_common.py b/sklearn/metrics/tests/test_common.py index 3f2ba83b474c7..24f01d46610a7 100644 --- a/sklearn/metrics/tests/test_common.py +++ b/sklearn/metrics/tests/test_common.py @@ -29,6 +29,7 @@ from sklearn.metrics import cohen_kappa_score from sklearn.metrics import confusion_matrix from sklearn.metrics import coverage_error +from sklearn.metrics import detection_error_tradeoff_curve from sklearn.metrics import explained_variance_score from sklearn.metrics import f1_score from sklearn.metrics import fbeta_score @@ -205,6 +206,7 @@ def precision_recall_curve_padded_thresholds(*args, **kwargs): CURVE_METRICS = { "roc_curve": roc_curve, "precision_recall_curve": precision_recall_curve_padded_thresholds, + "detection_error_tradeoff_curve": detection_error_tradeoff_curve, } THRESHOLDED_METRICS = { @@ -301,6 +303,7 @@ def precision_recall_curve_padded_thresholds(*args, **kwargs): # curves "roc_curve", "precision_recall_curve", + "detection_error_tradeoff_curve", } # Metric undefined with "binary" or "multiclass" input @@ -322,6 +325,7 @@ def precision_recall_curve_padded_thresholds(*args, **kwargs): METRICS_WITH_POS_LABEL = { "roc_curve", "precision_recall_curve", + "detection_error_tradeoff_curve", "brier_score_loss", @@ -352,6 +356,7 @@ def precision_recall_curve_padded_thresholds(*args, **kwargs): "normalized_confusion_matrix", "roc_curve", "precision_recall_curve", + "detection_error_tradeoff_curve", "precision_score", "recall_score", "f1_score", "f2_score", "f0.5_score", "jaccard_score", @@ -464,6 +469,7 @@ def precision_recall_curve_padded_thresholds(*args, **kwargs): "normalized_confusion_matrix", "roc_curve", "precision_recall_curve", + "detection_error_tradeoff_curve", "precision_score", "recall_score", "f2_score", "f0.5_score", diff --git a/sklearn/metrics/tests/test_ranking.py b/sklearn/metrics/tests/test_ranking.py index 3daafa8d196d3..e08a8909cfe72 100644 --- a/sklearn/metrics/tests/test_ranking.py +++ b/sklearn/metrics/tests/test_ranking.py @@ -16,11 +16,13 @@ from sklearn.utils._testing import assert_almost_equal from sklearn.utils._testing import assert_array_equal from sklearn.utils._testing import assert_array_almost_equal +from sklearn.utils._testing import assert_raises from sklearn.utils._testing import assert_warns from sklearn.metrics import auc from sklearn.metrics import average_precision_score from sklearn.metrics import coverage_error +from sklearn.metrics import detection_error_tradeoff_curve from sklearn.metrics import label_ranking_average_precision_score from sklearn.metrics import precision_recall_curve from sklearn.metrics import label_ranking_loss @@ -925,6 +927,111 @@ def test_score_scale_invariance(): assert pr_auc == pr_auc_shifted [email protected]("y_true,y_score,expected_fpr,expected_fnr", [ + ([0, 0, 1], [0, 0.5, 1], [0], [0]), + ([0, 0, 1], [0, 0.25, 0.5], [0], [0]), + ([0, 0, 1], [0.5, 0.75, 1], [0], [0]), + ([0, 0, 1], [0.25, 0.5, 0.75], [0], [0]), + ([0, 1, 0], [0, 0.5, 1], [0.5], [0]), + ([0, 1, 0], [0, 0.25, 0.5], [0.5], [0]), + ([0, 1, 0], [0.5, 0.75, 1], [0.5], [0]), + ([0, 1, 0], [0.25, 0.5, 0.75], [0.5], [0]), + ([0, 1, 1], [0, 0.5, 1], [0.0], [0]), + ([0, 1, 1], [0, 0.25, 0.5], [0], [0]), + ([0, 1, 1], [0.5, 0.75, 1], [0], [0]), + ([0, 1, 1], [0.25, 0.5, 0.75], [0], [0]), + ([1, 0, 0], [0, 0.5, 1], [1, 1, 0.5], [0, 1, 1]), + ([1, 0, 0], [0, 0.25, 0.5], [1, 1, 0.5], [0, 1, 1]), + ([1, 0, 0], [0.5, 0.75, 1], [1, 1, 0.5], [0, 1, 1]), + ([1, 0, 0], [0.25, 0.5, 0.75], [1, 1, 0.5], [0, 1, 1]), + ([1, 0, 1], [0, 0.5, 1], [1, 1, 0], [0, 0.5, 0.5]), + ([1, 0, 1], [0, 0.25, 0.5], [1, 1, 0], [0, 0.5, 0.5]), + ([1, 0, 1], [0.5, 0.75, 1], [1, 1, 0], [0, 0.5, 0.5]), + ([1, 0, 1], [0.25, 0.5, 0.75], [1, 1, 0], [0, 0.5, 0.5]), +]) +def test_detection_error_tradeoff_curve_toydata(y_true, y_score, + expected_fpr, expected_fnr): + # Check on a batch of small examples. + fpr, fnr, _ = detection_error_tradeoff_curve(y_true, y_score) + + assert_array_almost_equal(fpr, expected_fpr) + assert_array_almost_equal(fnr, expected_fnr) + + [email protected]("y_true,y_score,expected_fpr,expected_fnr", [ + ([1, 0], [0.5, 0.5], [1], [0]), + ([0, 1], [0.5, 0.5], [1], [0]), + ([0, 0, 1], [0.25, 0.5, 0.5], [0.5], [0]), + ([0, 1, 0], [0.25, 0.5, 0.5], [0.5], [0]), + ([0, 1, 1], [0.25, 0.5, 0.5], [0], [0]), + ([1, 0, 0], [0.25, 0.5, 0.5], [1], [0]), + ([1, 0, 1], [0.25, 0.5, 0.5], [1], [0]), + ([1, 1, 0], [0.25, 0.5, 0.5], [1], [0]), +]) +def test_detection_error_tradeoff_curve_tie_handling(y_true, y_score, + expected_fpr, + expected_fnr): + fpr, fnr, _ = detection_error_tradeoff_curve(y_true, y_score) + + assert_array_almost_equal(fpr, expected_fpr) + assert_array_almost_equal(fnr, expected_fnr) + + +def test_detection_error_tradeoff_curve_sanity_check(): + # Exactly duplicated inputs yield the same result. + assert_array_almost_equal( + detection_error_tradeoff_curve([0, 0, 1], [0, 0.5, 1]), + detection_error_tradeoff_curve( + [0, 0, 0, 0, 1, 1], [0, 0, 0.5, 0.5, 1, 1]) + ) + + [email protected]("y_score", [ + (0), (0.25), (0.5), (0.75), (1) +]) +def test_detection_error_tradeoff_curve_constant_scores(y_score): + fpr, fnr, threshold = detection_error_tradeoff_curve( + y_true=[0, 1, 0, 1, 0, 1], + y_score=np.full(6, y_score) + ) + + assert_array_almost_equal(fpr, [1]) + assert_array_almost_equal(fnr, [0]) + assert_array_almost_equal(threshold, [y_score]) + + [email protected]("y_true", [ + ([0, 0, 0, 0, 0, 1]), + ([0, 0, 0, 0, 1, 1]), + ([0, 0, 0, 1, 1, 1]), + ([0, 0, 1, 1, 1, 1]), + ([0, 1, 1, 1, 1, 1]), +]) +def test_detection_error_tradeoff_curve_perfect_scores(y_true): + fpr, fnr, _ = detection_error_tradeoff_curve( + y_true=y_true, + y_score=y_true + ) + + assert_array_almost_equal(fpr, [0]) + assert_array_almost_equal(fnr, [0]) + + +def test_detection_error_tradeoff_curve_bad_input(): + # input variables with inconsistent numbers of samples + assert_raises(ValueError, detection_error_tradeoff_curve, + [0, 1], [0, 0.5, 1]) + assert_raises(ValueError, detection_error_tradeoff_curve, + [0, 1, 1], [0, 0.5]) + + # When the y_true values are all the same a detection error tradeoff cannot + # be computed. + assert_raises(ValueError, detection_error_tradeoff_curve, + [0, 0, 0], [0, 0.5, 1]) + assert_raises(ValueError, detection_error_tradeoff_curve, + [1, 1, 1], [0, 0.5, 1]) + + def check_lrap_toy(lrap_score): # Check on several small example that it works assert_almost_equal(lrap_score([[0, 1]], [[0.25, 0.75]]), 1)
[ { "path": "doc/modules/classes.rst", "old_path": "a/doc/modules/classes.rst", "new_path": "b/doc/modules/classes.rst", "metadata": "diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst\nindex 2e54d000a13aa..2fd1366e18434 100644\n--- a/doc/modules/classes.rst\n+++ b/doc/modules/classes.rst\n@@ -946,6 +946,7 @@ details.\n metrics.cohen_kappa_score\n metrics.confusion_matrix\n metrics.dcg_score\n+ metrics.detection_error_tradeoff_curve\n metrics.f1_score\n metrics.fbeta_score\n metrics.hamming_loss\n" }, { "path": "doc/modules/model_evaluation.rst", "old_path": "a/doc/modules/model_evaluation.rst", "new_path": "b/doc/modules/model_evaluation.rst", "metadata": "diff --git a/doc/modules/model_evaluation.rst b/doc/modules/model_evaluation.rst\nindex f8874869a0274..decd0f42383eb 100644\n--- a/doc/modules/model_evaluation.rst\n+++ b/doc/modules/model_evaluation.rst\n@@ -306,6 +306,7 @@ Some of these are restricted to the binary classification case:\n \n precision_recall_curve\n roc_curve\n+ detection_error_tradeoff_curve\n \n \n Others also work in the multiclass case:\n@@ -1437,6 +1438,93 @@ to the given limit.\n In Data Mining, 2001.\n Proceedings IEEE International Conference, pp. 131-138.\n \n+.. _det_curve:\n+\n+Detection error tradeoff (DET)\n+------------------------------\n+\n+The function :func:`detection_error_tradeoff_curve` computes the\n+detection error tradeoff curve (DET) curve [WikipediaDET2017]_.\n+Quoting Wikipedia:\n+\n+ \"A detection error tradeoff (DET) graph is a graphical plot of error rates for\n+ binary classification systems, plotting false reject rate vs. false accept\n+ rate. The x- and y-axes are scaled non-linearly by their standard normal\n+ deviates (or just by logarithmic transformation), yielding tradeoff curves\n+ that are more linear than ROC curves, and use most of the image area to\n+ highlight the differences of importance in the critical operating region.\"\n+\n+DET curves are a variation of receiver operating characteristic (ROC) curves\n+where False Negative Rate is plotted on the ordinate instead of True Positive\n+Rate.\n+DET curves are commonly plotted in normal deviate scale by transformation with\n+:math:`\\phi^{-1}` (with :math:`\\phi` being the cumulative distribution\n+function).\n+The resulting performance curves explicitly visualize the tradeoff of error\n+types for given classification algorithms.\n+See [Martin1997]_ for examples and further motivation.\n+\n+This figure compares the ROC and DET curves of two example classifiers on the\n+same classification task:\n+\n+.. image:: ../auto_examples/model_selection/images/sphx_glr_plot_det_001.png\n+ :target: ../auto_examples/model_selection/plot_det.html\n+ :scale: 75\n+ :align: center\n+\n+**Properties:**\n+\n+* DET curves form a linear curve in normal deviate scale if the detection\n+ scores are normally (or close-to normally) distributed.\n+ It was shown by [Navratil2007]_ that the reverse it not necessarily true and even more\n+ general distributions are able produce linear DET curves.\n+\n+* The normal deviate scale transformation spreads out the points such that a\n+ comparatively larger space of plot is occupied.\n+ Therefore curves with similar classification performance might be easier to\n+ distinguish on a DET plot.\n+\n+* With False Negative Rate being \"inverse\" to True Positive Rate the point\n+ of perfection for DET curves is the origin (in contrast to the top left corner\n+ for ROC curves).\n+\n+**Applications and limitations:**\n+\n+DET curves are intuitive to read and hence allow quick visual assessment of a\n+classifier's performance.\n+Additionally DET curves can be consulted for threshold analysis and operating\n+point selection.\n+This is particularly helpful if a comparison of error types is required.\n+\n+One the other hand DET curves do not provide their metric as a single number.\n+Therefore for either automated evaluation or comparison to other\n+classification tasks metrics like the derived area under ROC curve might be\n+better suited.\n+\n+.. topic:: Examples:\n+\n+ * See :ref:`sphx_glr_auto_examples_model_selection_plot_det.py`\n+ for an example comparison between receiver operating characteristic (ROC)\n+ curves and Detection error tradeoff (DET) curves.\n+\n+.. topic:: References:\n+\n+ .. [WikipediaDET2017] Wikipedia contributors. Detection error tradeoff.\n+ Wikipedia, The Free Encyclopedia. September 4, 2017, 23:33 UTC.\n+ Available at: https://en.wikipedia.org/w/index.php?title=Detection_error_tradeoff&oldid=798982054.\n+ Accessed February 19, 2018.\n+\n+ .. [Martin1997] A. Martin, G. Doddington, T. Kamm, M. Ordowski, and M. Przybocki,\n+ `The DET Curve in Assessment of Detection Task Performance\n+ <http://www.dtic.mil/docs/citations/ADA530509>`_,\n+ NIST 1997.\n+\n+ .. [Navratil2007] J. Navractil and D. Klusacek,\n+ \"`On Linear DETs,\n+ <http://www.research.ibm.com/CBG/papers/icassp07_navratil.pdf>`_\"\n+ 2007 IEEE International Conference on Acoustics,\n+ Speech and Signal Processing - ICASSP '07, Honolulu,\n+ HI, 2007, pp. IV-229-IV-232.\n \n .. _zero_one_loss:\n \n" }, { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex cf3347c0ee8cd..ff8149142f3b3 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -212,6 +212,11 @@ Changelog\n :mod:`sklearn.metrics`\n ......................\n \n+- |Feature| Added :func:`metrics.detection_error_tradeoff_curve` to compute\n+ Detection Error Tradeoff curve classification metric.\n+ :pr:`10591` by :user:`Jeremy Karnowski <jkarnows>` and\n+ :user:`Daniel Mohns <dmohns>`.\n+\n - |Feature| Added :func:`metrics.mean_absolute_percentage_error` metric and\n the associated scorer for regression problems. :issue:`10708` fixed with the\n PR :pr:`15007` by :user:`Ashutosh Hathidara <ashutosh1919>`. The scorer and\n" } ]
0.24
0550793bd61b84beb60d3a92c3eb90cc788a27a8
[]
[ "sklearn/metrics/tests/test_common.py::test_single_sample[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[samples_f2_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-Number of given labels, 2, not equal to the number of columns in 'y_score', 3-y_true4-labels4]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[r2_score]", "sklearn/metrics/tests/test_ranking.py::test_detection_error_tradeoff_curve_toydata[y_true7-y_score7-expected_fpr7-expected_fnr7]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_error[Partial AUC computation not available in multiclass setting, 'max_fpr' must be set to `None`, received `max_fpr=0.5` instead-kwargs3]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[hinge_loss]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[dcg_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_recall_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-Parameter 'labels' must be unique-y_true0-labels0]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[samples_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[macro_f1_score]", "sklearn/metrics/tests/test_ranking.py::test_dcg_score", "sklearn/metrics/tests/test_common.py::test_single_sample[r2_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_zeroes[f1_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[f0.5_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric7]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[normalized_confusion_matrix]", "sklearn/metrics/tests/test_ranking.py::test_precision_recall_curve_errors", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[micro_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[max_error]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[coverage_error]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[log_loss]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[weighted_roc_auc]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[dcg_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[metric17]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[matthews_corrcoef_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric19]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[unnormalized_log_loss]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve_hard", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric18]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[metric11]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[roc_auc_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[samples_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_roc_auc]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric20]", "sklearn/metrics/tests/test_ranking.py::test_detection_error_tradeoff_curve_toydata[y_true1-y_score1-expected_fpr1-expected_fnr1]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multiclass[recall_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[weighted_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_averaging_multiclass[f0.5_score]", "sklearn/metrics/tests/test_ranking.py::test_precision_recall_curve_toydata", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[weighted_ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_single_sample[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric32]", "sklearn/metrics/tests/test_ranking.py::test_detection_error_tradeoff_curve_tie_handling[y_true7-y_score7-expected_fpr7-expected_fnr7]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[metric8]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_ones[f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric27]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[partial_roc_auc]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[micro_roc_auc]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[log_loss]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[recall_score]", "sklearn/metrics/tests/test_common.py::test_normalize_option_binary_classification[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[macro_precision_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-Number of given labels, 2, not equal to the number of columns in 'y_score', 3-y_true4-labels4]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[macro_jaccard_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve[False]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[samples_roc_auc]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[f1_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[micro_jaccard_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-Number of classes in y_true not equal to the number of columns in 'y_score'-y_true2-None]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_ovo_roc_auc]", "sklearn/metrics/tests/test_ranking.py::test_detection_error_tradeoff_curve_toydata[y_true19-y_score19-expected_fpr19-expected_fnr19]", "sklearn/metrics/tests/test_ranking.py::test_detection_error_tradeoff_curve_perfect_scores[y_true0]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_zeroes[precision_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric3]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[samples_recall_score]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_normal_deviance]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[mean_absolute_error]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-'y_true' contains labels not in parameter 'labels'-y_true8-labels8]", "sklearn/metrics/tests/test_ranking.py::test_ndcg_toy_examples[True]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[hinge_loss]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-Number of given labels, 2, not equal to the number of columns in 'y_score', 3-y_true5-labels5]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[log_loss]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[detection_error_tradeoff_curve]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[dcg_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[ndcg_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[micro_roc_auc]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve_drop_intermediate", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[samples_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_f1_score]", "sklearn/metrics/tests/test_ranking.py::test_auc", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[samples_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[partial_roc_auc]", "sklearn/metrics/tests/test_ranking.py::test_ndcg_toy_examples[False]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric39]", "sklearn/metrics/tests/test_common.py::test_normalize_option_multilabel_classification", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[weighted_ovo_roc_auc]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[f1_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_error[average must be one of \\\\('macro', 'weighted'\\\\) for multiclass problems-kwargs0]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-5-2]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_single_sample[weighted_f1_score]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovr_roc_auc_toydata[y_true3-labels3]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[weighted_precision_score]", "sklearn/metrics/tests/test_ranking.py::test_label_ranking_avp[label_ranking_average_precision_score-check_lrap_toy]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-10-1]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve_one_label", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[metric29]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[zero_one_loss]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-Parameter 'labels' must be unique-y_true1-labels1]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[hinge_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[macro_jaccard_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_error[average must be one of \\\\('macro', 'weighted'\\\\) for multiclass problems-kwargs1]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric35]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[matthews_corrcoef_score]", "sklearn/metrics/tests/test_ranking.py::test_dcg_ties", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[r2_score]", "sklearn/metrics/tests/test_ranking.py::test_auc_errors", "sklearn/metrics/tests/test_ranking.py::test_detection_error_tradeoff_curve_toydata[y_true11-y_score11-expected_fpr11-expected_fnr11]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[<lambda>]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[max_error]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovr_roc_auc_toydata[y_true2-labels2]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[metric32]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[brier_score_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[samples_recall_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[metric12]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovr_roc_auc_toydata[y_true1-None]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[micro_precision_score]", "sklearn/metrics/tests/test_ranking.py::test_binary_clf_curve_multiclass_error", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[unnormalized_log_loss]", "sklearn/metrics/tests/test_ranking.py::test_detection_error_tradeoff_curve_toydata[y_true16-y_score16-expected_fpr16-expected_fnr16]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[recall_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_ranking.py::test_lrap_error_raised", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance_multilabel_and_multioutput", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_f0.5_score]", "sklearn/metrics/tests/test_ranking.py::test_lrap_sample_weighting_zero_labels", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_single_sample[macro_jaccard_score]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-2-2]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[mean_normal_deviance]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[zero_one_loss]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-Number of classes in y_true not equal to the number of columns in 'y_score'-y_true2-None]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-2-20]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[ndcg_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[hamming_loss]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-10-20]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[r2_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[mean_absolute_error]", "sklearn/metrics/tests/test_ranking.py::test_partial_roc_auc_score", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_f2_score]", "sklearn/metrics/tests/test_ranking.py::test_detection_error_tradeoff_curve_toydata[y_true17-y_score17-expected_fpr17-expected_fnr17]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-5-8]", "sklearn/metrics/tests/test_common.py::test_single_sample[matthews_corrcoef_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[metric13]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[samples_precision_score]", "sklearn/metrics/tests/test_ranking.py::test_average_precision_constant_values", "sklearn/metrics/tests/test_ranking.py::test_detection_error_tradeoff_curve_toydata[y_true15-y_score15-expected_fpr15-expected_fnr15]", "sklearn/metrics/tests/test_common.py::test_single_sample[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[ovr_roc_auc]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-'y_true' contains labels not in parameter 'labels'-y_true9-labels9]", "sklearn/metrics/tests/test_ranking.py::test_detection_error_tradeoff_curve_toydata[y_true10-y_score10-expected_fpr10-expected_fnr10]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric15]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[label_ranking_loss]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_single_sample[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[micro_f0.5_score]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-5-1]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[samples_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[normalized_confusion_matrix]", "sklearn/metrics/tests/test_ranking.py::test_detection_error_tradeoff_curve_toydata[y_true12-y_score12-expected_fpr12-expected_fnr12]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[metric14]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[micro_jaccard_score]", "sklearn/metrics/tests/test_ranking.py::test_detection_error_tradeoff_curve_constant_scores[0.75]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[metric9]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[micro_f0.5_score]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-5-20]", "sklearn/metrics/tests/test_common.py::test_single_sample[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric23]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_ones[f2_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[log_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[label_ranking_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[log_loss]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_symmetry_consistency", "sklearn/metrics/tests/test_common.py::test_single_sample[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[f0.5_score]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovo_roc_auc_toydata[y_true3-None]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[average_precision_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[micro_f2_score]", "sklearn/metrics/tests/test_ranking.py::test_detection_error_tradeoff_curve_toydata[y_true3-y_score3-expected_fpr3-expected_fnr3]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[micro_precision_score]", "sklearn/metrics/tests/test_ranking.py::test_average_precision_score_pos_label_errors", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_compound_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_ranking.py::test_detection_error_tradeoff_curve_toydata[y_true13-y_score13-expected_fpr13-expected_fnr13]", "sklearn/metrics/tests/test_ranking.py::test_detection_error_tradeoff_curve_tie_handling[y_true4-y_score4-expected_fpr4-expected_fnr4]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_zeroes[recall_score]", "sklearn/metrics/tests/test_common.py::test_normalize_option_multiclass_classification[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric38]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[samples_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[matthews_corrcoef_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[average_precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[dcg_score]", "sklearn/metrics/tests/test_ranking.py::test_detection_error_tradeoff_curve_tie_handling[y_true3-y_score3-expected_fpr3-expected_fnr3]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[samples_recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric26]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-Number of given labels, 4, not equal to the number of columns in 'y_score', 3-y_true6-labels6]", "sklearn/metrics/tests/test_ranking.py::test_detection_error_tradeoff_curve_tie_handling[y_true6-y_score6-expected_fpr6-expected_fnr6]", "sklearn/metrics/tests/test_common.py::test_single_sample[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[samples_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[ovo_roc_auc]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[median_absolute_error]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_error[sample_weight is not supported for multiclass one-vs-one ROC AUC, 'sample_weight' must be None in this case-kwargs2]", "sklearn/metrics/tests/test_ranking.py::test_detection_error_tradeoff_curve_toydata[y_true5-y_score5-expected_fpr5-expected_fnr5]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[metric28]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric34]", "sklearn/metrics/tests/test_common.py::test_single_sample[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_single_sample[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric41]", "sklearn/metrics/tests/test_ranking.py::test_detection_error_tradeoff_curve_sanity_check", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_zeroes[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_roc_auc]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_ones[f1_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[samples_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[precision_recall_curve]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-'y_true' contains labels not in parameter 'labels'-y_true8-labels8]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[micro_jaccard_score]", "sklearn/metrics/tests/test_ranking.py::test_detection_error_tradeoff_curve_toydata[y_true0-y_score0-expected_fpr0-expected_fnr0]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[coverage_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[average_precision_score]", "sklearn/metrics/tests/test_ranking.py::test_ndcg_score", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[hinge_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[unnormalized_log_loss]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-Parameter 'labels' must be unique-y_true0-labels0]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[hamming_loss]", "sklearn/metrics/tests/test_ranking.py::test_detection_error_tradeoff_curve_tie_handling[y_true5-y_score5-expected_fpr5-expected_fnr5]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric25]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[precision_recall_curve]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[zero_one_loss]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-2-1]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_jaccard_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-Number of given labels, 4, not equal to the number of columns in 'y_score', 3-y_true7-labels7]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[hinge_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric40]", "sklearn/metrics/tests/test_ranking.py::test_detection_error_tradeoff_curve_tie_handling[y_true0-y_score0-expected_fpr0-expected_fnr0]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[average_precision_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_poisson_deviance]", "sklearn/metrics/tests/test_ranking.py::test_auc_score_non_binary_class", "sklearn/metrics/tests/test_common.py::test_single_sample[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_roc_auc]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_single_sample[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_f1_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multiclass[f2_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[accuracy_score]", "sklearn/metrics/tests/test_ranking.py::test_label_ranking_avp[label_ranking_average_precision_score-check_zero_or_all_relevant_labels]", "sklearn/metrics/tests/test_ranking.py::test_label_ranking_avp[_my_lrap-check_lrap_without_tie_and_increasing_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric29]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[weighted_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[label_ranking_average_precision_score]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovo_roc_auc_toydata_binary[y_true0-labels0]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[brier_score_loss]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[matthews_corrcoef_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[f2_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric10]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[f0.5_score]", "sklearn/metrics/tests/test_ranking.py::test_detection_error_tradeoff_curve_toydata[y_true4-y_score4-expected_fpr4-expected_fnr4]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric37]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[label_ranking_loss]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[samples_roc_auc]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[mean_absolute_error]", "sklearn/metrics/tests/test_ranking.py::test_label_ranking_avp[label_ranking_average_precision_score-check_lrap_only_ties]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[hinge_loss]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_normal_deviance]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-Number of given labels, 2, not equal to the number of columns in 'y_score', 3-y_true5-labels5]", "sklearn/metrics/tests/test_ranking.py::test_detection_error_tradeoff_curve_constant_scores[0]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[metric7]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[weighted_ovo_roc_auc]", "sklearn/metrics/tests/test_ranking.py::test_detection_error_tradeoff_curve_tie_handling[y_true2-y_score2-expected_fpr2-expected_fnr2]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[r2_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[micro_average_precision_score]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovo_roc_auc_toydata_binary[y_true1-labels1]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[mean_compound_poisson_deviance]", "sklearn/metrics/tests/test_ranking.py::test_detection_error_tradeoff_curve_perfect_scores[y_true2]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-2-8]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[average_precision_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[zero_one_loss]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-Parameter 'labels' must be ordered-y_true3-labels3]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[recall_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve_toydata", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[matthews_corrcoef_score]", "sklearn/metrics/tests/test_ranking.py::test_detection_error_tradeoff_curve_perfect_scores[y_true3]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve_multi", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[metric18]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[samples_roc_auc]", "sklearn/metrics/tests/test_common.py::test_averaging_multiclass[precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric30]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[label_ranking_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[hinge_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[coverage_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric31]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[weighted_roc_auc]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[log_loss]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_normal_deviance]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[balanced_accuracy_score]", "sklearn/metrics/tests/test_ranking.py::test_ranking_appropriate_input_shape", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[roc_auc_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[samples_f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[metric16]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[macro_precision_score]", "sklearn/metrics/tests/test_ranking.py::test_detection_error_tradeoff_curve_toydata[y_true9-y_score9-expected_fpr9-expected_fnr9]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[zero_one_loss]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve_confidence", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_compound_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[cohen_kappa_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-Number of given labels, 4, not equal to the number of columns in 'y_score', 3-y_true6-labels6]", "sklearn/metrics/tests/test_common.py::test_averaging_binary_multilabel_all_zeroes", "sklearn/metrics/tests/test_ranking.py::test_label_ranking_loss", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[samples_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_roc_auc]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[weighted_f1_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve[True]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[samples_f2_score]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[r2_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[partial_roc_auc]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[roc_auc_score]", "sklearn/metrics/tests/test_ranking.py::test_coverage_error", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[roc_auc_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-Parameter 'labels' must be unique-y_true1-labels1]", "sklearn/metrics/tests/test_ranking.py::test_label_ranking_avp[_my_lrap-check_lrap_toy]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[max_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[brier_score_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[r2_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[weighted_ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric21]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[micro_f1_score]", "sklearn/metrics/tests/test_ranking.py::test_detection_error_tradeoff_curve_toydata[y_true6-y_score6-expected_fpr6-expected_fnr6]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-10-8]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_precision_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_error[multi_class must be in \\\\('ovo', 'ovr'\\\\)-kwargs5]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[log_loss]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[ovo_roc_auc]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[macro_f2_score]", "sklearn/metrics/tests/test_ranking.py::test_label_ranking_avp[_my_lrap-check_lrap_only_ties]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[micro_recall_score]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovo_roc_auc_toydata[y_true0-labels0]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_ranking.py::test_binary_clf_curve_implicit_pos_label[roc_curve]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_error[multi_class='ovp' is not supported for multiclass ROC AUC, multi_class must be in \\\\('ovo', 'ovr'\\\\)-kwargs4]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[roc_curve]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[ndcg_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_gamma_deviance]", "sklearn/metrics/tests/test_ranking.py::test_detection_error_tradeoff_curve_toydata[y_true18-y_score18-expected_fpr18-expected_fnr18]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[metric10]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[jaccard_score]", "sklearn/metrics/tests/test_ranking.py::test_detection_error_tradeoff_curve_perfect_scores[y_true1]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[log_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[f2_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric2]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_zeroes[f0.5_score]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[partial_roc_auc]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric22]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[samples_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[macro_f1_score]", "sklearn/metrics/tests/test_ranking.py::test_label_ranking_avp[label_ranking_average_precision_score-check_lrap_without_tie_and_increasing_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-'y_true' contains labels not in parameter 'labels'-y_true10-labels10]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_jaccard_score]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-10-2]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_compound_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[macro_recall_score]", "sklearn/metrics/tests/test_ranking.py::test_detection_error_tradeoff_curve_constant_scores[0.25]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[roc_curve]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[average_precision_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[accuracy_score]", "sklearn/metrics/tests/test_ranking.py::test_detection_error_tradeoff_curve_toydata[y_true14-y_score14-expected_fpr14-expected_fnr14]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-'y_true' contains labels not in parameter 'labels'-y_true10-labels10]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_multilabel_representation_invariance", "sklearn/metrics/tests/test_ranking.py::test_detection_error_tradeoff_curve_toydata[y_true2-y_score2-expected_fpr2-expected_fnr2]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_zeroes[f2_score]", "sklearn/metrics/tests/test_ranking.py::test_detection_error_tradeoff_curve_bad_input", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[precision_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[samples_f1_score]", "sklearn/metrics/tests/test_common.py::test_normalize_option_binary_classification[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_ones[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[log_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[cohen_kappa_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-Number of given labels, 4, not equal to the number of columns in 'y_score', 3-y_true7-labels7]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[micro_precision_score]", "sklearn/metrics/tests/test_ranking.py::test_ndcg_ignore_ties_with_k", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[roc_auc_score]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovr_roc_auc_toydata[y_true0-None]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[partial_roc_auc]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[metric3]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_ovo_roc_auc]", "sklearn/metrics/tests/test_ranking.py::test_score_scale_invariance", "sklearn/metrics/tests/test_common.py::test_single_sample[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_f2_score]", "sklearn/metrics/tests/test_ranking.py::test_detection_error_tradeoff_curve_constant_scores[1]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_ones[precision_score]", "sklearn/metrics/tests/test_ranking.py::test_detection_error_tradeoff_curve_perfect_scores[y_true4]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[samples_f1_score]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[micro_recall_score]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovo_roc_auc_toydata[y_true1-None]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[ovo_roc_auc]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_ones[recall_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[r2_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_compound_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_squared_error]", "sklearn/metrics/tests/test_ranking.py::test_ndcg_invariant", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[coverage_error]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[matthews_corrcoef_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric16]", "sklearn/metrics/tests/test_common.py::test_averaging_multiclass[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[hinge_loss]", "sklearn/metrics/tests/test_common.py::test_normalize_option_multiclass_classification[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_normal_deviance]", "sklearn/metrics/tests/test_ranking.py::test_roc_returns_consistency", "sklearn/metrics/tests/test_common.py::test_single_sample[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[label_ranking_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[label_ranking_loss]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_roc_auc]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[log_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric33]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[matthews_corrcoef]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[max_error]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[ovr_roc_auc]", "sklearn/metrics/tests/test_ranking.py::test_ranking_loss_ties_handling", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[r2_score]", "sklearn/metrics/tests/test_ranking.py::test_precision_recall_curve", "sklearn/metrics/tests/test_ranking.py::test_binary_clf_curve_implicit_pos_label[precision_recall_curve]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[samples_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[samples_precision_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_jaccard_score]", "sklearn/metrics/tests/test_ranking.py::test_detection_error_tradeoff_curve_tie_handling[y_true1-y_score1-expected_fpr1-expected_fnr1]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[roc_auc_score]", "sklearn/metrics/tests/test_ranking.py::test_detection_error_tradeoff_curve_constant_scores[0.5]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[samples_f2_score]", "sklearn/metrics/tests/test_common.py::test_no_averaging_labels", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[max_error]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[macro_f1_score]", "sklearn/metrics/tests/test_ranking.py::test_label_ranking_avp[_my_lrap-check_zero_or_all_relevant_labels]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric36]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric28]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[r2_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-'y_true' contains labels not in parameter 'labels'-y_true9-labels9]", "sklearn/metrics/tests/test_common.py::test_single_sample[micro_f0.5_score]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovo_roc_auc_toydata[y_true2-labels2]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[f2_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[macro_f2_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-Parameter 'labels' must be ordered-y_true3-labels3]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_f2_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[median_absolute_error]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve_end_points", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[mean_gamma_deviance]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve_fpr_tpr_increasing", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[ndcg_score]", "sklearn/metrics/tests/test_ranking.py::test_detection_error_tradeoff_curve_toydata[y_true8-y_score8-expected_fpr8-expected_fnr8]", "sklearn/metrics/tests/test_common.py::test_averaging_multiclass[f1_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[ovo_roc_auc]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_ranking.py::test_coverage_tie_handling", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[detection_error_tradeoff_curve]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric24]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[label_ranking_loss]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [ { "type": "file", "name": "examples/model_selection/plot_det.py" } ] }
[ { "path": "doc/modules/classes.rst", "old_path": "a/doc/modules/classes.rst", "new_path": "b/doc/modules/classes.rst", "metadata": "diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst\nindex 2e54d000a13aa..2fd1366e18434 100644\n--- a/doc/modules/classes.rst\n+++ b/doc/modules/classes.rst\n@@ -946,6 +946,7 @@ details.\n metrics.cohen_kappa_score\n metrics.confusion_matrix\n metrics.dcg_score\n+ metrics.detection_error_tradeoff_curve\n metrics.f1_score\n metrics.fbeta_score\n metrics.hamming_loss\n" }, { "path": "doc/modules/model_evaluation.rst", "old_path": "a/doc/modules/model_evaluation.rst", "new_path": "b/doc/modules/model_evaluation.rst", "metadata": "diff --git a/doc/modules/model_evaluation.rst b/doc/modules/model_evaluation.rst\nindex f8874869a0274..decd0f42383eb 100644\n--- a/doc/modules/model_evaluation.rst\n+++ b/doc/modules/model_evaluation.rst\n@@ -306,6 +306,7 @@ Some of these are restricted to the binary classification case:\n \n precision_recall_curve\n roc_curve\n+ detection_error_tradeoff_curve\n \n \n Others also work in the multiclass case:\n@@ -1437,6 +1438,93 @@ to the given limit.\n In Data Mining, 2001.\n Proceedings IEEE International Conference, pp. 131-138.\n \n+.. _det_curve:\n+\n+Detection error tradeoff (DET)\n+------------------------------\n+\n+The function :func:`detection_error_tradeoff_curve` computes the\n+detection error tradeoff curve (DET) curve [WikipediaDET2017]_.\n+Quoting Wikipedia:\n+\n+ \"A detection error tradeoff (DET) graph is a graphical plot of error rates for\n+ binary classification systems, plotting false reject rate vs. false accept\n+ rate. The x- and y-axes are scaled non-linearly by their standard normal\n+ deviates (or just by logarithmic transformation), yielding tradeoff curves\n+ that are more linear than ROC curves, and use most of the image area to\n+ highlight the differences of importance in the critical operating region.\"\n+\n+DET curves are a variation of receiver operating characteristic (ROC) curves\n+where False Negative Rate is plotted on the ordinate instead of True Positive\n+Rate.\n+DET curves are commonly plotted in normal deviate scale by transformation with\n+:math:`\\phi^{-1}` (with :math:`\\phi` being the cumulative distribution\n+function).\n+The resulting performance curves explicitly visualize the tradeoff of error\n+types for given classification algorithms.\n+See [Martin1997]_ for examples and further motivation.\n+\n+This figure compares the ROC and DET curves of two example classifiers on the\n+same classification task:\n+\n+.. image:: ../auto_examples/model_selection/images/sphx_glr_plot_det_001.png\n+ :target: ../auto_examples/model_selection/plot_det.html\n+ :scale: 75\n+ :align: center\n+\n+**Properties:**\n+\n+* DET curves form a linear curve in normal deviate scale if the detection\n+ scores are normally (or close-to normally) distributed.\n+ It was shown by [Navratil2007]_ that the reverse it not necessarily true and even more\n+ general distributions are able produce linear DET curves.\n+\n+* The normal deviate scale transformation spreads out the points such that a\n+ comparatively larger space of plot is occupied.\n+ Therefore curves with similar classification performance might be easier to\n+ distinguish on a DET plot.\n+\n+* With False Negative Rate being \"inverse\" to True Positive Rate the point\n+ of perfection for DET curves is the origin (in contrast to the top left corner\n+ for ROC curves).\n+\n+**Applications and limitations:**\n+\n+DET curves are intuitive to read and hence allow quick visual assessment of a\n+classifier's performance.\n+Additionally DET curves can be consulted for threshold analysis and operating\n+point selection.\n+This is particularly helpful if a comparison of error types is required.\n+\n+One the other hand DET curves do not provide their metric as a single number.\n+Therefore for either automated evaluation or comparison to other\n+classification tasks metrics like the derived area under ROC curve might be\n+better suited.\n+\n+.. topic:: Examples:\n+\n+ * See :ref:`sphx_glr_auto_examples_model_selection_plot_det.py`\n+ for an example comparison between receiver operating characteristic (ROC)\n+ curves and Detection error tradeoff (DET) curves.\n+\n+.. topic:: References:\n+\n+ .. [WikipediaDET2017] Wikipedia contributors. Detection error tradeoff.\n+ Wikipedia, The Free Encyclopedia. September 4, 2017, 23:33 UTC.\n+ Available at: https://en.wikipedia.org/w/index.php?title=Detection_error_tradeoff&oldid=798982054.\n+ Accessed February 19, 2018.\n+\n+ .. [Martin1997] A. Martin, G. Doddington, T. Kamm, M. Ordowski, and M. Przybocki,\n+ `The DET Curve in Assessment of Detection Task Performance\n+ <http://www.dtic.mil/docs/citations/ADA530509>`_,\n+ NIST 1997.\n+\n+ .. [Navratil2007] J. Navractil and D. Klusacek,\n+ \"`On Linear DETs,\n+ <http://www.research.ibm.com/CBG/papers/icassp07_navratil.pdf>`_\"\n+ 2007 IEEE International Conference on Acoustics,\n+ Speech and Signal Processing - ICASSP '07, Honolulu,\n+ HI, 2007, pp. IV-229-IV-232.\n \n .. _zero_one_loss:\n \n" }, { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex cf3347c0ee8cd..ff8149142f3b3 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -212,6 +212,11 @@ Changelog\n :mod:`sklearn.metrics`\n ......................\n \n+- |Feature| Added :func:`metrics.detection_error_tradeoff_curve` to compute\n+ Detection Error Tradeoff curve classification metric.\n+ :pr:`<PRID>` by :user:`<NAME>` and\n+ :user:`<NAME>`.\n+\n - |Feature| Added :func:`metrics.mean_absolute_percentage_error` metric and\n the associated scorer for regression problems. :issue:`<PRID>` fixed with the\n PR :pr:`<PRID>` by :user:`<NAME>`. The scorer and\n" } ]
diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst index 2e54d000a13aa..2fd1366e18434 100644 --- a/doc/modules/classes.rst +++ b/doc/modules/classes.rst @@ -946,6 +946,7 @@ details. metrics.cohen_kappa_score metrics.confusion_matrix metrics.dcg_score + metrics.detection_error_tradeoff_curve metrics.f1_score metrics.fbeta_score metrics.hamming_loss diff --git a/doc/modules/model_evaluation.rst b/doc/modules/model_evaluation.rst index f8874869a0274..decd0f42383eb 100644 --- a/doc/modules/model_evaluation.rst +++ b/doc/modules/model_evaluation.rst @@ -306,6 +306,7 @@ Some of these are restricted to the binary classification case: precision_recall_curve roc_curve + detection_error_tradeoff_curve Others also work in the multiclass case: @@ -1437,6 +1438,93 @@ to the given limit. In Data Mining, 2001. Proceedings IEEE International Conference, pp. 131-138. +.. _det_curve: + +Detection error tradeoff (DET) +------------------------------ + +The function :func:`detection_error_tradeoff_curve` computes the +detection error tradeoff curve (DET) curve [WikipediaDET2017]_. +Quoting Wikipedia: + + "A detection error tradeoff (DET) graph is a graphical plot of error rates for + binary classification systems, plotting false reject rate vs. false accept + rate. The x- and y-axes are scaled non-linearly by their standard normal + deviates (or just by logarithmic transformation), yielding tradeoff curves + that are more linear than ROC curves, and use most of the image area to + highlight the differences of importance in the critical operating region." + +DET curves are a variation of receiver operating characteristic (ROC) curves +where False Negative Rate is plotted on the ordinate instead of True Positive +Rate. +DET curves are commonly plotted in normal deviate scale by transformation with +:math:`\phi^{-1}` (with :math:`\phi` being the cumulative distribution +function). +The resulting performance curves explicitly visualize the tradeoff of error +types for given classification algorithms. +See [Martin1997]_ for examples and further motivation. + +This figure compares the ROC and DET curves of two example classifiers on the +same classification task: + +.. image:: ../auto_examples/model_selection/images/sphx_glr_plot_det_001.png + :target: ../auto_examples/model_selection/plot_det.html + :scale: 75 + :align: center + +**Properties:** + +* DET curves form a linear curve in normal deviate scale if the detection + scores are normally (or close-to normally) distributed. + It was shown by [Navratil2007]_ that the reverse it not necessarily true and even more + general distributions are able produce linear DET curves. + +* The normal deviate scale transformation spreads out the points such that a + comparatively larger space of plot is occupied. + Therefore curves with similar classification performance might be easier to + distinguish on a DET plot. + +* With False Negative Rate being "inverse" to True Positive Rate the point + of perfection for DET curves is the origin (in contrast to the top left corner + for ROC curves). + +**Applications and limitations:** + +DET curves are intuitive to read and hence allow quick visual assessment of a +classifier's performance. +Additionally DET curves can be consulted for threshold analysis and operating +point selection. +This is particularly helpful if a comparison of error types is required. + +One the other hand DET curves do not provide their metric as a single number. +Therefore for either automated evaluation or comparison to other +classification tasks metrics like the derived area under ROC curve might be +better suited. + +.. topic:: Examples: + + * See :ref:`sphx_glr_auto_examples_model_selection_plot_det.py` + for an example comparison between receiver operating characteristic (ROC) + curves and Detection error tradeoff (DET) curves. + +.. topic:: References: + + .. [WikipediaDET2017] Wikipedia contributors. Detection error tradeoff. + Wikipedia, The Free Encyclopedia. September 4, 2017, 23:33 UTC. + Available at: https://en.wikipedia.org/w/index.php?title=Detection_error_tradeoff&oldid=798982054. + Accessed February 19, 2018. + + .. [Martin1997] A. Martin, G. Doddington, T. Kamm, M. Ordowski, and M. Przybocki, + `The DET Curve in Assessment of Detection Task Performance + <http://www.dtic.mil/docs/citations/ADA530509>`_, + NIST 1997. + + .. [Navratil2007] J. Navractil and D. Klusacek, + "`On Linear DETs, + <http://www.research.ibm.com/CBG/papers/icassp07_navratil.pdf>`_" + 2007 IEEE International Conference on Acoustics, + Speech and Signal Processing - ICASSP '07, Honolulu, + HI, 2007, pp. IV-229-IV-232. .. _zero_one_loss: diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index cf3347c0ee8cd..ff8149142f3b3 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -212,6 +212,11 @@ Changelog :mod:`sklearn.metrics` ...................... +- |Feature| Added :func:`metrics.detection_error_tradeoff_curve` to compute + Detection Error Tradeoff curve classification metric. + :pr:`<PRID>` by :user:`<NAME>` and + :user:`<NAME>`. + - |Feature| Added :func:`metrics.mean_absolute_percentage_error` metric and the associated scorer for regression problems. :issue:`<PRID>` fixed with the PR :pr:`<PRID>` by :user:`<NAME>`. The scorer and If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names: [{'type': 'file', 'name': 'examples/model_selection/plot_det.py'}]
scikit-learn/scikit-learn
scikit-learn__scikit-learn-16625
https://github.com/scikit-learn/scikit-learn/pull/16625
diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst index e05d08781181f..6dbab18d94a0c 100644 --- a/doc/modules/classes.rst +++ b/doc/modules/classes.rst @@ -966,6 +966,7 @@ details. metrics.recall_score metrics.roc_auc_score metrics.roc_curve + metrics.top_k_accuracy_score metrics.zero_one_loss Regression metrics diff --git a/doc/modules/model_evaluation.rst b/doc/modules/model_evaluation.rst index 05750222ad0ca..96fe4d396dc5d 100644 --- a/doc/modules/model_evaluation.rst +++ b/doc/modules/model_evaluation.rst @@ -60,6 +60,7 @@ Scoring Function **Classification** 'accuracy' :func:`metrics.accuracy_score` 'balanced_accuracy' :func:`metrics.balanced_accuracy_score` +'top_k_accuracy' :func:`metrics.top_k_accuracy_score` 'average_precision' :func:`metrics.average_precision_score` 'neg_brier_score' :func:`metrics.brier_score_loss` 'f1' :func:`metrics.f1_score` for binary targets @@ -318,6 +319,7 @@ Others also work in the multiclass case: hinge_loss matthews_corrcoef roc_auc_score + top_k_accuracy_score Some also work in the multilabel case: @@ -438,6 +440,44 @@ In the multilabel case with binary label indicators:: for an example of accuracy score usage using permutations of the dataset. +.. _top_k_accuracy_score: + +Top-k accuracy score +-------------------- + +The :func:`top_k_accuracy_score` function is a generalization of +:func:`accuracy_score`. The difference is that a prediction is considered +correct as long as the true label is associated with one of the ``k`` highest +predicted scores. :func:`accuracy_score` is the special case of `k = 1`. + +The function covers the binary and multiclass classification cases but not the +multilabel case. + +If :math:`\hat{f}_{i,j}` is the predicted class for the :math:`i`-th sample +corresponding to the :math:`j`-th largest predicted score and :math:`y_i` is the +corresponding true value, then the fraction of correct predictions over +:math:`n_\text{samples}` is defined as + +.. math:: + + \texttt{top-k accuracy}(y, \hat{f}) = \frac{1}{n_\text{samples}} \sum_{i=0}^{n_\text{samples}-1} \sum_{j=1}^{k} 1(\hat{f}_{i,j} = y_i) + +where :math:`k` is the number of guesses allowed and :math:`1(x)` is the +`indicator function <https://en.wikipedia.org/wiki/Indicator_function>`_. + + >>> import numpy as np + >>> from sklearn.metrics import top_k_accuracy_score + >>> y_true = np.array([0, 1, 2, 2]) + >>> y_score = np.array([[0.5, 0.2, 0.2], + ... [0.3, 0.4, 0.2], + ... [0.2, 0.4, 0.3], + ... [0.7, 0.2, 0.1]]) + >>> top_k_accuracy_score(y_true, y_score, k=2) + 0.75 + >>> # Not normalizing gives the number of "correctly" classified samples + >>> top_k_accuracy_score(y_true, y_score, k=2, normalize=False) + 3 + .. _balanced_accuracy_score: Balanced accuracy score diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index bd7f368b023a9..68f6addbcad94 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -157,6 +157,10 @@ Changelog :pr:`18280` by :user:`Alex Liang <tianchuliang>` and `Guillaume Lemaitre`_. +- |Feature| :func:`datasets.fetch_openml` now validates md5checksum of arff + files downloaded or cached to ensure data integrity. + :pr:`14800` by :user:`Shashank Singh <shashanksingh28>` and `Joel Nothman`_. + - |API| The default value of `as_frame` in :func:`datasets.fetch_openml` is changed from False to 'auto'. :pr:`17610` by :user:`Jiaxiang <fujiaxiang>`. @@ -378,11 +382,18 @@ Changelog :mod:`sklearn.metrics` ...................... +- |Feature| new metric :func:`metrics.top_k_accuracy_score`. It's a + generalization of :func:`metrics.top_k_accuracy_score`, the difference is + that a prediction is considered correct as long as the true label is + associated with one of the `k` highest predicted scores. + :func:`accuracy_score` is the special case of `k = 1`. + :pr:`16625` by :user:`Geoffrey Bolmier <gbolmier>`. + - |Feature| Added :func:`metrics.det_curve` to compute Detection Error Tradeoff curve classification metric. :pr:`10591` by :user:`Jeremy Karnowski <jkarnows>` and :user:`Daniel Mohns <dmohns>`. - + - |Feature| Added :func:`metrics.plot_det_curve` and :class:`metrics.DetCurveDisplay` to ease the plot of DET curves. :pr:`18176` by :user:`Guillaume Lemaitre <glemaitre>`. @@ -406,6 +417,10 @@ Changelog class to be used when computing the precision and recall statistics. :pr:`17569` by :user:`Guillaume Lemaitre <glemaitre>`. +- |Feature| :func:`metrics.plot_confusion_matrix` now supports making colorbar + optional in the matplotlib plot by setting colorbar=False. :pr:`17192` by + :user:`Avi Gupta <avigupta2612>` + - |Enhancement| Add `pos_label` parameter in :func:`metrics.plot_roc_curve` in order to specify the positive class to be used when computing the roc auc statistics. diff --git a/sklearn/metrics/__init__.py b/sklearn/metrics/__init__.py index a8beea4f8c2f9..ebe9affb5e3e3 100644 --- a/sklearn/metrics/__init__.py +++ b/sklearn/metrics/__init__.py @@ -15,6 +15,7 @@ from ._ranking import precision_recall_curve from ._ranking import roc_auc_score from ._ranking import roc_curve +from ._ranking import top_k_accuracy_score from ._classification import accuracy_score from ._classification import balanced_accuracy_score @@ -160,6 +161,7 @@ 'SCORERS', 'silhouette_samples', 'silhouette_score', + 'top_k_accuracy_score', 'v_measure_score', 'zero_one_loss', 'brier_score_loss', diff --git a/sklearn/metrics/_ranking.py b/sklearn/metrics/_ranking.py index b9e693b1e0905..1687d693e7ee0 100644 --- a/sklearn/metrics/_ranking.py +++ b/sklearn/metrics/_ranking.py @@ -1567,3 +1567,151 @@ def ndcg_score(y_true, y_score, *, k=None, sample_weight=None, _check_dcg_target_type(y_true) gain = _ndcg_sample_scores(y_true, y_score, k=k, ignore_ties=ignore_ties) return np.average(gain, weights=sample_weight) + + +def top_k_accuracy_score(y_true, y_score, *, k=2, normalize=True, + sample_weight=None, labels=None): + """Top-k Accuracy classification score. + + This metric computes the number of times where the correct label is among + the top `k` labels predicted (ranked by predicted scores). Note that the + multilabel case isn't covered here. + + Read more in the :ref:`User Guide <top_k_accuracy_score>` + + Parameters + ---------- + y_true : array-like of shape (n_samples,) + True labels. + + y_score : array-like of shape (n_samples,) or (n_samples, n_classes) + Target scores. These can be either probability estimates or + non-thresholded decision values (as returned by + :term:`decision_function` on some classifiers). The binary case expects + scores with shape (n_samples,) while the multiclass case expects scores + with shape (n_samples, n_classes). In the nulticlass case, the order of + the class scores must correspond to the order of ``labels``, if + provided, or else to the numerical or lexicographical order of the + labels in ``y_true``. + + k : int, default=2 + Number of most likely outcomes considered to find the correct label. + + normalize : bool, default=True + If `True`, return the fraction of correctly classified samples. + Otherwise, return the number of correctly classified samples. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. If `None`, all samples are given the same weight. + + labels : array-like of shape (n_classes,), default=None + Multiclass only. List of labels that index the classes in ``y_score``. + If ``None``, the numerical or lexicographical order of the labels in + ``y_true`` is used. + + Returns + ------- + score : float + The top-k accuracy score. The best performance is 1 with + `normalize == True` and the number of samples with + `normalize == False`. + + See also + -------- + accuracy_score + + Notes + ----- + In cases where two or more labels are assigned equal predicted scores, + the labels with the highest indices will be chosen first. This might + impact the result if the correct label falls after the threshold because + of that. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.metrics import top_k_accuracy_score + >>> y_true = np.array([0, 1, 2, 2]) + >>> y_score = np.array([[0.5, 0.2, 0.2], # 0 is in top 2 + ... [0.3, 0.4, 0.2], # 1 is in top 2 + ... [0.2, 0.4, 0.3], # 2 is in top 2 + ... [0.7, 0.2, 0.1]]) # 2 isn't in top 2 + >>> top_k_accuracy_score(y_true, y_score, k=2) + 0.75 + >>> # Not normalizing gives the number of "correctly" classified samples + >>> top_k_accuracy_score(y_true, y_score, k=2, normalize=False) + 3 + + """ + y_true = check_array(y_true, ensure_2d=False, dtype=None) + y_true = column_or_1d(y_true) + y_type = type_of_target(y_true) + y_score = check_array(y_score, ensure_2d=False) + y_score = column_or_1d(y_score) if y_type == 'binary' else y_score + check_consistent_length(y_true, y_score, sample_weight) + + if y_type not in {'binary', 'multiclass'}: + raise ValueError( + f"y type must be 'binary' or 'multiclass', got '{y_type}' instead." + ) + + y_score_n_classes = y_score.shape[1] if y_score.ndim == 2 else 2 + + if labels is None: + classes = _unique(y_true) + n_classes = len(classes) + + if n_classes != y_score_n_classes: + raise ValueError( + f"Number of classes in 'y_true' ({n_classes}) not equal " + f"to the number of classes in 'y_score' ({y_score_n_classes})." + ) + else: + labels = column_or_1d(labels) + classes = _unique(labels) + n_labels = len(labels) + n_classes = len(classes) + + if n_classes != n_labels: + raise ValueError("Parameter 'labels' must be unique.") + + if not np.array_equal(classes, labels): + raise ValueError("Parameter 'labels' must be ordered.") + + if n_classes != y_score_n_classes: + raise ValueError( + f"Number of given labels ({n_classes}) not equal to the " + f"number of classes in 'y_score' ({y_score_n_classes})." + ) + + if len(np.setdiff1d(y_true, classes)): + raise ValueError( + "'y_true' contains labels not in parameter 'labels'." + ) + + if k >= n_classes: + warnings.warn( + f"'k' ({k}) greater than or equal to 'n_classes' ({n_classes}) " + "will result in a perfect score and is therefore meaningless.", + UndefinedMetricWarning + ) + + y_true_encoded = _encode(y_true, uniques=classes) + + if y_type == 'binary': + if k == 1: + threshold = .5 if y_score.min() >= 0 and y_score.max() <= 1 else 0 + y_pred = (y_score > threshold).astype(np.int) + hits = y_pred == y_true_encoded + else: + hits = np.ones_like(y_score, dtype=np.bool_) + elif y_type == 'multiclass': + sorted_pred = np.argsort(y_score, axis=1, kind='mergesort')[:, ::-1] + hits = (y_true_encoded == sorted_pred[:, :k].T).any(axis=0) + + if normalize: + return np.average(hits, weights=sample_weight) + elif sample_weight is None: + return np.sum(hits) + else: + return np.dot(hits, sample_weight) diff --git a/sklearn/metrics/_scorer.py b/sklearn/metrics/_scorer.py index 1010480495982..170e85d78f02f 100644 --- a/sklearn/metrics/_scorer.py +++ b/sklearn/metrics/_scorer.py @@ -27,9 +27,9 @@ from . import (r2_score, median_absolute_error, max_error, mean_absolute_error, mean_squared_error, mean_squared_log_error, mean_poisson_deviance, mean_gamma_deviance, accuracy_score, - f1_score, roc_auc_score, average_precision_score, - precision_score, recall_score, log_loss, - balanced_accuracy_score, explained_variance_score, + top_k_accuracy_score, f1_score, roc_auc_score, + average_precision_score, precision_score, recall_score, + log_loss, balanced_accuracy_score, explained_variance_score, brier_score_loss, jaccard_score, mean_absolute_percentage_error) from .cluster import adjusted_rand_score @@ -653,6 +653,9 @@ def make_scorer(score_func, *, greater_is_better=True, needs_proba=False, balanced_accuracy_scorer = make_scorer(balanced_accuracy_score) # Score functions that need decision values +top_k_accuracy_scorer = make_scorer(top_k_accuracy_score, + greater_is_better=True, + needs_threshold=True) roc_auc_scorer = make_scorer(roc_auc_score, greater_is_better=True, needs_threshold=True) average_precision_scorer = make_scorer(average_precision_score, @@ -701,7 +704,9 @@ def make_scorer(score_func, *, greater_is_better=True, needs_proba=False, neg_root_mean_squared_error=neg_root_mean_squared_error_scorer, neg_mean_poisson_deviance=neg_mean_poisson_deviance_scorer, neg_mean_gamma_deviance=neg_mean_gamma_deviance_scorer, - accuracy=accuracy_scorer, roc_auc=roc_auc_scorer, + accuracy=accuracy_scorer, + top_k_accuracy=top_k_accuracy_scorer, + roc_auc=roc_auc_scorer, roc_auc_ovr=roc_auc_ovr_scorer, roc_auc_ovo=roc_auc_ovo_scorer, roc_auc_ovr_weighted=roc_auc_ovr_weighted_scorer,
diff --git a/sklearn/metrics/tests/test_common.py b/sklearn/metrics/tests/test_common.py index e503a64a47769..6688ddc2aa834 100644 --- a/sklearn/metrics/tests/test_common.py +++ b/sklearn/metrics/tests/test_common.py @@ -59,6 +59,7 @@ from sklearn.metrics import zero_one_loss from sklearn.metrics import ndcg_score from sklearn.metrics import dcg_score +from sklearn.metrics import top_k_accuracy_score from sklearn.metrics._base import _average_binary_score @@ -243,7 +244,9 @@ def precision_recall_curve_padded_thresholds(*args, **kwargs): "label_ranking_average_precision_score": label_ranking_average_precision_score, "ndcg_score": ndcg_score, - "dcg_score": dcg_score + "dcg_score": dcg_score, + + "top_k_accuracy_score": top_k_accuracy_score } ALL_METRICS = dict() @@ -383,6 +386,7 @@ def precision_recall_curve_padded_thresholds(*args, **kwargs): # Metrics with a "normalize" option METRICS_WITH_NORMALIZE_OPTION = { "accuracy_score", + "top_k_accuracy_score", "zero_one_loss", } @@ -573,6 +577,7 @@ def test_sample_order_invariance(name): random_state = check_random_state(0) y_true = random_state.randint(0, 2, size=(20, )) y_pred = random_state.randint(0, 2, size=(20, )) + if name in METRICS_REQUIRE_POSITIVE_Y: y_true, y_pred = _require_positive_targets(y_true, y_pred) @@ -961,41 +966,59 @@ def test_raise_value_error_multilabel_sequences(name): @pytest.mark.parametrize('name', sorted(METRICS_WITH_NORMALIZE_OPTION)) def test_normalize_option_binary_classification(name): # Test in the binary case + n_classes = 2 n_samples = 20 random_state = check_random_state(0) - y_true = random_state.randint(0, 2, size=(n_samples, )) - y_pred = random_state.randint(0, 2, size=(n_samples, )) + + y_true = random_state.randint(0, n_classes, size=(n_samples, )) + y_pred = random_state.randint(0, n_classes, size=(n_samples, )) + y_score = random_state.normal(size=y_true.shape) metrics = ALL_METRICS[name] - measure = metrics(y_true, y_pred, normalize=True) - assert_array_less(-1.0 * measure, 0, + pred = y_score if name in THRESHOLDED_METRICS else y_pred + measure_normalized = metrics(y_true, pred, normalize=True) + measure_not_normalized = metrics(y_true, pred, normalize=False) + + assert_array_less(-1.0 * measure_normalized, 0, err_msg="We failed to test correctly the normalize " "option") - assert_allclose(metrics(y_true, y_pred, normalize=False) / n_samples, - measure) + + assert_allclose(measure_normalized, measure_not_normalized / n_samples, + err_msg=f"Failed with {name}") @pytest.mark.parametrize('name', sorted(METRICS_WITH_NORMALIZE_OPTION)) def test_normalize_option_multiclass_classification(name): # Test in the multiclass case + n_classes = 4 + n_samples = 20 random_state = check_random_state(0) - y_true = random_state.randint(0, 4, size=(20, )) - y_pred = random_state.randint(0, 4, size=(20, )) - n_samples = y_true.shape[0] + + y_true = random_state.randint(0, n_classes, size=(n_samples, )) + y_pred = random_state.randint(0, n_classes, size=(n_samples, )) + y_score = random_state.uniform(size=(n_samples, n_classes)) metrics = ALL_METRICS[name] - measure = metrics(y_true, y_pred, normalize=True) - assert_array_less(-1.0 * measure, 0, + pred = y_score if name in THRESHOLDED_METRICS else y_pred + measure_normalized = metrics(y_true, pred, normalize=True) + measure_not_normalized = metrics(y_true, pred, normalize=False) + + assert_array_less(-1.0 * measure_normalized, 0, err_msg="We failed to test correctly the normalize " "option") - assert_allclose(metrics(y_true, y_pred, normalize=False) / n_samples, - measure) + assert_allclose(measure_normalized, measure_not_normalized / n_samples, + err_msg=f"Failed with {name}") -def test_normalize_option_multilabel_classification(): + [email protected]('name', sorted( + METRICS_WITH_NORMALIZE_OPTION.intersection(MULTILABELS_METRICS) +)) +def test_normalize_option_multilabel_classification(name): # Test in the multilabel case n_classes = 4 n_samples = 100 + random_state = check_random_state(0) # for both random_state 0 and 1, y_true and y_pred has at least one # unlabelled entry @@ -1010,18 +1033,23 @@ def test_normalize_option_multilabel_classification(): allow_unlabeled=True, n_samples=n_samples) + y_score = random_state.uniform(size=y_true.shape) + # To make sure at least one empty label is present y_true += [0]*n_classes y_pred += [0]*n_classes - for name in METRICS_WITH_NORMALIZE_OPTION: - metrics = ALL_METRICS[name] - measure = metrics(y_true, y_pred, normalize=True) - assert_array_less(-1.0 * measure, 0, - err_msg="We failed to test correctly the normalize " - "option") - assert_allclose(metrics(y_true, y_pred, normalize=False) / n_samples, - measure, err_msg="Failed with %s" % name) + metrics = ALL_METRICS[name] + pred = y_score if name in THRESHOLDED_METRICS else y_pred + measure_normalized = metrics(y_true, pred, normalize=True) + measure_not_normalized = metrics(y_true, pred, normalize=False) + + assert_array_less(-1.0 * measure_normalized, 0, + err_msg="We failed to test correctly the normalize " + "option") + + assert_allclose(measure_normalized, measure_not_normalized / n_samples, + err_msg=f"Failed with {name}") @ignore_warnings @@ -1160,6 +1188,10 @@ def check_sample_weight_invariance(name, metric, y1, y2): rng = np.random.RandomState(0) sample_weight = rng.randint(1, 10, size=len(y1)) + # top_k_accuracy_score always lead to a perfect score for k > 1 in the + # binary case + metric = partial(metric, k=1) if name == "top_k_accuracy_score" else metric + # check that unit weights gives the same score as no weight unweighted_score = metric(y1, y2, sample_weight=None) diff --git a/sklearn/metrics/tests/test_ranking.py b/sklearn/metrics/tests/test_ranking.py index 9637162142b2c..db8a50f7d27a8 100644 --- a/sklearn/metrics/tests/test_ranking.py +++ b/sklearn/metrics/tests/test_ranking.py @@ -19,6 +19,7 @@ from sklearn.utils._testing import assert_array_almost_equal from sklearn.utils._testing import assert_warns +from sklearn.metrics import accuracy_score from sklearn.metrics import auc from sklearn.metrics import average_precision_score from sklearn.metrics import coverage_error @@ -30,8 +31,11 @@ from sklearn.metrics import roc_curve from sklearn.metrics._ranking import _ndcg_sample_scores, _dcg_sample_scores from sklearn.metrics import ndcg_score, dcg_score +from sklearn.metrics import top_k_accuracy_score from sklearn.exceptions import UndefinedMetricWarning +from sklearn.model_selection import train_test_split +from sklearn.linear_model import LogisticRegression ############################################################################### @@ -1608,3 +1612,136 @@ def test_partial_roc_auc_score(): assert_almost_equal( roc_auc_score(y_true, y_pred, max_fpr=max_fpr), _partial_roc_auc_score(y_true, y_pred, max_fpr)) + + [email protected]('y_true, k, true_score', [ + ([0, 1, 2, 3], 1, 0.25), + ([0, 1, 2, 3], 2, 0.5), + ([0, 1, 2, 3], 3, 0.75), +]) +def test_top_k_accuracy_score(y_true, k, true_score): + y_score = np.array([ + [0.4, 0.3, 0.2, 0.1], + [0.1, 0.3, 0.4, 0.2], + [0.4, 0.1, 0.2, 0.3], + [0.3, 0.2, 0.4, 0.1], + ]) + score = top_k_accuracy_score(y_true, y_score, k=k) + assert score == pytest.approx(true_score) + + [email protected]('y_score, k, true_score', [ + (np.array([-1, -1, 1, 1]), 1, 1), + (np.array([-1, 1, -1, 1]), 1, 0.5), + (np.array([-1, 1, -1, 1]), 2, 1), + (np.array([.2, .2, .7, .7]), 1, 1), + (np.array([.2, .7, .2, .7]), 1, 0.5), + (np.array([.2, .7, .2, .7]), 2, 1), +]) +def test_top_k_accuracy_score_binary(y_score, k, true_score): + y_true = [0, 0, 1, 1] + + threshold = .5 if y_score.min() >= 0 and y_score.max() <= 1 else 0 + y_pred = (y_score > threshold).astype(np.int) if k == 1 else y_true + + score = top_k_accuracy_score(y_true, y_score, k=k) + score_acc = accuracy_score(y_true, y_pred) + + assert score == score_acc == pytest.approx(true_score) + + +def test_top_k_accuracy_score_increasing(): + # Make sure increasing k leads to a higher score + X, y = datasets.make_classification(n_classes=10, n_samples=1000, + n_informative=10, random_state=0) + + X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) + + clf = LogisticRegression(random_state=0) + clf.fit(X_train, y_train) + + for X, y in zip((X_train, X_test), (y_train, y_test)): + scores = [ + top_k_accuracy_score(y, clf.predict_proba(X), k=k) + for k in range(2, 10) + ] + + assert np.all(np.diff(scores) > 0) + + [email protected]('y_true, k, true_score', [ + ([0, 1, 2, 3], 1, 0.25), + ([0, 1, 2, 3], 2, 0.5), + ([0, 1, 2, 3], 3, 1), +]) +def test_top_k_accuracy_score_ties(y_true, k, true_score): + # Make sure highest indices labels are chosen first in case of ties + y_score = np.array([ + [5, 5, 7, 0], + [1, 5, 5, 5], + [0, 0, 3, 3], + [1, 1, 1, 1], + ]) + assert top_k_accuracy_score(y_true, y_score, + k=k) == pytest.approx(true_score) + + [email protected]('y_true, k', [ + ([0, 1, 2, 3], 4), + ([0, 1, 2, 3], 5), +]) +def test_top_k_accuracy_score_warning(y_true, k): + y_score = np.array([ + [0.4, 0.3, 0.2, 0.1], + [0.1, 0.4, 0.3, 0.2], + [0.2, 0.1, 0.4, 0.3], + [0.3, 0.2, 0.1, 0.4], + ]) + w = UndefinedMetricWarning + score = assert_warns(w, top_k_accuracy_score, y_true, y_score, k=k) + assert score == 1 + + [email protected]('y_true, labels, msg', [ + ( + [0, .57, 1, 2], + None, + "y type must be 'binary' or 'multiclass', got 'continuous'" + ), + ( + [0, 1, 2, 3], + None, + r"Number of classes in 'y_true' \(4\) not equal to the number of " + r"classes in 'y_score' \(3\)." + ), + ( + ['c', 'c', 'a', 'b'], + ['a', 'b', 'c', 'c'], + "Parameter 'labels' must be unique." + ), + ( + ['c', 'c', 'a', 'b'], + ['a', 'c', 'b'], + "Parameter 'labels' must be ordered." + ), + ( + [0, 0, 1, 2], + [0, 1, 2, 3], + r"Number of given labels \(4\) not equal to the number of classes in " + r"'y_score' \(3\)." + ), + ( + [0, 0, 1, 2], + [0, 1, 3], + "'y_true' contains labels not in parameter 'labels'." + ), +]) +def test_top_k_accuracy_score_error(y_true, labels, msg): + y_score = np.array([ + [0.2, 0.1, 0.7], + [0.4, 0.3, 0.3], + [0.3, 0.4, 0.3], + [0.4, 0.5, 0.1], + ]) + with pytest.raises(ValueError, match=msg): + top_k_accuracy_score(y_true, y_score, k=2, labels=labels) diff --git a/sklearn/metrics/tests/test_score_objects.py b/sklearn/metrics/tests/test_score_objects.py index f379d0e2d7397..5597931990239 100644 --- a/sklearn/metrics/tests/test_score_objects.py +++ b/sklearn/metrics/tests/test_score_objects.py @@ -63,7 +63,7 @@ 'max_error', 'neg_mean_poisson_deviance', 'neg_mean_gamma_deviance'] -CLF_SCORERS = ['accuracy', 'balanced_accuracy', +CLF_SCORERS = ['accuracy', 'balanced_accuracy', 'top_k_accuracy', 'f1', 'f1_weighted', 'f1_macro', 'f1_micro', 'roc_auc', 'average_precision', 'precision', 'precision_weighted', 'precision_macro', 'precision_micro', @@ -506,6 +506,9 @@ def test_classification_scorer_sample_weight(): if name in REGRESSION_SCORERS: # skip the regression scores continue + if name == 'top_k_accuracy': + # in the binary case k > 1 will always lead to a perfect score + scorer._kwargs = {'k': 1} if name in MULTILABEL_ONLY_SCORERS: target = y_ml_test else:
[ { "path": "doc/modules/classes.rst", "old_path": "a/doc/modules/classes.rst", "new_path": "b/doc/modules/classes.rst", "metadata": "diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst\nindex e05d08781181f..6dbab18d94a0c 100644\n--- a/doc/modules/classes.rst\n+++ b/doc/modules/classes.rst\n@@ -966,6 +966,7 @@ details.\n metrics.recall_score\n metrics.roc_auc_score\n metrics.roc_curve\n+ metrics.top_k_accuracy_score\n metrics.zero_one_loss\n \n Regression metrics\n" }, { "path": "doc/modules/model_evaluation.rst", "old_path": "a/doc/modules/model_evaluation.rst", "new_path": "b/doc/modules/model_evaluation.rst", "metadata": "diff --git a/doc/modules/model_evaluation.rst b/doc/modules/model_evaluation.rst\nindex 05750222ad0ca..96fe4d396dc5d 100644\n--- a/doc/modules/model_evaluation.rst\n+++ b/doc/modules/model_evaluation.rst\n@@ -60,6 +60,7 @@ Scoring Function\n **Classification**\n 'accuracy' :func:`metrics.accuracy_score`\n 'balanced_accuracy' :func:`metrics.balanced_accuracy_score`\n+'top_k_accuracy' :func:`metrics.top_k_accuracy_score`\n 'average_precision' :func:`metrics.average_precision_score`\n 'neg_brier_score' :func:`metrics.brier_score_loss`\n 'f1' :func:`metrics.f1_score` for binary targets\n@@ -318,6 +319,7 @@ Others also work in the multiclass case:\n hinge_loss\n matthews_corrcoef\n roc_auc_score\n+ top_k_accuracy_score\n \n \n Some also work in the multilabel case:\n@@ -438,6 +440,44 @@ In the multilabel case with binary label indicators::\n for an example of accuracy score usage using permutations of\n the dataset.\n \n+.. _top_k_accuracy_score:\n+\n+Top-k accuracy score\n+--------------------\n+\n+The :func:`top_k_accuracy_score` function is a generalization of\n+:func:`accuracy_score`. The difference is that a prediction is considered\n+correct as long as the true label is associated with one of the ``k`` highest\n+predicted scores. :func:`accuracy_score` is the special case of `k = 1`.\n+\n+The function covers the binary and multiclass classification cases but not the\n+multilabel case.\n+\n+If :math:`\\hat{f}_{i,j}` is the predicted class for the :math:`i`-th sample\n+corresponding to the :math:`j`-th largest predicted score and :math:`y_i` is the\n+corresponding true value, then the fraction of correct predictions over\n+:math:`n_\\text{samples}` is defined as\n+\n+.. math::\n+\n+ \\texttt{top-k accuracy}(y, \\hat{f}) = \\frac{1}{n_\\text{samples}} \\sum_{i=0}^{n_\\text{samples}-1} \\sum_{j=1}^{k} 1(\\hat{f}_{i,j} = y_i)\n+\n+where :math:`k` is the number of guesses allowed and :math:`1(x)` is the\n+`indicator function <https://en.wikipedia.org/wiki/Indicator_function>`_.\n+\n+ >>> import numpy as np\n+ >>> from sklearn.metrics import top_k_accuracy_score\n+ >>> y_true = np.array([0, 1, 2, 2])\n+ >>> y_score = np.array([[0.5, 0.2, 0.2],\n+ ... [0.3, 0.4, 0.2],\n+ ... [0.2, 0.4, 0.3],\n+ ... [0.7, 0.2, 0.1]])\n+ >>> top_k_accuracy_score(y_true, y_score, k=2)\n+ 0.75\n+ >>> # Not normalizing gives the number of \"correctly\" classified samples\n+ >>> top_k_accuracy_score(y_true, y_score, k=2, normalize=False)\n+ 3\n+\n .. _balanced_accuracy_score:\n \n Balanced accuracy score\n" }, { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex bd7f368b023a9..68f6addbcad94 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -157,6 +157,10 @@ Changelog\n :pr:`18280` by :user:`Alex Liang <tianchuliang>` and\n `Guillaume Lemaitre`_.\n \n+- |Feature| :func:`datasets.fetch_openml` now validates md5checksum of arff\n+ files downloaded or cached to ensure data integrity.\n+ :pr:`14800` by :user:`Shashank Singh <shashanksingh28>` and `Joel Nothman`_.\n+\n - |API| The default value of `as_frame` in :func:`datasets.fetch_openml` is\n changed from False to 'auto'.\n :pr:`17610` by :user:`Jiaxiang <fujiaxiang>`.\n@@ -378,11 +382,18 @@ Changelog\n :mod:`sklearn.metrics`\n ......................\n \n+- |Feature| new metric :func:`metrics.top_k_accuracy_score`. It's a\n+ generalization of :func:`metrics.top_k_accuracy_score`, the difference is\n+ that a prediction is considered correct as long as the true label is\n+ associated with one of the `k` highest predicted scores.\n+ :func:`accuracy_score` is the special case of `k = 1`.\n+ :pr:`16625` by :user:`Geoffrey Bolmier <gbolmier>`.\n+\n - |Feature| Added :func:`metrics.det_curve` to compute Detection Error Tradeoff\n curve classification metric.\n :pr:`10591` by :user:`Jeremy Karnowski <jkarnows>` and\n :user:`Daniel Mohns <dmohns>`.\n-\n+ \n - |Feature| Added :func:`metrics.plot_det_curve` and\n :class:`metrics.DetCurveDisplay` to ease the plot of DET curves.\n :pr:`18176` by :user:`Guillaume Lemaitre <glemaitre>`.\n@@ -406,6 +417,10 @@ Changelog\n class to be used when computing the precision and recall statistics.\n :pr:`17569` by :user:`Guillaume Lemaitre <glemaitre>`.\n \n+- |Feature| :func:`metrics.plot_confusion_matrix` now supports making colorbar\n+ optional in the matplotlib plot by setting colorbar=False. :pr:`17192` by\n+ :user:`Avi Gupta <avigupta2612>`\n+\n - |Enhancement| Add `pos_label` parameter in\n :func:`metrics.plot_roc_curve` in order to specify the positive\n class to be used when computing the roc auc statistics.\n" } ]
0.24
6ca9eab67e1054a1f9508dfa286e0542c8bab5e3
[ "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[completeness_score]", "sklearn/metrics/tests/test_score_objects.py::test_check_scoring_and_check_multimetric_scoring[multi_tuple]", "sklearn/metrics/tests/test_score_objects.py::test_check_scoring_and_check_multimetric_scoring[single_tuple]", "sklearn/metrics/tests/test_score_objects.py::test_check_scoring_and_check_multimetric_scoring_errors[empty dict]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[neg_mean_absolute_percentage_error]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[mutual_info_score]", "sklearn/metrics/tests/test_score_objects.py::test_check_scoring_and_check_multimetric_scoring[dict_str]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[roc_auc_ovr_weighted]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_select_proba_error[ProbaScorer]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[adjusted_mutual_info_score]", "sklearn/metrics/tests/test_score_objects.py::test_check_scoring_and_check_multimetric_scoring_errors[non-string key dict]", "sklearn/metrics/tests/test_score_objects.py::test_supervised_cluster_scorers", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[recall]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[jaccard]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[jaccard_samples]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[homogeneity_score]", "sklearn/metrics/tests/test_score_objects.py::test_check_scoring_and_check_multimetric_scoring[single_list]", "sklearn/metrics/tests/test_score_objects.py::test_multimetric_scorer_calls_method_once[scorers0-1-1-1]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_no_op_multiclass_select_proba", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[recall_weighted]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[neg_mean_squared_error]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[neg_mean_poisson_deviance]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[neg_log_loss]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[recall_macro]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[precision]", "sklearn/metrics/tests/test_score_objects.py::test_check_scoring_and_check_multimetric_scoring_errors[non-unique str]", "sklearn/metrics/tests/test_score_objects.py::test_scoring_is_not_metric", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[balanced_accuracy]", "sklearn/metrics/tests/test_score_objects.py::test_thresholded_scorers", "sklearn/metrics/tests/test_score_objects.py::test_scorer_select_proba_error[PredictScorer]", "sklearn/metrics/tests/test_score_objects.py::test_multiclass_roc_no_proba_scorer_errors[roc_auc_ovo_weighted]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[adjusted_rand_score]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[roc_auc]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[jaccard_micro]", "sklearn/metrics/tests/test_score_objects.py::test_non_symmetric_metric_pos_label[f1_score]", "sklearn/metrics/tests/test_score_objects.py::test_brier_score_loss_pos_label", "sklearn/metrics/tests/test_score_objects.py::test_multiclass_roc_no_proba_scorer_errors[roc_auc_ovr]", "sklearn/metrics/tests/test_score_objects.py::test_multiclass_roc_proba_scorer[roc_auc_ovo_weighted-metric3]", "sklearn/metrics/tests/test_score_objects.py::test_check_scoring_and_check_multimetric_scoring[multi_list]", "sklearn/metrics/tests/test_score_objects.py::test_multiclass_roc_proba_scorer[roc_auc_ovr-metric0]", "sklearn/metrics/tests/test_score_objects.py::test_make_scorer", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[f1_samples]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[precision_weighted]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[jaccard_weighted]", "sklearn/metrics/tests/test_score_objects.py::test_multiclass_roc_proba_scorer_label", "sklearn/metrics/tests/test_score_objects.py::test_average_precision_pos_label", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[roc_auc_ovr]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[accuracy]", "sklearn/metrics/tests/test_score_objects.py::test_multiclass_roc_no_proba_scorer_errors[roc_auc_ovr_weighted]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[roc_auc_ovo]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[neg_median_absolute_error]", "sklearn/metrics/tests/test_score_objects.py::test_check_scoring_and_check_multimetric_scoring_errors[list of int]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[normalized_mutual_info_score]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[f1_macro]", "sklearn/metrics/tests/test_score_objects.py::test_regression_scorer_sample_weight", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[average_precision]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[f1_weighted]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[explained_variance]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[neg_brier_score]", "sklearn/metrics/tests/test_score_objects.py::test_non_symmetric_metric_pos_label[jaccard_score]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[precision_samples]", "sklearn/metrics/tests/test_score_objects.py::test_regression_scorers", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[roc_auc_ovo_weighted]", "sklearn/metrics/tests/test_score_objects.py::test_non_symmetric_metric_pos_label[precision_score]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[v_measure_score]", "sklearn/metrics/tests/test_score_objects.py::test_multimetric_scorer_calls_method_once[scorers2-1-1-0]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_select_proba_error[ThresholdScorer]", "sklearn/metrics/tests/test_score_objects.py::test_multiclass_roc_no_proba_scorer_errors[roc_auc_ovo]", "sklearn/metrics/tests/test_score_objects.py::test_multiclass_roc_proba_scorer[roc_auc_ovr_weighted-metric2]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[precision_macro]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[r2]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[neg_root_mean_squared_error]", "sklearn/metrics/tests/test_score_objects.py::test_multimetric_scorer_sanity_check", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[f1_micro]", "sklearn/metrics/tests/test_score_objects.py::test_check_scoring_and_check_multimetric_scoring_errors[tuple of one callable]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[f1]", "sklearn/metrics/tests/test_score_objects.py::test_thresholded_scorers_multilabel_indicator_data", "sklearn/metrics/tests/test_score_objects.py::test_raises_on_score_list", "sklearn/metrics/tests/test_score_objects.py::test_multiclass_roc_proba_scorer[roc_auc_ovo-metric1]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[max_error]", "sklearn/metrics/tests/test_score_objects.py::test_check_scoring_and_check_multimetric_scoring_errors[tuple of callables]", "sklearn/metrics/tests/test_score_objects.py::test_all_scorers_repr", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[recall_micro]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[jaccard_macro]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[fowlkes_mallows_score]", "sklearn/metrics/tests/test_score_objects.py::test_check_scoring_and_check_multimetric_scoring[dict_callable]", "sklearn/metrics/tests/test_score_objects.py::test_check_scoring_and_check_multimetric_scoring_errors[empty tuple]", "sklearn/metrics/tests/test_score_objects.py::test_multimetric_scorer_calls_method_once[scorers1-1-0-1]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[precision_micro]", "sklearn/metrics/tests/test_score_objects.py::test_classification_scores", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[neg_mean_gamma_deviance]", "sklearn/metrics/tests/test_score_objects.py::test_non_symmetric_metric_pos_label[recall_score]", "sklearn/metrics/tests/test_score_objects.py::test_classification_scorer_sample_weight", "sklearn/metrics/tests/test_score_objects.py::test_multimetric_scorer_calls_method_once_classifier_no_decision", "sklearn/metrics/tests/test_score_objects.py::test_check_scoring_gridsearchcv", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[recall_samples]", "sklearn/metrics/tests/test_score_objects.py::test_multimetric_scorer_calls_method_once_regressor_threshold", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[neg_mean_squared_log_error]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[neg_mean_absolute_error]" ]
[ "sklearn/metrics/tests/test_common.py::test_single_sample[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[samples_f2_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-Number of given labels, 2, not equal to the number of columns in 'y_score', 3-y_true4-labels4]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[r2_score]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_binary[y_score2-2-1]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[hinge_loss]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[dcg_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_error[Partial AUC computation not available in multiclass setting, 'max_fpr' must be set to `None`, received `max_fpr=0.5` instead-kwargs3]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_recall_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-Parameter 'labels' must be unique-y_true0-labels0]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[samples_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[macro_f1_score]", "sklearn/metrics/tests/test_ranking.py::test_dcg_score", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[r2_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_zeroes[f1_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[f0.5_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric7]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[samples_f2_score]", "sklearn/metrics/tests/test_ranking.py::test_precision_recall_curve_errors", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[micro_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[max_error]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true13-y_score13-expected_fpr13-expected_fnr13]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[coverage_error]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[log_loss]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[weighted_roc_auc]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[dcg_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[metric17]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[str-recall_score-False]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[matthews_corrcoef_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric19]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[samples_precision_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve_hard", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric18]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[metric11]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[roc_auc_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[samples_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_roc_auc]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric20]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true16-y_score16-expected_fpr16-expected_fnr16]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_tie_handling[y_true4-y_score4-expected_fpr4-expected_fnr4]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multiclass[recall_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[weighted_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_averaging_multiclass[f0.5_score]", "sklearn/metrics/tests/test_ranking.py::test_precision_recall_curve_toydata", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[weighted_ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_single_sample[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric32]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[metric8]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_ones[f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric27]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true19-y_score19-expected_fpr19-expected_fnr19]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[partial_roc_auc]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[micro_roc_auc]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[log_loss]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[recall_score]", "sklearn/metrics/tests/test_common.py::test_normalize_option_binary_classification[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[macro_precision_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-Number of given labels, 2, not equal to the number of columns in 'y_score', 3-y_true4-labels4]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[macro_jaccard_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve[False]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_constant_scores[1]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[samples_roc_auc]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[f1_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[micro_jaccard_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-Number of classes in y_true not equal to the number of columns in 'y_score'-y_true2-None]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_ovo_roc_auc]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_binary[y_score5-2-1]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[macro_f2_score]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true3-y_score3-expected_fpr3-expected_fnr3]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_zeroes[precision_score]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[str-average_precision_score-True]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric3]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[samples_recall_score]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_normal_deviance]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[mean_absolute_error]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-'y_true' contains labels not in parameter 'labels'-y_true8-labels8]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true0-y_score0-expected_fpr0-expected_fnr0]", "sklearn/metrics/tests/test_ranking.py::test_ndcg_toy_examples[True]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_ties[y_true1-2-0.5]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[hinge_loss]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-Number of given labels, 2, not equal to the number of columns in 'y_score', 3-y_true5-labels5]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[log_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[mean_absolute_error]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_perfect_scores[y_true2]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[dcg_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[ndcg_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[micro_roc_auc]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve_drop_intermediate", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score[y_true2-3-0.75]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[samples_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[macro_f2_score]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_bad_input[y_true0-y_pred0-inconsistent numbers of samples]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_binary[y_score0-1-1]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_f1_score]", "sklearn/metrics/tests/test_ranking.py::test_auc", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[samples_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[partial_roc_auc]", "sklearn/metrics/tests/test_ranking.py::test_ndcg_toy_examples[False]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric39]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[weighted_ovo_roc_auc]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[f1_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_error[average must be one of \\\\('macro', 'weighted'\\\\) for multiclass problems-kwargs0]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-5-2]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_single_sample[weighted_f1_score]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovr_roc_auc_toydata[y_true3-labels3]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[weighted_jaccard_score]", "sklearn/metrics/tests/test_ranking.py::test_label_ranking_avp[label_ranking_average_precision_score-check_lrap_toy]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-10-1]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true9-y_score9-expected_fpr9-expected_fnr9]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve_one_label", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[micro_f0.5_score]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_constant_scores[0.75]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_bad_input[y_true1-y_pred1-inconsistent numbers of samples]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[metric29]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[zero_one_loss]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-Parameter 'labels' must be unique-y_true1-labels1]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[hinge_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[macro_jaccard_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_error[average must be one of \\\\('macro', 'weighted'\\\\) for multiclass problems-kwargs1]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric35]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[matthews_corrcoef_score]", "sklearn/metrics/tests/test_ranking.py::test_dcg_ties", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[r2_score]", "sklearn/metrics/tests/test_ranking.py::test_auc_errors", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[<lambda>]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[max_error]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_normalize_option_multiclass_classification[top_k_accuracy_score]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovr_roc_auc_toydata[y_true2-labels2]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_perfect_scores[y_true3]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[brier_score_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[samples_recall_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[metric12]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovr_roc_auc_toydata[y_true1-None]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[micro_precision_score]", "sklearn/metrics/tests/test_ranking.py::test_binary_clf_curve_multiclass_error", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[recall_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[det_curve]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[top_k_accuracy_score]", "sklearn/metrics/tests/test_ranking.py::test_lrap_error_raised", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance_multilabel_and_multioutput", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_f0.5_score]", "sklearn/metrics/tests/test_ranking.py::test_lrap_sample_weighting_zero_labels", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_single_sample[macro_jaccard_score]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-2-2]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[mean_normal_deviance]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_bad_input[y_true3-y_pred3-Only one class present in y_true]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[zero_one_loss]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-Number of classes in y_true not equal to the number of columns in 'y_score'-y_true2-None]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[object-average_precision_score-True]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_perfect_scores[y_true4]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-2-20]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[ndcg_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[hamming_loss]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-10-20]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_error[y_true1-None-Number of classes in 'y_true' \\\\(4\\\\) not equal to the number of classes in 'y_score' \\\\(3\\\\).]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[r2_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[mean_absolute_error]", "sklearn/metrics/tests/test_ranking.py::test_partial_roc_auc_score", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_f2_score]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-5-8]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[samples_f1_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[matthews_corrcoef_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[metric13]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[samples_precision_score]", "sklearn/metrics/tests/test_ranking.py::test_average_precision_constant_values", "sklearn/metrics/tests/test_common.py::test_single_sample[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[ovr_roc_auc]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-'y_true' contains labels not in parameter 'labels'-y_true9-labels9]", "sklearn/metrics/tests/test_common.py::test_normalize_option_binary_classification[top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[object-metric3-False]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_perfect_scores[y_true1]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[metric30]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[label_ranking_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric15]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_single_sample[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[f0.5_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[samples_average_precision_score]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-5-1]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[object-precision_score-False]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_tie_handling[y_true1-y_score1-expected_fpr1-expected_fnr1]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[metric14]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true7-y_score7-expected_fpr7-expected_fnr7]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[weighted_f1_score]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score[y_true0-1-0.25]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[metric9]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[micro_f0.5_score]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-5-20]", "sklearn/metrics/tests/test_common.py::test_single_sample[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric23]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_ones[f2_score]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_tie_handling[y_true6-y_score6-expected_fpr6-expected_fnr6]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[log_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[label_ranking_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[log_loss]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_symmetry_consistency", "sklearn/metrics/tests/test_common.py::test_single_sample[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[f0.5_score]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovo_roc_auc_toydata[y_true3-None]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[average_precision_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[micro_f2_score]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_error[y_true4-labels4-Number of given labels \\\\(4\\\\) not equal to the number of classes in 'y_score' \\\\(3\\\\).]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[micro_precision_score]", "sklearn/metrics/tests/test_ranking.py::test_average_precision_score_pos_label_errors", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_compound_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[object-precision_recall_curve-True]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true17-y_score17-expected_fpr17-expected_fnr17]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true6-y_score6-expected_fpr6-expected_fnr6]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_zeroes[recall_score]", "sklearn/metrics/tests/test_common.py::test_normalize_option_multiclass_classification[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric38]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[samples_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[matthews_corrcoef_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[average_precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[dcg_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[samples_recall_score]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_perfect_scores[y_true0]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric26]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-Number of given labels, 4, not equal to the number of columns in 'y_score', 3-y_true6-labels6]", "sklearn/metrics/tests/test_common.py::test_single_sample[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true5-y_score5-expected_fpr5-expected_fnr5]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[samples_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[str-precision_score-False]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[str-precision_recall_curve-True]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[ovo_roc_auc]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[median_absolute_error]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_error[sample_weight is not supported for multiclass one-vs-one ROC AUC, 'sample_weight' must be None in this case-kwargs2]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score[y_true1-2-0.5]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric34]", "sklearn/metrics/tests/test_common.py::test_single_sample[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[matthews_corrcoef_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric41]", "sklearn/metrics/tests/test_common.py::test_normalize_option_multilabel_classification[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_zeroes[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_roc_auc]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_ones[f1_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[samples_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[precision_recall_curve]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-'y_true' contains labels not in parameter 'labels'-y_true8-labels8]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[recall_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[samples_recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[coverage_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[average_precision_score]", "sklearn/metrics/tests/test_ranking.py::test_ndcg_score", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[hinge_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[unnormalized_log_loss]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-Parameter 'labels' must be unique-y_true0-labels0]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric25]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[precision_recall_curve]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[object-jaccard_score-False]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[zero_one_loss]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-2-1]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[explained_variance_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-Number of given labels, 4, not equal to the number of columns in 'y_score', 3-y_true7-labels7]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[hinge_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric40]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[average_precision_score]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true18-y_score18-expected_fpr18-expected_fnr18]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[str-metric3-False]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_poisson_deviance]", "sklearn/metrics/tests/test_ranking.py::test_auc_score_non_binary_class", "sklearn/metrics/tests/test_common.py::test_single_sample[explained_variance_score]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_bad_input[y_true2-y_pred2-Only one class present in y_true]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_roc_auc]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_single_sample[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_f1_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multiclass[f2_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[accuracy_score]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true12-y_score12-expected_fpr12-expected_fnr12]", "sklearn/metrics/tests/test_ranking.py::test_label_ranking_avp[label_ranking_average_precision_score-check_zero_or_all_relevant_labels]", "sklearn/metrics/tests/test_ranking.py::test_label_ranking_avp[_my_lrap-check_lrap_without_tie_and_increasing_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric29]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[weighted_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[label_ranking_average_precision_score]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovo_roc_auc_toydata_binary[y_true0-labels0]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[brier_score_loss]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[f2_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[matthews_corrcoef_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[f2_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric10]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric37]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[label_ranking_loss]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[samples_roc_auc]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[mean_absolute_error]", "sklearn/metrics/tests/test_ranking.py::test_label_ranking_avp[label_ranking_average_precision_score-check_lrap_only_ties]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[hinge_loss]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_normal_deviance]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-Number of given labels, 2, not equal to the number of columns in 'y_score', 3-y_true5-labels5]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true14-y_score14-expected_fpr14-expected_fnr14]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[metric7]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[weighted_ovo_roc_auc]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_error[y_true5-labels5-'y_true' contains labels not in parameter 'labels'.]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[r2_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[micro_average_precision_score]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovo_roc_auc_toydata_binary[y_true1-labels1]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[mean_compound_poisson_deviance]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-2-8]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[average_precision_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[recall_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-Parameter 'labels' must be ordered-y_true3-labels3]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve_toydata", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[matthews_corrcoef_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve_multi", "sklearn/metrics/tests/test_ranking.py::test_det_curve_tie_handling[y_true2-y_score2-expected_fpr2-expected_fnr2]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[metric18]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[samples_roc_auc]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[object-f1_score-False]", "sklearn/metrics/tests/test_common.py::test_averaging_multiclass[precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric30]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_recall_score]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true1-y_score1-expected_fpr1-expected_fnr1]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[label_ranking_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[hinge_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[coverage_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric31]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[weighted_roc_auc]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[log_loss]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_normal_deviance]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[balanced_accuracy_score]", "sklearn/metrics/tests/test_ranking.py::test_ranking_appropriate_input_shape", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[object-roc_curve-True]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[roc_auc_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[samples_f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[metric16]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_sanity_check", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[zero_one_loss]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve_confidence", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_compound_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[cohen_kappa_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-Number of given labels, 4, not equal to the number of columns in 'y_score', 3-y_true6-labels6]", "sklearn/metrics/tests/test_common.py::test_averaging_binary_multilabel_all_zeroes", "sklearn/metrics/tests/test_ranking.py::test_label_ranking_loss", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_recall_score]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_constant_scores[0.25]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[samples_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[object-recall_score-False]", "sklearn/metrics/tests/test_common.py::test_single_sample[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_roc_auc]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[weighted_f1_score]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[top_k_accuracy]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[weighted_f2_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve[True]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[balanced_accuracy_score]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_warning[y_true0-4]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[samples_f2_score]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[r2_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[partial_roc_auc]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[object-brier_score_loss-True]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[roc_auc_score]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_constant_scores[0]", "sklearn/metrics/tests/test_ranking.py::test_coverage_error", "sklearn/metrics/tests/test_ranking.py::test_det_curve_pos_label", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_ties[y_true2-3-1]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true8-y_score8-expected_fpr8-expected_fnr8]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_increasing", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[roc_auc_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-Parameter 'labels' must be unique-y_true1-labels1]", "sklearn/metrics/tests/test_ranking.py::test_label_ranking_avp[_my_lrap-check_lrap_toy]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[max_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[brier_score_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[r2_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[weighted_ovr_roc_auc]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_binary[y_score1-1-0.5]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric21]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_ties[y_true0-1-0.25]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_error[y_true0-None-y type must be 'binary' or 'multiclass', got 'continuous']", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[micro_f1_score]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-10-8]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_precision_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_error[multi_class must be in \\\\('ovo', 'ovr'\\\\)-kwargs5]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[log_loss]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[ovo_roc_auc]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[macro_f2_score]", "sklearn/metrics/tests/test_ranking.py::test_label_ranking_avp[_my_lrap-check_lrap_only_ties]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_tie_handling[y_true3-y_score3-expected_fpr3-expected_fnr3]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[micro_recall_score]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovo_roc_auc_toydata[y_true0-labels0]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_ranking.py::test_binary_clf_curve_implicit_pos_label[roc_curve]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_error[multi_class='ovp' is not supported for multiclass ROC AUC, multi_class must be in \\\\('ovo', 'ovr'\\\\)-kwargs4]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[roc_curve]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[ndcg_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[metric10]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[log_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[f2_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric2]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_zeroes[f0.5_score]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[partial_roc_auc]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric22]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[samples_average_precision_score]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true11-y_score11-expected_fpr11-expected_fnr11]", "sklearn/metrics/tests/test_common.py::test_single_sample[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[macro_f1_score]", "sklearn/metrics/tests/test_ranking.py::test_label_ranking_avp[label_ranking_average_precision_score-check_lrap_without_tie_and_increasing_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-'y_true' contains labels not in parameter 'labels'-y_true10-labels10]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_jaccard_score]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-10-2]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_warning[y_true1-5]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_absolute_error]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_tie_handling[y_true7-y_score7-expected_fpr7-expected_fnr7]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_compound_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[macro_recall_score]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_binary[y_score3-1-1]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[roc_curve]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[average_precision_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[str-brier_score_loss-True]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[macro_f2_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-'y_true' contains labels not in parameter 'labels'-y_true10-labels10]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_multilabel_representation_invariance", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_zeroes[f2_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[recall_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[precision_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[str-roc_curve-True]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[samples_f1_score]", "sklearn/metrics/tests/test_common.py::test_normalize_option_binary_classification[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[median_absolute_error]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true4-y_score4-expected_fpr4-expected_fnr4]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_ones[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[log_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[cohen_kappa_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-Number of given labels, 4, not equal to the number of columns in 'y_score', 3-y_true7-labels7]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[micro_precision_score]", "sklearn/metrics/tests/test_ranking.py::test_ndcg_ignore_ties_with_k", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[roc_auc_score]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovr_roc_auc_toydata[y_true0-None]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[unnormalized_multilabel_confusion_matrix_sample]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[partial_roc_auc]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[metric3]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_ovo_roc_auc]", "sklearn/metrics/tests/test_ranking.py::test_score_scale_invariance", "sklearn/metrics/tests/test_common.py::test_single_sample[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_f2_score]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true15-y_score15-expected_fpr15-expected_fnr15]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_ones[precision_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[samples_f1_score]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[micro_recall_score]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovo_roc_auc_toydata[y_true1-None]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[metric33]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[ovo_roc_auc]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_ones[recall_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[samples_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[r2_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_compound_poisson_deviance]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_error[y_true2-labels2-Parameter 'labels' must be unique.]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_squared_error]", "sklearn/metrics/tests/test_ranking.py::test_ndcg_invariant", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true10-y_score10-expected_fpr10-expected_fnr10]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_error[y_true3-labels3-Parameter 'labels' must be ordered.]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[coverage_error]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[top_k_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[matthews_corrcoef_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric16]", "sklearn/metrics/tests/test_common.py::test_averaging_multiclass[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[f1_score]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_bad_input[y_true4-y_pred4-pos_label is not specified]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[det_curve]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[cohen_kappa_score]", "sklearn/metrics/tests/test_ranking.py::test_top_k_accuracy_score_binary[y_score4-1-0.5]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[hinge_loss]", "sklearn/metrics/tests/test_common.py::test_normalize_option_multiclass_classification[zero_one_loss]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_tie_handling[y_true5-y_score5-expected_fpr5-expected_fnr5]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_normal_deviance]", "sklearn/metrics/tests/test_ranking.py::test_roc_returns_consistency", "sklearn/metrics/tests/test_common.py::test_single_sample[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[label_ranking_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[label_ranking_loss]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_roc_auc]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[log_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric33]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[matthews_corrcoef]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[max_error]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[ovr_roc_auc]", "sklearn/metrics/tests/test_ranking.py::test_ranking_loss_ties_handling", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[r2_score]", "sklearn/metrics/tests/test_ranking.py::test_precision_recall_curve", "sklearn/metrics/tests/test_ranking.py::test_binary_clf_curve_implicit_pos_label[precision_recall_curve]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[samples_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[samples_precision_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[samples_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[roc_auc_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[samples_f2_score]", "sklearn/metrics/tests/test_common.py::test_no_averaging_labels", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[max_error]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[macro_f1_score]", "sklearn/metrics/tests/test_ranking.py::test_label_ranking_avp[_my_lrap-check_zero_or_all_relevant_labels]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric36]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_constant_scores[0.5]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric28]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[r2_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-'y_true' contains labels not in parameter 'labels'-y_true9-labels9]", "sklearn/metrics/tests/test_common.py::test_normalize_option_multilabel_classification[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[micro_f0.5_score]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovo_roc_auc_toydata[y_true2-labels2]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[f2_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[macro_f2_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-Parameter 'labels' must be ordered-y_true3-labels3]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[str-jaccard_score-False]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_f2_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[median_absolute_error]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve_end_points", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[micro_precision_score]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_tie_handling[y_true0-y_score0-expected_fpr0-expected_fnr0]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_metrics_pos_label_error_str[str-f1_score-False]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[mean_gamma_deviance]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve_fpr_tpr_increasing", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[ndcg_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multiclass[f1_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[hamming_loss]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true2-y_score2-expected_fpr2-expected_fnr2]", "sklearn/metrics/tests/test_common.py::test_single_sample[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[ovo_roc_auc]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_ranking.py::test_coverage_tie_handling", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_metrics_consistent_type_error[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric24]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[label_ranking_loss]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/modules/classes.rst", "old_path": "a/doc/modules/classes.rst", "new_path": "b/doc/modules/classes.rst", "metadata": "diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst\nindex e05d08781181f..6dbab18d94a0c 100644\n--- a/doc/modules/classes.rst\n+++ b/doc/modules/classes.rst\n@@ -966,6 +966,7 @@ details.\n metrics.recall_score\n metrics.roc_auc_score\n metrics.roc_curve\n+ metrics.top_k_accuracy_score\n metrics.zero_one_loss\n \n Regression metrics\n" }, { "path": "doc/modules/model_evaluation.rst", "old_path": "a/doc/modules/model_evaluation.rst", "new_path": "b/doc/modules/model_evaluation.rst", "metadata": "diff --git a/doc/modules/model_evaluation.rst b/doc/modules/model_evaluation.rst\nindex 05750222ad0ca..96fe4d396dc5d 100644\n--- a/doc/modules/model_evaluation.rst\n+++ b/doc/modules/model_evaluation.rst\n@@ -60,6 +60,7 @@ Scoring Function\n **Classification**\n 'accuracy' :func:`metrics.accuracy_score`\n 'balanced_accuracy' :func:`metrics.balanced_accuracy_score`\n+'top_k_accuracy' :func:`metrics.top_k_accuracy_score`\n 'average_precision' :func:`metrics.average_precision_score`\n 'neg_brier_score' :func:`metrics.brier_score_loss`\n 'f1' :func:`metrics.f1_score` for binary targets\n@@ -318,6 +319,7 @@ Others also work in the multiclass case:\n hinge_loss\n matthews_corrcoef\n roc_auc_score\n+ top_k_accuracy_score\n \n \n Some also work in the multilabel case:\n@@ -438,6 +440,44 @@ In the multilabel case with binary label indicators::\n for an example of accuracy score usage using permutations of\n the dataset.\n \n+.. _top_k_accuracy_score:\n+\n+Top-k accuracy score\n+--------------------\n+\n+The :func:`top_k_accuracy_score` function is a generalization of\n+:func:`accuracy_score`. The difference is that a prediction is considered\n+correct as long as the true label is associated with one of the ``k`` highest\n+predicted scores. :func:`accuracy_score` is the special case of `k = 1`.\n+\n+The function covers the binary and multiclass classification cases but not the\n+multilabel case.\n+\n+If :math:`\\hat{f}_{i,j}` is the predicted class for the :math:`i`-th sample\n+corresponding to the :math:`j`-th largest predicted score and :math:`y_i` is the\n+corresponding true value, then the fraction of correct predictions over\n+:math:`n_\\text{samples}` is defined as\n+\n+.. math::\n+\n+ \\texttt{top-k accuracy}(y, \\hat{f}) = \\frac{1}{n_\\text{samples}} \\sum_{i=0}^{n_\\text{samples}-1} \\sum_{j=1}^{k} 1(\\hat{f}_{i,j} = y_i)\n+\n+where :math:`k` is the number of guesses allowed and :math:`1(x)` is the\n+`indicator function <https://en.wikipedia.org/wiki/Indicator_function>`_.\n+\n+ >>> import numpy as np\n+ >>> from sklearn.metrics import top_k_accuracy_score\n+ >>> y_true = np.array([0, 1, 2, 2])\n+ >>> y_score = np.array([[0.5, 0.2, 0.2],\n+ ... [0.3, 0.4, 0.2],\n+ ... [0.2, 0.4, 0.3],\n+ ... [0.7, 0.2, 0.1]])\n+ >>> top_k_accuracy_score(y_true, y_score, k=2)\n+ 0.75\n+ >>> # Not normalizing gives the number of \"correctly\" classified samples\n+ >>> top_k_accuracy_score(y_true, y_score, k=2, normalize=False)\n+ 3\n+\n .. _balanced_accuracy_score:\n \n Balanced accuracy score\n" }, { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex bd7f368b023a9..68f6addbcad94 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -157,6 +157,10 @@ Changelog\n :pr:`<PRID>` by :user:`<NAME>` and\n `Guillaume Lemaitre`_.\n \n+- |Feature| :func:`datasets.fetch_openml` now validates md5checksum of arff\n+ files downloaded or cached to ensure data integrity.\n+ :pr:`<PRID>` by :user:`<NAME>` and `Joel Nothman`_.\n+\n - |API| The default value of `as_frame` in :func:`datasets.fetch_openml` is\n changed from False to 'auto'.\n :pr:`<PRID>` by :user:`<NAME>`.\n@@ -378,11 +382,18 @@ Changelog\n :mod:`sklearn.metrics`\n ......................\n \n+- |Feature| new metric :func:`metrics.top_k_accuracy_score`. It's a\n+ generalization of :func:`metrics.top_k_accuracy_score`, the difference is\n+ that a prediction is considered correct as long as the true label is\n+ associated with one of the `k` highest predicted scores.\n+ :func:`accuracy_score` is the special case of `k = 1`.\n+ :pr:`<PRID>` by :user:`<NAME>`.\n+\n - |Feature| Added :func:`metrics.det_curve` to compute Detection Error Tradeoff\n curve classification metric.\n :pr:`<PRID>` by :user:`<NAME>` and\n :user:`<NAME>`.\n-\n+ \n - |Feature| Added :func:`metrics.plot_det_curve` and\n :class:`metrics.DetCurveDisplay` to ease the plot of DET curves.\n :pr:`<PRID>` by :user:`<NAME>`.\n@@ -406,6 +417,10 @@ Changelog\n class to be used when computing the precision and recall statistics.\n :pr:`<PRID>` by :user:`<NAME>`.\n \n+- |Feature| :func:`metrics.plot_confusion_matrix` now supports making colorbar\n+ optional in the matplotlib plot by setting colorbar=False. :pr:`<PRID>` by\n+ :user:`<NAME>`\n+\n - |Enhancement| Add `pos_label` parameter in\n :func:`metrics.plot_roc_curve` in order to specify the positive\n class to be used when computing the roc auc statistics.\n" } ]
diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst index e05d08781181f..6dbab18d94a0c 100644 --- a/doc/modules/classes.rst +++ b/doc/modules/classes.rst @@ -966,6 +966,7 @@ details. metrics.recall_score metrics.roc_auc_score metrics.roc_curve + metrics.top_k_accuracy_score metrics.zero_one_loss Regression metrics diff --git a/doc/modules/model_evaluation.rst b/doc/modules/model_evaluation.rst index 05750222ad0ca..96fe4d396dc5d 100644 --- a/doc/modules/model_evaluation.rst +++ b/doc/modules/model_evaluation.rst @@ -60,6 +60,7 @@ Scoring Function **Classification** 'accuracy' :func:`metrics.accuracy_score` 'balanced_accuracy' :func:`metrics.balanced_accuracy_score` +'top_k_accuracy' :func:`metrics.top_k_accuracy_score` 'average_precision' :func:`metrics.average_precision_score` 'neg_brier_score' :func:`metrics.brier_score_loss` 'f1' :func:`metrics.f1_score` for binary targets @@ -318,6 +319,7 @@ Others also work in the multiclass case: hinge_loss matthews_corrcoef roc_auc_score + top_k_accuracy_score Some also work in the multilabel case: @@ -438,6 +440,44 @@ In the multilabel case with binary label indicators:: for an example of accuracy score usage using permutations of the dataset. +.. _top_k_accuracy_score: + +Top-k accuracy score +-------------------- + +The :func:`top_k_accuracy_score` function is a generalization of +:func:`accuracy_score`. The difference is that a prediction is considered +correct as long as the true label is associated with one of the ``k`` highest +predicted scores. :func:`accuracy_score` is the special case of `k = 1`. + +The function covers the binary and multiclass classification cases but not the +multilabel case. + +If :math:`\hat{f}_{i,j}` is the predicted class for the :math:`i`-th sample +corresponding to the :math:`j`-th largest predicted score and :math:`y_i` is the +corresponding true value, then the fraction of correct predictions over +:math:`n_\text{samples}` is defined as + +.. math:: + + \texttt{top-k accuracy}(y, \hat{f}) = \frac{1}{n_\text{samples}} \sum_{i=0}^{n_\text{samples}-1} \sum_{j=1}^{k} 1(\hat{f}_{i,j} = y_i) + +where :math:`k` is the number of guesses allowed and :math:`1(x)` is the +`indicator function <https://en.wikipedia.org/wiki/Indicator_function>`_. + + >>> import numpy as np + >>> from sklearn.metrics import top_k_accuracy_score + >>> y_true = np.array([0, 1, 2, 2]) + >>> y_score = np.array([[0.5, 0.2, 0.2], + ... [0.3, 0.4, 0.2], + ... [0.2, 0.4, 0.3], + ... [0.7, 0.2, 0.1]]) + >>> top_k_accuracy_score(y_true, y_score, k=2) + 0.75 + >>> # Not normalizing gives the number of "correctly" classified samples + >>> top_k_accuracy_score(y_true, y_score, k=2, normalize=False) + 3 + .. _balanced_accuracy_score: Balanced accuracy score diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index bd7f368b023a9..68f6addbcad94 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -157,6 +157,10 @@ Changelog :pr:`<PRID>` by :user:`<NAME>` and `Guillaume Lemaitre`_. +- |Feature| :func:`datasets.fetch_openml` now validates md5checksum of arff + files downloaded or cached to ensure data integrity. + :pr:`<PRID>` by :user:`<NAME>` and `Joel Nothman`_. + - |API| The default value of `as_frame` in :func:`datasets.fetch_openml` is changed from False to 'auto'. :pr:`<PRID>` by :user:`<NAME>`. @@ -378,11 +382,18 @@ Changelog :mod:`sklearn.metrics` ...................... +- |Feature| new metric :func:`metrics.top_k_accuracy_score`. It's a + generalization of :func:`metrics.top_k_accuracy_score`, the difference is + that a prediction is considered correct as long as the true label is + associated with one of the `k` highest predicted scores. + :func:`accuracy_score` is the special case of `k = 1`. + :pr:`<PRID>` by :user:`<NAME>`. + - |Feature| Added :func:`metrics.det_curve` to compute Detection Error Tradeoff curve classification metric. :pr:`<PRID>` by :user:`<NAME>` and :user:`<NAME>`. - + - |Feature| Added :func:`metrics.plot_det_curve` and :class:`metrics.DetCurveDisplay` to ease the plot of DET curves. :pr:`<PRID>` by :user:`<NAME>`. @@ -406,6 +417,10 @@ Changelog class to be used when computing the precision and recall statistics. :pr:`<PRID>` by :user:`<NAME>`. +- |Feature| :func:`metrics.plot_confusion_matrix` now supports making colorbar + optional in the matplotlib plot by setting colorbar=False. :pr:`<PRID>` by + :user:`<NAME>` + - |Enhancement| Add `pos_label` parameter in :func:`metrics.plot_roc_curve` in order to specify the positive class to be used when computing the roc auc statistics.
scikit-learn/scikit-learn
scikit-learn__scikit-learn-18176
https://github.com/scikit-learn/scikit-learn/pull/18176
diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst index f5a0e71e07d1c..2ec617df85cc0 100644 --- a/doc/modules/classes.rst +++ b/doc/modules/classes.rst @@ -947,7 +947,7 @@ details. metrics.cohen_kappa_score metrics.confusion_matrix metrics.dcg_score - metrics.detection_error_tradeoff_curve + metrics.det_curve metrics.f1_score metrics.fbeta_score metrics.hamming_loss @@ -1100,6 +1100,7 @@ See the :ref:`visualizations` section of the user guide for further details. :template: function.rst metrics.plot_confusion_matrix + metrics.plot_det_curve metrics.plot_precision_recall_curve metrics.plot_roc_curve @@ -1108,6 +1109,7 @@ See the :ref:`visualizations` section of the user guide for further details. :template: class.rst metrics.ConfusionMatrixDisplay + metrics.DetCurveDisplay metrics.PrecisionRecallDisplay metrics.RocCurveDisplay diff --git a/doc/modules/model_evaluation.rst b/doc/modules/model_evaluation.rst index e64aee2075e06..58c30d3091830 100644 --- a/doc/modules/model_evaluation.rst +++ b/doc/modules/model_evaluation.rst @@ -306,7 +306,7 @@ Some of these are restricted to the binary classification case: precision_recall_curve roc_curve - detection_error_tradeoff_curve + det_curve Others also work in the multiclass case: @@ -1443,7 +1443,7 @@ to the given limit. Detection error tradeoff (DET) ------------------------------ -The function :func:`detection_error_tradeoff_curve` computes the +The function :func:`det_curve` computes the detection error tradeoff curve (DET) curve [WikipediaDET2017]_. Quoting Wikipedia: diff --git a/doc/visualizations.rst b/doc/visualizations.rst index ad316205b3c90..a2d40408b403f 100644 --- a/doc/visualizations.rst +++ b/doc/visualizations.rst @@ -78,6 +78,7 @@ Functions inspection.plot_partial_dependence metrics.plot_confusion_matrix + metrics.plot_det_curve metrics.plot_precision_recall_curve metrics.plot_roc_curve @@ -91,5 +92,6 @@ Display Objects inspection.PartialDependenceDisplay metrics.ConfusionMatrixDisplay + metrics.DetCurveDisplay metrics.PrecisionRecallDisplay metrics.RocCurveDisplay diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index aaf86a2f0576d..1da9670307b75 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -280,11 +280,15 @@ Changelog :mod:`sklearn.metrics` ...................... -- |Feature| Added :func:`metrics.detection_error_tradeoff_curve` to compute - Detection Error Tradeoff curve classification metric. +- |Feature| Added :func:`metrics.det_curve` to compute Detection Error Tradeoff + curve classification metric. :pr:`10591` by :user:`Jeremy Karnowski <jkarnows>` and :user:`Daniel Mohns <dmohns>`. +- |Feature| Added :func:`metrics.plot_det_curve` and :class:`DetCurveDisplay` + to ease the plot of DET curves. + :pr:`18176` by :user:`Guillaume Lemaitre <glemaitre>`. + - |Feature| Added :func:`metrics.mean_absolute_percentage_error` metric and the associated scorer for regression problems. :issue:`10708` fixed with the PR :pr:`15007` by :user:`Ashutosh Hathidara <ashutosh1919>`. The scorer and diff --git a/examples/model_selection/plot_det.py b/examples/model_selection/plot_det.py index f4b1b96f947a2..2e27dd07ee684 100644 --- a/examples/model_selection/plot_det.py +++ b/examples/model_selection/plot_det.py @@ -8,9 +8,9 @@ for the same classification task. DET curves are commonly plotted in normal deviate scale. -To achieve this we transform the error rates as returned by the -:func:`~sklearn.metrics.detection_error_tradeoff_curve` function and the axis -scale using :func:`scipy.stats.norm`. +To achieve this `plot_det_curve` transforms the error rates as returned by the +:func:`~sklearn.metrics.det_curve` and the axis scale using +:func:`scipy.stats.norm`. The point of this example is to demonstrate two properties of DET curves, namely: @@ -39,8 +39,8 @@ - See :func:`sklearn.metrics.roc_curve` for further information about ROC curves. - - See :func:`sklearn.metrics.detection_error_tradeoff_curve` for further - information about DET curves. + - See :func:`sklearn.metrics.det_curve` for further information about + DET curves. - This example is loosely based on :ref:`sphx_glr_auto_examples_classification_plot_classifier_comparison.py` @@ -51,15 +51,13 @@ from sklearn.datasets import make_classification from sklearn.ensemble import RandomForestClassifier -from sklearn.metrics import detection_error_tradeoff_curve +from sklearn.metrics import plot_det_curve from sklearn.metrics import plot_roc_curve from sklearn.model_selection import train_test_split from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from sklearn.svm import LinearSVC -from scipy.stats import norm - N_SAMPLES = 1000 classifiers = { @@ -79,43 +77,17 @@ # prepare plots fig, [ax_roc, ax_det] = plt.subplots(1, 2, figsize=(11, 5)) -# first prepare the ROC curve -ax_roc.set_title('Receiver Operating Characteristic (ROC) curves') -ax_roc.grid(linestyle='--') - -# second prepare the DET curve -ax_det.set_title('Detection Error Tradeoff (DET) curves') -ax_det.set_xlabel('False Positive Rate') -ax_det.set_ylabel('False Negative Rate') -ax_det.set_xlim(-3, 3) -ax_det.set_ylim(-3, 3) -ax_det.grid(linestyle='--') - -# customized ticks for DET curve plot to represent normal deviate scale -ticks = [0.001, 0.01, 0.05, 0.20, 0.5, 0.80, 0.95, 0.99, 0.999] -tick_locs = norm.ppf(ticks) -tick_lbls = [ - '{:.0%}'.format(s) if (100*s).is_integer() else '{:.1%}'.format(s) - for s in ticks -] -plt.sca(ax_det) -plt.xticks(tick_locs, tick_lbls) -plt.yticks(tick_locs, tick_lbls) - -# iterate over classifiers for name, clf in classifiers.items(): clf.fit(X_train, y_train) - if hasattr(clf, "decision_function"): - y_score = clf.decision_function(X_test) - else: - y_score = clf.predict_proba(X_test)[:, 1] - plot_roc_curve(clf, X_test, y_test, ax=ax_roc, name=name) - det_fpr, det_fnr, _ = detection_error_tradeoff_curve(y_test, y_score) + plot_det_curve(clf, X_test, y_test, ax=ax_det, name=name) + +ax_roc.set_title('Receiver Operating Characteristic (ROC) curves') +ax_det.set_title('Detection Error Tradeoff (DET) curves') - # transform errors into normal deviate scale - ax_det.plot(norm.ppf(det_fpr), norm.ppf(det_fnr), label=name) +ax_roc.grid(linestyle='--') +ax_det.grid(linestyle='--') plt.legend() plt.show() diff --git a/sklearn/metrics/__init__.py b/sklearn/metrics/__init__.py index a69d5c618c20f..a8beea4f8c2f9 100644 --- a/sklearn/metrics/__init__.py +++ b/sklearn/metrics/__init__.py @@ -7,7 +7,7 @@ from ._ranking import auc from ._ranking import average_precision_score from ._ranking import coverage_error -from ._ranking import detection_error_tradeoff_curve +from ._ranking import det_curve from ._ranking import dcg_score from ._ranking import label_ranking_average_precision_score from ._ranking import label_ranking_loss @@ -77,6 +77,8 @@ from ._scorer import SCORERS from ._scorer import get_scorer +from ._plot.det_curve import plot_det_curve +from ._plot.det_curve import DetCurveDisplay from ._plot.roc_curve import plot_roc_curve from ._plot.roc_curve import RocCurveDisplay from ._plot.precision_recall_curve import plot_precision_recall_curve @@ -105,7 +107,8 @@ 'coverage_error', 'dcg_score', 'davies_bouldin_score', - 'detection_error_tradeoff_curve', + 'DetCurveDisplay', + 'det_curve', 'euclidean_distances', 'explained_variance_score', 'f1_score', @@ -142,6 +145,7 @@ 'pairwise_distances_chunked', 'pairwise_kernels', 'plot_confusion_matrix', + 'plot_det_curve', 'plot_precision_recall_curve', 'plot_roc_curve', 'PrecisionRecallDisplay', diff --git a/sklearn/metrics/_plot/det_curve.py b/sklearn/metrics/_plot/det_curve.py new file mode 100644 index 0000000000000..00ae0226ea6d3 --- /dev/null +++ b/sklearn/metrics/_plot/det_curve.py @@ -0,0 +1,224 @@ +import scipy as sp + +from .base import _get_response + +from .. import det_curve + +from ...utils import check_matplotlib_support + + +class DetCurveDisplay: + """DET curve visualization. + + It is recommend to use :func:`~sklearn.metrics.plot_det_curve` to create a + visualizer. All parameters are stored as attributes. + + Read more in the :ref:`User Guide <visualizations>`. + + .. versionadded:: 0.24 + + Parameters + ---------- + fpr : ndarray + False positive rate. + + tpr : ndarray + True positive rate. + + estimator_name : str, default=None + Name of estimator. If None, the estimator name is not shown. + + pos_label : str or int, default=None + The label of the positive class. + + Attributes + ---------- + line_ : matplotlib Artist + DET Curve. + + ax_ : matplotlib Axes + Axes with DET Curve. + + figure_ : matplotlib Figure + Figure containing the curve. + + Examples + -------- + >>> import matplotlib.pyplot as plt # doctest: +SKIP + >>> import numpy as np + >>> from sklearn import metrics + >>> y = np.array([0, 0, 1, 1]) + >>> pred = np.array([0.1, 0.4, 0.35, 0.8]) + >>> fpr, fnr, thresholds = metrics.det_curve(y, pred) + >>> display = metrics.DetCurveDisplay( + ... fpr=fpr, fnr=fnr, estimator_name='example estimator' + ... ) + >>> display.plot() # doctest: +SKIP + >>> plt.show() # doctest: +SKIP + """ + def __init__(self, *, fpr, fnr, estimator_name=None, pos_label=None): + self.fpr = fpr + self.fnr = fnr + self.estimator_name = estimator_name + self.pos_label = pos_label + + def plot(self, ax=None, *, name=None, **kwargs): + """Plot visualization. + + Parameters + ---------- + ax : matplotlib axes, default=None + Axes object to plot on. If `None`, a new figure and axes is + created. + + name : str, default=None + Name of DET curve for labeling. If `None`, use the name of the + estimator. + + Returns + ------- + display : :class:`~sklearn.metrics.plot.DetCurveDisplay` + Object that stores computed values. + """ + check_matplotlib_support('DetCurveDisplay.plot') + + name = self.estimator_name if name is None else name + line_kwargs = {} if name is None else {"label": name} + line_kwargs.update(**kwargs) + + import matplotlib.pyplot as plt + + if ax is None: + _, ax = plt.subplots() + + self.line_, = ax.plot( + sp.stats.norm.ppf(self.fpr), + sp.stats.norm.ppf(self.fnr), + **line_kwargs, + ) + info_pos_label = (f" (Positive label: {self.pos_label})" + if self.pos_label is not None else "") + + xlabel = "False Positive Rate" + info_pos_label + ylabel = "False Negative Rate" + info_pos_label + ax.set(xlabel=xlabel, ylabel=ylabel) + + if "label" in line_kwargs: + ax.legend(loc="lower right") + + ticks = [0.001, 0.01, 0.05, 0.20, 0.5, 0.80, 0.95, 0.99, 0.999] + tick_locations = sp.stats.norm.ppf(ticks) + tick_labels = [ + '{:.0%}'.format(s) if (100*s).is_integer() else '{:.1%}'.format(s) + for s in ticks + ] + ax.set_xticks(tick_locations) + ax.set_xticklabels(tick_labels) + ax.set_xlim(-3, 3) + ax.set_yticks(tick_locations) + ax.set_yticklabels(tick_labels) + ax.set_ylim(-3, 3) + + self.ax_ = ax + self.figure_ = ax.figure + return self + + +def plot_det_curve( + estimator, + X, + y, + *, + sample_weight=None, + response_method="auto", + name=None, + ax=None, + pos_label=None, + **kwargs +): + """Plot detection error tradeoff (DET) curve. + + Extra keyword arguments will be passed to matplotlib's `plot`. + + Read more in the :ref:`User Guide <visualizations>`. + + .. versionadded:: 0.24 + + Parameters + ---------- + estimator : estimator instance + Fitted classifier or a fitted :class:`~sklearn.pipeline.Pipeline` + in which the last estimator is a classifier. + + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Input values. + + y : array-like of shape (n_samples,) + Target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + response_method : {'predict_proba', 'decision_function', 'auto'} \ + default='auto' + Specifies whether to use :term:`predict_proba` or + :term:`decision_function` as the predicted target response. If set to + 'auto', :term:`predict_proba` is tried first and if it does not exist + :term:`decision_function` is tried next. + + name : str, default=None + Name of DET curve for labeling. If `None`, use the name of the + estimator. + + ax : matplotlib axes, default=None + Axes object to plot on. If `None`, a new figure and axes is created. + + pos_label : str or int, default=None + The label of the positive class. + When `pos_label=None`, if `y_true` is in {-1, 1} or {0, 1}, + `pos_label` is set to 1, otherwise an error will be raised. + + Returns + ------- + display : :class:`~sklearn.metrics.DetCurveDisplay` + Object that stores computed values. + + See Also + -------- + det_curve : Compute error rates for different probability thresholds + + plot_roc_curve : Plot Receiver operating characteristic (ROC) curve + + Examples + -------- + >>> import matplotlib.pyplot as plt # doctest: +SKIP + >>> from sklearn import datasets, metrics, model_selection, svm + >>> X, y = datasets.make_classification(random_state=0) + >>> X_train, X_test, y_train, y_test = model_selection.train_test_split( + ... X, y, random_state=0) + >>> clf = svm.SVC(random_state=0) + >>> clf.fit(X_train, y_train) + SVC(random_state=0) + >>> metrics.plot_det_curve(clf, X_test, y_test) # doctest: +SKIP + >>> plt.show() # doctest: +SKIP + """ + check_matplotlib_support('plot_det_curve') + + y_pred, pos_label = _get_response( + X, estimator, response_method, pos_label=pos_label + ) + + fpr, fnr, _ = det_curve( + y, y_pred, pos_label=pos_label, sample_weight=sample_weight, + ) + + name = estimator.__class__.__name__ if name is None else name + + viz = DetCurveDisplay( + fpr=fpr, + fnr=fnr, + estimator_name=name, + pos_label=pos_label + ) + + return viz.plot(ax=ax, name=name, **kwargs) diff --git a/sklearn/metrics/_ranking.py b/sklearn/metrics/_ranking.py index 0d44600d272e3..8e6a2280eebd5 100644 --- a/sklearn/metrics/_ranking.py +++ b/sklearn/metrics/_ranking.py @@ -218,8 +218,7 @@ def _binary_uninterpolated_average_precision( average, sample_weight=sample_weight) -def detection_error_tradeoff_curve(y_true, y_score, pos_label=None, - sample_weight=None): +def det_curve(y_true, y_score, pos_label=None, sample_weight=None): """Compute error rates for different probability thresholds. .. note:: @@ -273,10 +272,10 @@ def detection_error_tradeoff_curve(y_true, y_score, pos_label=None, Examples -------- >>> import numpy as np - >>> from sklearn.metrics import detection_error_tradeoff_curve + >>> from sklearn.metrics import det_curve >>> y_true = np.array([0, 0, 1, 1]) >>> y_scores = np.array([0.1, 0.4, 0.35, 0.8]) - >>> fpr, fnr, thresholds = detection_error_tradeoff_curve(y_true, y_scores) + >>> fpr, fnr, thresholds = det_curve(y_true, y_scores) >>> fpr array([0.5, 0.5, 0. ]) >>> fnr @@ -747,14 +746,13 @@ def precision_recall_curve(y_true, probas_pred, *, pos_label=None, thresholds : ndarray of shape (n_thresholds,) Increasing thresholds on the decision function used to compute - precision and recall. n_thresgolds <= len(np.unique(probas_pred)). + precision and recall. n_thresholds <= len(np.unique(probas_pred)). See also -------- average_precision_score : Compute average precision from prediction scores - detection_error_tradeoff_curve: Compute error rates for different \ - probability thresholds + det_curve: Compute error rates for different probability thresholds roc_curve : Compute Receiver operating characteristic (ROC) curve @@ -846,8 +844,7 @@ def roc_curve(y_true, y_score, *, pos_label=None, sample_weight=None, See Also -------- - detection_error_tradeoff_curve: Compute error rates for different \ - probability thresholds + det_curve: Compute error rates for different probability thresholds roc_auc_score : Compute the area under the ROC curve
diff --git a/sklearn/metrics/_plot/tests/test_plot_curve_common.py b/sklearn/metrics/_plot/tests/test_plot_curve_common.py new file mode 100644 index 0000000000000..c3b56f1724372 --- /dev/null +++ b/sklearn/metrics/_plot/tests/test_plot_curve_common.py @@ -0,0 +1,103 @@ +import pytest + +from sklearn.base import ClassifierMixin +from sklearn.base import clone +from sklearn.compose import make_column_transformer +from sklearn.datasets import load_iris +from sklearn.exceptions import NotFittedError +from sklearn.linear_model import LogisticRegression +from sklearn.pipeline import make_pipeline +from sklearn.preprocessing import StandardScaler +from sklearn.tree import DecisionTreeClassifier + +from sklearn.metrics import plot_det_curve +from sklearn.metrics import plot_roc_curve + + [email protected](scope="module") +def data(): + return load_iris(return_X_y=True) + + [email protected](scope="module") +def data_binary(data): + X, y = data + return X[y < 2], y[y < 2] + + [email protected]("plot_func", [plot_det_curve, plot_roc_curve]) +def test_plot_curve_error_non_binary(pyplot, data, plot_func): + X, y = data + clf = DecisionTreeClassifier() + clf.fit(X, y) + + msg = "DecisionTreeClassifier should be a binary classifier" + with pytest.raises(ValueError, match=msg): + plot_func(clf, X, y) + + [email protected]( + "response_method, msg", + [("predict_proba", "response method predict_proba is not defined in " + "MyClassifier"), + ("decision_function", "response method decision_function is not defined " + "in MyClassifier"), + ("auto", "response method decision_function or predict_proba is not " + "defined in MyClassifier"), + ("bad_method", "response_method must be 'predict_proba', " + "'decision_function' or 'auto'")] +) [email protected]("plot_func", [plot_det_curve, plot_roc_curve]) +def test_plot_curve_error_no_response( + pyplot, data_binary, response_method, msg, plot_func, +): + X, y = data_binary + + class MyClassifier(ClassifierMixin): + def fit(self, X, y): + self.classes_ = [0, 1] + return self + + clf = MyClassifier().fit(X, y) + + with pytest.raises(ValueError, match=msg): + plot_func(clf, X, y, response_method=response_method) + + [email protected]("plot_func", [plot_det_curve, plot_roc_curve]) +def test_plot_curve_estimator_name_multiple_calls( + pyplot, data_binary, plot_func +): + # non-regression test checking that the `name` used when calling + # `plot_func` is used as well when calling `disp.plot()` + X, y = data_binary + clf_name = "my hand-crafted name" + clf = LogisticRegression().fit(X, y) + disp = plot_func(clf, X, y, name=clf_name) + assert disp.estimator_name == clf_name + pyplot.close("all") + disp.plot() + assert clf_name in disp.line_.get_label() + pyplot.close("all") + clf_name = "another_name" + disp.plot(name=clf_name) + assert clf_name in disp.line_.get_label() + + [email protected]( + "clf", [LogisticRegression(), + make_pipeline(StandardScaler(), LogisticRegression()), + make_pipeline(make_column_transformer((StandardScaler(), [0, 1])), + LogisticRegression())]) [email protected]("plot_func", [plot_det_curve, plot_roc_curve]) +def test_plot_det_curve_not_fitted_errors(pyplot, data_binary, clf, plot_func): + X, y = data_binary + # clone since we parametrize the test and the classifier will be fitted + # when testing the second and subsequent plotting function + model = clone(clf) + with pytest.raises(NotFittedError): + plot_func(model, X, y) + model.fit(X, y) + disp = plot_func(model, X, y) + assert model.__class__.__name__ in disp.line_.get_label() + assert disp.estimator_name == model.__class__.__name__ diff --git a/sklearn/metrics/_plot/tests/test_plot_det_curve.py b/sklearn/metrics/_plot/tests/test_plot_det_curve.py new file mode 100644 index 0000000000000..9ef10237af879 --- /dev/null +++ b/sklearn/metrics/_plot/tests/test_plot_det_curve.py @@ -0,0 +1,84 @@ +import pytest +import numpy as np +from numpy.testing import assert_allclose + +from sklearn.datasets import load_iris +from sklearn.linear_model import LogisticRegression + +from sklearn.metrics import det_curve +from sklearn.metrics import plot_det_curve + + [email protected](scope="module") +def data(): + return load_iris(return_X_y=True) + + [email protected](scope="module") +def data_binary(data): + X, y = data + return X[y < 2], y[y < 2] + + [email protected]( + "response_method", ["predict_proba", "decision_function"] +) [email protected]("with_sample_weight", [True, False]) [email protected]("with_strings", [True, False]) +def test_plot_det_curve( + pyplot, + response_method, + data_binary, + with_sample_weight, + with_strings +): + X, y = data_binary + + pos_label = None + if with_strings: + y = np.array(["c", "b"])[y] + pos_label = "c" + + if with_sample_weight: + rng = np.random.RandomState(42) + sample_weight = rng.randint(1, 4, size=(X.shape[0])) + else: + sample_weight = None + + lr = LogisticRegression() + lr.fit(X, y) + + viz = plot_det_curve( + lr, X, y, alpha=0.8, sample_weight=sample_weight, + ) + + y_pred = getattr(lr, response_method)(X) + if y_pred.ndim == 2: + y_pred = y_pred[:, 1] + + fpr, fnr, _ = det_curve( + y, y_pred, sample_weight=sample_weight, pos_label=pos_label, + ) + + assert_allclose(viz.fpr, fpr) + assert_allclose(viz.fnr, fnr) + + assert viz.estimator_name == "LogisticRegression" + + # cannot fail thanks to pyplot fixture + import matplotlib as mpl # noqal + assert isinstance(viz.line_, mpl.lines.Line2D) + assert viz.line_.get_alpha() == 0.8 + assert isinstance(viz.ax_, mpl.axes.Axes) + assert isinstance(viz.figure_, mpl.figure.Figure) + assert viz.line_.get_label() == "LogisticRegression" + + expected_pos_label = 1 if pos_label is None else pos_label + expected_ylabel = ( + f"False Negative Rate (Positive label: {expected_pos_label})" + ) + expected_xlabel = ( + f"False Positive Rate (Positive label: {expected_pos_label})" + ) + assert viz.ax_.get_ylabel() == expected_ylabel + assert viz.ax_.get_xlabel() == expected_xlabel diff --git a/sklearn/metrics/_plot/tests/test_plot_roc_curve.py b/sklearn/metrics/_plot/tests/test_plot_roc_curve.py index 76b7024f0dc7c..de5a23d81af19 100644 --- a/sklearn/metrics/_plot/tests/test_plot_roc_curve.py +++ b/sklearn/metrics/_plot/tests/test_plot_roc_curve.py @@ -2,7 +2,6 @@ import numpy as np from numpy.testing import assert_allclose -from sklearn.tree import DecisionTreeClassifier from sklearn.metrics import plot_roc_curve from sklearn.metrics import RocCurveDisplay from sklearn.metrics import roc_curve @@ -11,7 +10,6 @@ from sklearn.datasets import load_breast_cancer from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split -from sklearn.base import ClassifierMixin from sklearn.exceptions import NotFittedError from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler @@ -34,42 +32,6 @@ def data_binary(data): X, y = data return X[y < 2], y[y < 2] - -def test_plot_roc_curve_error_non_binary(pyplot, data): - X, y = data - clf = DecisionTreeClassifier() - clf.fit(X, y) - - msg = "DecisionTreeClassifier should be a binary classifier" - with pytest.raises(ValueError, match=msg): - plot_roc_curve(clf, X, y) - - [email protected]( - "response_method, msg", - [("predict_proba", "response method predict_proba is not defined in " - "MyClassifier"), - ("decision_function", "response method decision_function is not defined " - "in MyClassifier"), - ("auto", "response method decision_function or predict_proba is not " - "defined in MyClassifier"), - ("bad_method", "response_method must be 'predict_proba', " - "'decision_function' or 'auto'")]) -def test_plot_roc_curve_error_no_response(pyplot, data_binary, response_method, - msg): - X, y = data_binary - - class MyClassifier(ClassifierMixin): - def fit(self, X, y): - self.classes_ = [0, 1] - return self - - clf = MyClassifier().fit(X, y) - - with pytest.raises(ValueError, match=msg): - plot_roc_curve(clf, X, y, response_method=response_method) - - @pytest.mark.parametrize("response_method", ["predict_proba", "decision_function"]) @pytest.mark.parametrize("with_sample_weight", [True, False]) @@ -146,23 +108,6 @@ def test_roc_curve_not_fitted_errors(pyplot, data_binary, clf): assert disp.estimator_name == clf.__class__.__name__ -def test_plot_roc_curve_estimator_name_multiple_calls(pyplot, data_binary): - # non-regression test checking that the `name` used when calling - # `plot_roc_curve` is used as well when calling `disp.plot()` - X, y = data_binary - clf_name = "my hand-crafted name" - clf = LogisticRegression().fit(X, y) - disp = plot_roc_curve(clf, X, y, name=clf_name) - assert disp.estimator_name == clf_name - pyplot.close("all") - disp.plot() - assert clf_name in disp.line_.get_label() - pyplot.close("all") - clf_name = "another_name" - disp.plot(name=clf_name) - assert clf_name in disp.line_.get_label() - - @pytest.mark.parametrize( "roc_auc, estimator_name, expected_label", [ diff --git a/sklearn/metrics/tests/test_common.py b/sklearn/metrics/tests/test_common.py index 24f01d46610a7..5a8e4b3f69d8c 100644 --- a/sklearn/metrics/tests/test_common.py +++ b/sklearn/metrics/tests/test_common.py @@ -29,7 +29,7 @@ from sklearn.metrics import cohen_kappa_score from sklearn.metrics import confusion_matrix from sklearn.metrics import coverage_error -from sklearn.metrics import detection_error_tradeoff_curve +from sklearn.metrics import det_curve from sklearn.metrics import explained_variance_score from sklearn.metrics import f1_score from sklearn.metrics import fbeta_score @@ -206,7 +206,7 @@ def precision_recall_curve_padded_thresholds(*args, **kwargs): CURVE_METRICS = { "roc_curve": roc_curve, "precision_recall_curve": precision_recall_curve_padded_thresholds, - "detection_error_tradeoff_curve": detection_error_tradeoff_curve, + "det_curve": det_curve, } THRESHOLDED_METRICS = { @@ -303,7 +303,7 @@ def precision_recall_curve_padded_thresholds(*args, **kwargs): # curves "roc_curve", "precision_recall_curve", - "detection_error_tradeoff_curve", + "det_curve", } # Metric undefined with "binary" or "multiclass" input @@ -325,7 +325,7 @@ def precision_recall_curve_padded_thresholds(*args, **kwargs): METRICS_WITH_POS_LABEL = { "roc_curve", "precision_recall_curve", - "detection_error_tradeoff_curve", + "det_curve", "brier_score_loss", @@ -356,7 +356,7 @@ def precision_recall_curve_padded_thresholds(*args, **kwargs): "normalized_confusion_matrix", "roc_curve", "precision_recall_curve", - "detection_error_tradeoff_curve", + "det_curve", "precision_score", "recall_score", "f1_score", "f2_score", "f0.5_score", "jaccard_score", @@ -469,7 +469,7 @@ def precision_recall_curve_padded_thresholds(*args, **kwargs): "normalized_confusion_matrix", "roc_curve", "precision_recall_curve", - "detection_error_tradeoff_curve", + "det_curve", "precision_score", "recall_score", "f2_score", "f0.5_score", diff --git a/sklearn/metrics/tests/test_ranking.py b/sklearn/metrics/tests/test_ranking.py index 02d19aea1236c..166ff775e2690 100644 --- a/sklearn/metrics/tests/test_ranking.py +++ b/sklearn/metrics/tests/test_ranking.py @@ -22,7 +22,7 @@ from sklearn.metrics import auc from sklearn.metrics import average_precision_score from sklearn.metrics import coverage_error -from sklearn.metrics import detection_error_tradeoff_curve +from sklearn.metrics import det_curve from sklearn.metrics import label_ranking_average_precision_score from sklearn.metrics import precision_recall_curve from sklearn.metrics import label_ranking_loss @@ -949,10 +949,10 @@ def test_score_scale_invariance(): ([1, 0, 1], [0.5, 0.75, 1], [1, 1, 0], [0, 0.5, 0.5]), ([1, 0, 1], [0.25, 0.5, 0.75], [1, 1, 0], [0, 0.5, 0.5]), ]) -def test_detection_error_tradeoff_curve_toydata(y_true, y_score, +def test_det_curve_toydata(y_true, y_score, expected_fpr, expected_fnr): # Check on a batch of small examples. - fpr, fnr, _ = detection_error_tradeoff_curve(y_true, y_score) + fpr, fnr, _ = det_curve(y_true, y_score) assert_allclose(fpr, expected_fpr) assert_allclose(fnr, expected_fnr) @@ -968,20 +968,20 @@ def test_detection_error_tradeoff_curve_toydata(y_true, y_score, ([1, 0, 1], [0.25, 0.5, 0.5], [1], [0]), ([1, 1, 0], [0.25, 0.5, 0.5], [1], [0]), ]) -def test_detection_error_tradeoff_curve_tie_handling(y_true, y_score, +def test_det_curve_tie_handling(y_true, y_score, expected_fpr, expected_fnr): - fpr, fnr, _ = detection_error_tradeoff_curve(y_true, y_score) + fpr, fnr, _ = det_curve(y_true, y_score) assert_allclose(fpr, expected_fpr) assert_allclose(fnr, expected_fnr) -def test_detection_error_tradeoff_curve_sanity_check(): +def test_det_curve_sanity_check(): # Exactly duplicated inputs yield the same result. assert_allclose( - detection_error_tradeoff_curve([0, 0, 1], [0, 0.5, 1]), - detection_error_tradeoff_curve( + det_curve([0, 0, 1], [0, 0.5, 1]), + det_curve( [0, 0, 0, 0, 1, 1], [0, 0, 0.5, 0.5, 1, 1]) ) @@ -989,8 +989,8 @@ def test_detection_error_tradeoff_curve_sanity_check(): @pytest.mark.parametrize("y_score", [ (0), (0.25), (0.5), (0.75), (1) ]) -def test_detection_error_tradeoff_curve_constant_scores(y_score): - fpr, fnr, threshold = detection_error_tradeoff_curve( +def test_det_curve_constant_scores(y_score): + fpr, fnr, threshold = det_curve( y_true=[0, 1, 0, 1, 0, 1], y_score=np.full(6, y_score) ) @@ -1007,8 +1007,8 @@ def test_detection_error_tradeoff_curve_constant_scores(y_score): ([0, 0, 1, 1, 1, 1]), ([0, 1, 1, 1, 1, 1]), ]) -def test_detection_error_tradeoff_curve_perfect_scores(y_true): - fpr, fnr, _ = detection_error_tradeoff_curve( +def test_det_curve_perfect_scores(y_true): + fpr, fnr, _ = det_curve( y_true=y_true, y_score=y_true ) @@ -1031,13 +1031,13 @@ def test_detection_error_tradeoff_curve_perfect_scores(y_true): ), ], ) -def test_detection_error_tradeoff_curve_bad_input(y_true, y_pred, err_msg): +def test_det_curve_bad_input(y_true, y_pred, err_msg): # input variables with inconsistent numbers of samples with pytest.raises(ValueError, match=err_msg): - detection_error_tradeoff_curve(y_true, y_pred) + det_curve(y_true, y_pred) -def test_detection_error_tradeoff_curve_pos_label(): +def test_det_curve_pos_label(): y_true = ["cancer"] * 3 + ["not cancer"] * 7 y_pred_pos_not_cancer = np.array( [0.1, 0.4, 0.6, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.9] @@ -1045,11 +1045,11 @@ def test_detection_error_tradeoff_curve_pos_label(): y_pred_pos_cancer = 1 - y_pred_pos_not_cancer fpr_pos_cancer, fnr_pos_cancer, th_pos_cancer = \ - detection_error_tradeoff_curve( + det_curve( y_true, y_pred_pos_cancer, pos_label="cancer", ) fpr_pos_not_cancer, fnr_pos_not_cancer, th_pos_not_cancer = \ - detection_error_tradeoff_curve( + det_curve( y_true, y_pred_pos_not_cancer, pos_label="not cancer", )
[ { "path": "doc/modules/classes.rst", "old_path": "a/doc/modules/classes.rst", "new_path": "b/doc/modules/classes.rst", "metadata": "diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst\nindex f5a0e71e07d1c..2ec617df85cc0 100644\n--- a/doc/modules/classes.rst\n+++ b/doc/modules/classes.rst\n@@ -947,7 +947,7 @@ details.\n metrics.cohen_kappa_score\n metrics.confusion_matrix\n metrics.dcg_score\n- metrics.detection_error_tradeoff_curve\n+ metrics.det_curve\n metrics.f1_score\n metrics.fbeta_score\n metrics.hamming_loss\n@@ -1100,6 +1100,7 @@ See the :ref:`visualizations` section of the user guide for further details.\n :template: function.rst\n \n metrics.plot_confusion_matrix\n+ metrics.plot_det_curve\n metrics.plot_precision_recall_curve\n metrics.plot_roc_curve\n \n@@ -1108,6 +1109,7 @@ See the :ref:`visualizations` section of the user guide for further details.\n :template: class.rst\n \n metrics.ConfusionMatrixDisplay\n+ metrics.DetCurveDisplay\n metrics.PrecisionRecallDisplay\n metrics.RocCurveDisplay\n \n" }, { "path": "doc/modules/model_evaluation.rst", "old_path": "a/doc/modules/model_evaluation.rst", "new_path": "b/doc/modules/model_evaluation.rst", "metadata": "diff --git a/doc/modules/model_evaluation.rst b/doc/modules/model_evaluation.rst\nindex e64aee2075e06..58c30d3091830 100644\n--- a/doc/modules/model_evaluation.rst\n+++ b/doc/modules/model_evaluation.rst\n@@ -306,7 +306,7 @@ Some of these are restricted to the binary classification case:\n \n precision_recall_curve\n roc_curve\n- detection_error_tradeoff_curve\n+ det_curve\n \n \n Others also work in the multiclass case:\n@@ -1443,7 +1443,7 @@ to the given limit.\n Detection error tradeoff (DET)\n ------------------------------\n \n-The function :func:`detection_error_tradeoff_curve` computes the\n+The function :func:`det_curve` computes the\n detection error tradeoff curve (DET) curve [WikipediaDET2017]_.\n Quoting Wikipedia:\n \n" }, { "path": "doc/visualizations.rst", "old_path": "a/doc/visualizations.rst", "new_path": "b/doc/visualizations.rst", "metadata": "diff --git a/doc/visualizations.rst b/doc/visualizations.rst\nindex ad316205b3c90..a2d40408b403f 100644\n--- a/doc/visualizations.rst\n+++ b/doc/visualizations.rst\n@@ -78,6 +78,7 @@ Functions\n \n inspection.plot_partial_dependence\n metrics.plot_confusion_matrix\n+ metrics.plot_det_curve\n metrics.plot_precision_recall_curve\n metrics.plot_roc_curve\n \n@@ -91,5 +92,6 @@ Display Objects\n \n inspection.PartialDependenceDisplay\n metrics.ConfusionMatrixDisplay\n+ metrics.DetCurveDisplay\n metrics.PrecisionRecallDisplay\n metrics.RocCurveDisplay\n" }, { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex aaf86a2f0576d..1da9670307b75 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -280,11 +280,15 @@ Changelog\n :mod:`sklearn.metrics`\n ......................\n \n-- |Feature| Added :func:`metrics.detection_error_tradeoff_curve` to compute\n- Detection Error Tradeoff curve classification metric.\n+- |Feature| Added :func:`metrics.det_curve` to compute Detection Error Tradeoff\n+ curve classification metric.\n :pr:`10591` by :user:`Jeremy Karnowski <jkarnows>` and\n :user:`Daniel Mohns <dmohns>`.\n \n+- |Feature| Added :func:`metrics.plot_det_curve` and :class:`DetCurveDisplay`\n+ to ease the plot of DET curves.\n+ :pr:`18176` by :user:`Guillaume Lemaitre <glemaitre>`.\n+\n - |Feature| Added :func:`metrics.mean_absolute_percentage_error` metric and\n the associated scorer for regression problems. :issue:`10708` fixed with the\n PR :pr:`15007` by :user:`Ashutosh Hathidara <ashutosh1919>`. The scorer and\n" } ]
0.24
bf4714f40113ac4e6045d34d89905f146c5274b3
[ "sklearn/metrics/_plot/tests/test_plot_roc_curve.py::test_plot_roc_curve[True-False-True-predict_proba]", "sklearn/metrics/_plot/tests/test_plot_roc_curve.py::test_plot_roc_curve[False-True-False-decision_function]", "sklearn/metrics/_plot/tests/test_plot_roc_curve.py::test_plot_roc_curve[True-False-True-decision_function]", "sklearn/metrics/_plot/tests/test_plot_roc_curve.py::test_plot_roc_curve[True-False-False-decision_function]", "sklearn/metrics/_plot/tests/test_plot_roc_curve.py::test_default_labels[None-my_est-my_est]", "sklearn/metrics/_plot/tests/test_plot_roc_curve.py::test_roc_curve_not_fitted_errors[clf0]", "sklearn/metrics/_plot/tests/test_plot_roc_curve.py::test_plot_roc_curve_pos_label[decision_function]", "sklearn/metrics/_plot/tests/test_plot_roc_curve.py::test_plot_roc_curve[True-True-False-predict_proba]", "sklearn/metrics/_plot/tests/test_plot_roc_curve.py::test_roc_curve_not_fitted_errors[clf2]", "sklearn/metrics/_plot/tests/test_plot_roc_curve.py::test_roc_curve_not_fitted_errors[clf1]", "sklearn/metrics/_plot/tests/test_plot_roc_curve.py::test_plot_roc_curve[True-True-True-decision_function]", "sklearn/metrics/_plot/tests/test_plot_roc_curve.py::test_default_labels[0.8-my_est2-my_est2 (AUC = 0.80)]", "sklearn/metrics/_plot/tests/test_plot_roc_curve.py::test_plot_roc_curve[False-False-True-decision_function]", "sklearn/metrics/_plot/tests/test_plot_roc_curve.py::test_plot_roc_curve[False-False-True-predict_proba]", "sklearn/metrics/_plot/tests/test_plot_roc_curve.py::test_plot_roc_curve[True-False-False-predict_proba]", "sklearn/metrics/_plot/tests/test_plot_roc_curve.py::test_plot_roc_curve[False-True-False-predict_proba]", "sklearn/metrics/_plot/tests/test_plot_roc_curve.py::test_plot_roc_curve[False-False-False-predict_proba]", "sklearn/metrics/_plot/tests/test_plot_roc_curve.py::test_default_labels[0.9-None-AUC = 0.90]", "sklearn/metrics/_plot/tests/test_plot_roc_curve.py::test_plot_roc_curve[True-True-False-decision_function]", "sklearn/metrics/_plot/tests/test_plot_roc_curve.py::test_plot_roc_curve[False-False-False-decision_function]", "sklearn/metrics/_plot/tests/test_plot_roc_curve.py::test_plot_roc_curve[False-True-True-decision_function]", "sklearn/metrics/_plot/tests/test_plot_roc_curve.py::test_plot_roc_curve[False-True-True-predict_proba]", "sklearn/metrics/_plot/tests/test_plot_roc_curve.py::test_plot_roc_curve[True-True-True-predict_proba]", "sklearn/metrics/_plot/tests/test_plot_roc_curve.py::test_plot_roc_curve_pos_label[predict_proba]" ]
[ "sklearn/metrics/tests/test_common.py::test_single_sample[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[samples_f2_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-Number of given labels, 2, not equal to the number of columns in 'y_score', 3-y_true4-labels4]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[r2_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_error[Partial AUC computation not available in multiclass setting, 'max_fpr' must be set to `None`, received `max_fpr=0.5` instead-kwargs3]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[hinge_loss]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[dcg_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_recall_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-Parameter 'labels' must be unique-y_true0-labels0]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[samples_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[macro_f1_score]", "sklearn/metrics/tests/test_ranking.py::test_dcg_score", "sklearn/metrics/_plot/tests/test_plot_det_curve.py::test_plot_det_curve[True-False-decision_function]", "sklearn/metrics/tests/test_common.py::test_single_sample[r2_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_zeroes[f1_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[f0.5_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric7]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[normalized_confusion_matrix]", "sklearn/metrics/tests/test_ranking.py::test_precision_recall_curve_errors", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[micro_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[max_error]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true13-y_score13-expected_fpr13-expected_fnr13]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[coverage_error]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[log_loss]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[weighted_roc_auc]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[dcg_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[metric17]", "sklearn/metrics/_plot/tests/test_plot_det_curve.py::test_plot_det_curve[True-True-decision_function]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[matthews_corrcoef_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric19]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[unnormalized_log_loss]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve_hard", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric18]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[metric11]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[roc_auc_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[samples_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_roc_auc]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric20]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[weighted_recall_score]", "sklearn/metrics/_plot/tests/test_plot_curve_common.py::test_plot_curve_error_no_response[plot_det_curve-decision_function-response method decision_function is not defined in MyClassifier]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[weighted_f0.5_score]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true16-y_score16-expected_fpr16-expected_fnr16]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_tie_handling[y_true4-y_score4-expected_fpr4-expected_fnr4]", "sklearn/metrics/tests/test_common.py::test_averaging_multiclass[recall_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[weighted_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_averaging_multiclass[f0.5_score]", "sklearn/metrics/tests/test_ranking.py::test_precision_recall_curve_toydata", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[weighted_ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_single_sample[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric32]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[metric8]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_ones[f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric27]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[partial_roc_auc]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true19-y_score19-expected_fpr19-expected_fnr19]", "sklearn/metrics/_plot/tests/test_plot_curve_common.py::test_plot_curve_error_no_response[plot_det_curve-predict_proba-response method predict_proba is not defined in MyClassifier]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[micro_roc_auc]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[log_loss]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[recall_score]", "sklearn/metrics/tests/test_common.py::test_normalize_option_binary_classification[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[macro_precision_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-Number of given labels, 2, not equal to the number of columns in 'y_score', 3-y_true4-labels4]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[macro_jaccard_score]", "sklearn/metrics/_plot/tests/test_plot_curve_common.py::test_plot_curve_estimator_name_multiple_calls[plot_det_curve]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve[False]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_constant_scores[1]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[samples_roc_auc]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_f0.5_score]", "sklearn/metrics/_plot/tests/test_plot_curve_common.py::test_plot_det_curve_not_fitted_errors[plot_det_curve-clf0]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[f1_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_ovo_roc_auc]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-Number of classes in y_true not equal to the number of columns in 'y_score'-y_true2-None]", "sklearn/metrics/_plot/tests/test_plot_curve_common.py::test_plot_det_curve_not_fitted_errors[plot_det_curve-clf2]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[macro_f2_score]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true3-y_score3-expected_fpr3-expected_fnr3]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_zeroes[precision_score]", "sklearn/metrics/_plot/tests/test_plot_curve_common.py::test_plot_curve_error_non_binary[plot_det_curve]", "sklearn/metrics/_plot/tests/test_plot_curve_common.py::test_plot_curve_error_no_response[plot_roc_curve-bad_method-response_method must be 'predict_proba', 'decision_function' or 'auto']", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric3]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[samples_recall_score]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_normal_deviance]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[mean_absolute_error]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-'y_true' contains labels not in parameter 'labels'-y_true8-labels8]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true0-y_score0-expected_fpr0-expected_fnr0]", "sklearn/metrics/tests/test_ranking.py::test_ndcg_toy_examples[True]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[hinge_loss]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-Number of given labels, 2, not equal to the number of columns in 'y_score', 3-y_true5-labels5]", "sklearn/metrics/_plot/tests/test_plot_curve_common.py::test_plot_det_curve_not_fitted_errors[plot_roc_curve-clf1]", "sklearn/metrics/_plot/tests/test_plot_curve_common.py::test_plot_curve_error_no_response[plot_roc_curve-decision_function-response method decision_function is not defined in MyClassifier]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[log_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[mean_absolute_error]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_perfect_scores[y_true2]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[dcg_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[ndcg_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[micro_roc_auc]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve_drop_intermediate", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[samples_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[macro_f2_score]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_bad_input[y_true0-y_pred0-inconsistent numbers of samples]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_f1_score]", "sklearn/metrics/tests/test_ranking.py::test_auc", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[samples_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[partial_roc_auc]", "sklearn/metrics/tests/test_ranking.py::test_ndcg_toy_examples[False]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric39]", "sklearn/metrics/tests/test_common.py::test_normalize_option_multilabel_classification", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[weighted_ovo_roc_auc]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[f1_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_error[average must be one of \\\\('macro', 'weighted'\\\\) for multiclass problems-kwargs0]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-5-2]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_single_sample[weighted_f1_score]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovr_roc_auc_toydata[y_true3-labels3]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[weighted_precision_score]", "sklearn/metrics/tests/test_ranking.py::test_label_ranking_avp[label_ranking_average_precision_score-check_lrap_toy]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-10-1]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true9-y_score9-expected_fpr9-expected_fnr9]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve_one_label", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[micro_f0.5_score]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_constant_scores[0.75]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_bad_input[y_true1-y_pred1-inconsistent numbers of samples]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[metric29]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[zero_one_loss]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-Parameter 'labels' must be unique-y_true1-labels1]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[hinge_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[macro_jaccard_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_error[average must be one of \\\\('macro', 'weighted'\\\\) for multiclass problems-kwargs1]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric35]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[matthews_corrcoef_score]", "sklearn/metrics/tests/test_ranking.py::test_dcg_ties", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[r2_score]", "sklearn/metrics/tests/test_ranking.py::test_auc_errors", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[<lambda>]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[max_error]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_perfect_scores[y_true3]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovr_roc_auc_toydata[y_true2-labels2]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[metric32]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[brier_score_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[samples_recall_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[metric12]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovr_roc_auc_toydata[y_true1-None]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[micro_precision_score]", "sklearn/metrics/tests/test_ranking.py::test_binary_clf_curve_multiclass_error", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[recall_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[det_curve]", "sklearn/metrics/tests/test_ranking.py::test_lrap_error_raised", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance_multilabel_and_multioutput", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_f0.5_score]", "sklearn/metrics/tests/test_ranking.py::test_lrap_sample_weighting_zero_labels", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_single_sample[macro_jaccard_score]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-2-2]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[mean_normal_deviance]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_bad_input[y_true3-y_pred3-Only one class present in y_true]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[zero_one_loss]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-Number of classes in y_true not equal to the number of columns in 'y_score'-y_true2-None]", "sklearn/metrics/_plot/tests/test_plot_curve_common.py::test_plot_curve_error_no_response[plot_det_curve-auto-response method decision_function or predict_proba is not defined in MyClassifier]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_perfect_scores[y_true4]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-2-20]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[ndcg_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[hamming_loss]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-10-20]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[r2_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_f2_score]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-5-8]", "sklearn/metrics/tests/test_ranking.py::test_partial_roc_auc_score", "sklearn/metrics/tests/test_common.py::test_single_sample[matthews_corrcoef_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[metric13]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[samples_precision_score]", "sklearn/metrics/tests/test_ranking.py::test_average_precision_constant_values", "sklearn/metrics/tests/test_common.py::test_single_sample[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[ovr_roc_auc]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-'y_true' contains labels not in parameter 'labels'-y_true9-labels9]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_perfect_scores[y_true1]", "sklearn/metrics/_plot/tests/test_plot_curve_common.py::test_plot_det_curve_not_fitted_errors[plot_det_curve-clf1]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[label_ranking_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric15]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_single_sample[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[micro_f0.5_score]", "sklearn/metrics/_plot/tests/test_plot_curve_common.py::test_plot_det_curve_not_fitted_errors[plot_roc_curve-clf2]", "sklearn/metrics/_plot/tests/test_plot_det_curve.py::test_plot_det_curve[False-False-predict_proba]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-5-1]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[samples_average_precision_score]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_tie_handling[y_true1-y_score1-expected_fpr1-expected_fnr1]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[metric14]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true7-y_score7-expected_fpr7-expected_fnr7]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[metric9]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[micro_f0.5_score]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-5-20]", "sklearn/metrics/tests/test_common.py::test_single_sample[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric23]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_ones[f2_score]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_tie_handling[y_true6-y_score6-expected_fpr6-expected_fnr6]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[log_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[label_ranking_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[log_loss]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_symmetry_consistency", "sklearn/metrics/tests/test_common.py::test_single_sample[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[f0.5_score]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovo_roc_auc_toydata[y_true3-None]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[average_precision_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[micro_precision_score]", "sklearn/metrics/tests/test_ranking.py::test_average_precision_score_pos_label_errors", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_compound_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true17-y_score17-expected_fpr17-expected_fnr17]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true6-y_score6-expected_fpr6-expected_fnr6]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_zeroes[recall_score]", "sklearn/metrics/tests/test_common.py::test_normalize_option_multiclass_classification[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric38]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[samples_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[matthews_corrcoef_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[average_precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[dcg_score]", "sklearn/metrics/_plot/tests/test_plot_det_curve.py::test_plot_det_curve[False-True-predict_proba]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[samples_recall_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_average_precision_score]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_perfect_scores[y_true0]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric26]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-Number of given labels, 4, not equal to the number of columns in 'y_score', 3-y_true6-labels6]", "sklearn/metrics/tests/test_common.py::test_single_sample[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true5-y_score5-expected_fpr5-expected_fnr5]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[samples_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[ovo_roc_auc]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[median_absolute_error]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_error[sample_weight is not supported for multiclass one-vs-one ROC AUC, 'sample_weight' must be None in this case-kwargs2]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[metric28]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric34]", "sklearn/metrics/tests/test_common.py::test_single_sample[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_single_sample[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric41]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_zeroes[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_roc_auc]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_ones[f1_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[samples_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[precision_recall_curve]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-'y_true' contains labels not in parameter 'labels'-y_true8-labels8]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[coverage_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[average_precision_score]", "sklearn/metrics/tests/test_ranking.py::test_ndcg_score", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[hinge_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[unnormalized_log_loss]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-Parameter 'labels' must be unique-y_true0-labels0]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric25]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[precision_recall_curve]", "sklearn/metrics/_plot/tests/test_plot_curve_common.py::test_plot_curve_estimator_name_multiple_calls[plot_roc_curve]", "sklearn/metrics/_plot/tests/test_plot_det_curve.py::test_plot_det_curve[True-False-predict_proba]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[zero_one_loss]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-2-1]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_jaccard_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-Number of given labels, 4, not equal to the number of columns in 'y_score', 3-y_true7-labels7]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[unnormalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[hinge_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric40]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[average_precision_score]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true18-y_score18-expected_fpr18-expected_fnr18]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_poisson_deviance]", "sklearn/metrics/tests/test_ranking.py::test_auc_score_non_binary_class", "sklearn/metrics/tests/test_common.py::test_single_sample[explained_variance_score]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_bad_input[y_true2-y_pred2-Only one class present in y_true]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_roc_auc]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_single_sample[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_f1_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multiclass[f2_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[accuracy_score]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true12-y_score12-expected_fpr12-expected_fnr12]", "sklearn/metrics/tests/test_ranking.py::test_label_ranking_avp[label_ranking_average_precision_score-check_zero_or_all_relevant_labels]", "sklearn/metrics/tests/test_ranking.py::test_label_ranking_avp[_my_lrap-check_lrap_without_tie_and_increasing_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric29]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[weighted_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[label_ranking_average_precision_score]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovo_roc_auc_toydata_binary[y_true0-labels0]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[brier_score_loss]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[matthews_corrcoef_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[f2_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric10]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric37]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[label_ranking_loss]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[samples_roc_auc]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[mean_absolute_error]", "sklearn/metrics/tests/test_ranking.py::test_label_ranking_avp[label_ranking_average_precision_score-check_lrap_only_ties]", "sklearn/metrics/_plot/tests/test_plot_curve_common.py::test_plot_curve_error_no_response[plot_det_curve-bad_method-response_method must be 'predict_proba', 'decision_function' or 'auto']", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[hinge_loss]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_normal_deviance]", "sklearn/metrics/_plot/tests/test_plot_det_curve.py::test_plot_det_curve[False-True-decision_function]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-Number of given labels, 2, not equal to the number of columns in 'y_score', 3-y_true5-labels5]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true14-y_score14-expected_fpr14-expected_fnr14]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[metric7]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[weighted_ovo_roc_auc]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[r2_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[micro_average_precision_score]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovo_roc_auc_toydata_binary[y_true1-labels1]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[mean_compound_poisson_deviance]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-2-8]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[average_precision_score]", "sklearn/metrics/_plot/tests/test_plot_det_curve.py::test_plot_det_curve[True-True-predict_proba]", "sklearn/metrics/tests/test_common.py::test_single_sample[zero_one_loss]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-Parameter 'labels' must be ordered-y_true3-labels3]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[recall_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve_toydata", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[matthews_corrcoef_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve_multi", "sklearn/metrics/tests/test_ranking.py::test_det_curve_tie_handling[y_true2-y_score2-expected_fpr2-expected_fnr2]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[metric18]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[samples_roc_auc]", "sklearn/metrics/tests/test_common.py::test_averaging_multiclass[precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric30]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_recall_score]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true1-y_score1-expected_fpr1-expected_fnr1]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[label_ranking_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[hinge_loss]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[coverage_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric31]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[weighted_roc_auc]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[log_loss]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_normal_deviance]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[balanced_accuracy_score]", "sklearn/metrics/tests/test_ranking.py::test_ranking_appropriate_input_shape", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[roc_auc_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[samples_f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[metric16]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_sanity_check", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[zero_one_loss]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve_confidence", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_compound_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[cohen_kappa_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-Number of given labels, 4, not equal to the number of columns in 'y_score', 3-y_true6-labels6]", "sklearn/metrics/tests/test_common.py::test_averaging_binary_multilabel_all_zeroes", "sklearn/metrics/tests/test_ranking.py::test_label_ranking_loss", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_recall_score]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_constant_scores[0.25]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[samples_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_roc_auc]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[weighted_f1_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve[True]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[samples_f2_score]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[r2_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[partial_roc_auc]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_f1_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[roc_auc_score]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_constant_scores[0]", "sklearn/metrics/tests/test_ranking.py::test_coverage_error", "sklearn/metrics/tests/test_ranking.py::test_det_curve_pos_label", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true8-y_score8-expected_fpr8-expected_fnr8]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[roc_auc_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-Parameter 'labels' must be unique-y_true1-labels1]", "sklearn/metrics/tests/test_ranking.py::test_label_ranking_avp[_my_lrap-check_lrap_toy]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[max_error]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[brier_score_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[r2_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[weighted_ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric21]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[micro_f1_score]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-10-8]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_precision_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_error[multi_class must be in \\\\('ovo', 'ovr'\\\\)-kwargs5]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[log_loss]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[ovo_roc_auc]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[macro_f2_score]", "sklearn/metrics/tests/test_ranking.py::test_label_ranking_avp[_my_lrap-check_lrap_only_ties]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_tie_handling[y_true3-y_score3-expected_fpr3-expected_fnr3]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[micro_recall_score]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovo_roc_auc_toydata[y_true0-labels0]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_ranking.py::test_binary_clf_curve_implicit_pos_label[roc_curve]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_error[multi_class='ovp' is not supported for multiclass ROC AUC, multi_class must be in \\\\('ovo', 'ovr'\\\\)-kwargs4]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[roc_curve]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[ndcg_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_gamma_deviance]", "sklearn/metrics/_plot/tests/test_plot_det_curve.py::test_plot_det_curve[False-False-decision_function]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[metric10]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[log_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[micro_precision_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[f2_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric2]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_zeroes[f0.5_score]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[partial_roc_auc]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric22]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[macro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[samples_average_precision_score]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true11-y_score11-expected_fpr11-expected_fnr11]", "sklearn/metrics/tests/test_common.py::test_single_sample[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[macro_f1_score]", "sklearn/metrics/tests/test_ranking.py::test_label_ranking_avp[label_ranking_average_precision_score-check_lrap_without_tie_and_increasing_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-'y_true' contains labels not in parameter 'labels'-y_true10-labels10]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_jaccard_score]", "sklearn/metrics/tests/test_ranking.py::test_alternative_lrap_implementation[0-10-2]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_absolute_error]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_tie_handling[y_true7-y_score7-expected_fpr7-expected_fnr7]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[mean_compound_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[roc_curve]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[average_precision_score]", "sklearn/metrics/_plot/tests/test_plot_curve_common.py::test_plot_curve_error_non_binary[plot_roc_curve]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_f2_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-'y_true' contains labels not in parameter 'labels'-y_true10-labels10]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_multilabel_representation_invariance", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[unnormalized_zero_one_loss]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_zeroes[f2_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[precision_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[mean_poisson_deviance]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[micro_f2_score]", "sklearn/metrics/_plot/tests/test_plot_curve_common.py::test_plot_det_curve_not_fitted_errors[plot_roc_curve-clf0]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[samples_f1_score]", "sklearn/metrics/tests/test_common.py::test_normalize_option_binary_classification[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[median_absolute_error]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true4-y_score4-expected_fpr4-expected_fnr4]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_ones[jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[log_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[micro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_single_sample[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[cohen_kappa_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-Number of given labels, 4, not equal to the number of columns in 'y_score', 3-y_true7-labels7]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[micro_precision_score]", "sklearn/metrics/tests/test_ranking.py::test_ndcg_ignore_ties_with_k", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[mean_gamma_deviance]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[roc_auc_score]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovr_roc_auc_toydata[y_true0-None]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[partial_roc_auc]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[metric3]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_ovo_roc_auc]", "sklearn/metrics/tests/test_ranking.py::test_score_scale_invariance", "sklearn/metrics/tests/test_common.py::test_single_sample[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_f2_score]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true15-y_score15-expected_fpr15-expected_fnr15]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[hamming_loss]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_ones[precision_score]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[samples_f1_score]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[mean_squared_error]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[micro_recall_score]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovo_roc_auc_toydata[y_true1-None]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[ovo_roc_auc]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel_all_ones[recall_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[micro_f2_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[r2_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[adjusted_balanced_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_compound_poisson_deviance]", "sklearn/metrics/_plot/tests/test_plot_curve_common.py::test_plot_curve_error_no_response[plot_roc_curve-auto-response method decision_function or predict_proba is not defined in MyClassifier]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[micro_recall_score]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[mean_squared_error]", "sklearn/metrics/tests/test_ranking.py::test_ndcg_invariant", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true10-y_score10-expected_fpr10-expected_fnr10]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[accuracy_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_invariance_string_vs_numbers_labels[coverage_error]", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[matthews_corrcoef_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_absolute_percentage_error]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric16]", "sklearn/metrics/tests/test_common.py::test_averaging_multiclass[jaccard_score]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_bad_input[y_true4-y_pred4-pos_label is not specified]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[det_curve]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[macro_f2_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[hinge_loss]", "sklearn/metrics/tests/test_common.py::test_normalize_option_multiclass_classification[zero_one_loss]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_tie_handling[y_true5-y_score5-expected_fpr5-expected_fnr5]", "sklearn/metrics/tests/test_common.py::test_single_sample[mean_normal_deviance]", "sklearn/metrics/tests/test_ranking.py::test_roc_returns_consistency", "sklearn/metrics/tests/test_common.py::test_single_sample[weighted_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[label_ranking_average_precision_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[label_ranking_loss]", "sklearn/metrics/tests/test_common.py::test_multioutput_number_of_output_differ[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_roc_auc]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[normalized_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[weighted_recall_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[log_loss]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric33]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[matthews_corrcoef]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[max_error]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[micro_f1_score]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[ovr_roc_auc]", "sklearn/metrics/tests/test_ranking.py::test_ranking_loss_ties_handling", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[weighted_ovr_roc_auc]", "sklearn/metrics/tests/test_common.py::test_single_sample_multioutput[r2_score]", "sklearn/metrics/tests/test_ranking.py::test_precision_recall_curve", "sklearn/metrics/tests/test_ranking.py::test_binary_clf_curve_implicit_pos_label[precision_recall_curve]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[samples_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[samples_precision_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[unnormalized_log_loss]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[roc_auc_score]", "sklearn/metrics/tests/test_common.py::test_classification_invariance_string_vs_numbers_labels[weighted_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_raise_value_error_multilabel_sequences[samples_f2_score]", "sklearn/metrics/tests/test_common.py::test_no_averaging_labels", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[weighted_precision_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[mean_absolute_error]", "sklearn/metrics/tests/test_common.py::test_regression_sample_weight_invariance[explained_variance_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[max_error]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[macro_f1_score]", "sklearn/metrics/tests/test_common.py::test_multilabel_label_permutations_invariance[macro_f1_score]", "sklearn/metrics/tests/test_ranking.py::test_label_ranking_avp[_my_lrap-check_zero_or_all_relevant_labels]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric36]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_constant_scores[0.5]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric28]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[cohen_kappa_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[median_absolute_error]", "sklearn/metrics/tests/test_common.py::test_multioutput_regression_invariance_to_dimension_shuffling[r2_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovr-'y_true' contains labels not in parameter 'labels'-y_true9-labels9]", "sklearn/metrics/tests/test_common.py::test_single_sample[micro_f0.5_score]", "sklearn/metrics/tests/test_ranking.py::test_multiclass_ovo_roc_auc_toydata[y_true2-labels2]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_common.py::test_single_sample[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_averaging_multilabel[f2_score]", "sklearn/metrics/tests/test_common.py::test_not_symmetric_metric[macro_f2_score]", "sklearn/metrics/tests/test_ranking.py::test_roc_auc_score_multiclass_labels_error[ovo-Parameter 'labels' must be ordered-y_true3-labels3]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[samples_f2_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[median_absolute_error]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve_end_points", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[micro_precision_score]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_tie_handling[y_true0-y_score0-expected_fpr0-expected_fnr0]", "sklearn/metrics/tests/test_common.py::test_multilabel_sample_weight_invariance[weighted_f2_score]", "sklearn/metrics/_plot/tests/test_plot_curve_common.py::test_plot_curve_error_no_response[plot_roc_curve-predict_proba-response method predict_proba is not defined in MyClassifier]", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[mean_gamma_deviance]", "sklearn/metrics/tests/test_ranking.py::test_roc_curve_fpr_tpr_increasing", "sklearn/metrics/tests/test_common.py::test_regression_thresholded_inf_nan_input[ndcg_score]", "sklearn/metrics/tests/test_common.py::test_averaging_multiclass[f1_score]", "sklearn/metrics/tests/test_common.py::test_symmetric_metric[hamming_loss]", "sklearn/metrics/tests/test_ranking.py::test_det_curve_toydata[y_true2-y_score2-expected_fpr2-expected_fnr2]", "sklearn/metrics/tests/test_common.py::test_single_sample[macro_recall_score]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[macro_f0.5_score]", "sklearn/metrics/tests/test_common.py::test_thresholded_metric_permutation_invariance[ovo_roc_auc]", "sklearn/metrics/tests/test_common.py::test_sample_order_invariance[unnormalized_multilabel_confusion_matrix]", "sklearn/metrics/tests/test_common.py::test_binary_sample_weight_invariance[micro_jaccard_score]", "sklearn/metrics/tests/test_common.py::test_format_invariance_with_1d_vectors[unnormalized_accuracy_score]", "sklearn/metrics/tests/test_ranking.py::test_coverage_tie_handling", "sklearn/metrics/tests/test_common.py::test_multiclass_sample_weight_invariance[macro_precision_score]", "sklearn/metrics/tests/test_common.py::test_classification_inf_nan_input[metric24]", "sklearn/metrics/tests/test_common.py::test_thresholded_multilabel_multioutput_permutations_invariance[label_ranking_loss]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [ { "type": "field", "name": "fpr" }, { "type": "field", "name": "response_method" }, { "type": "field", "name": "line_" }, { "type": "field", "name": "figure" }, { "type": "field", "name": "fnr" }, { "type": "field", "name": "name" }, { "type": "field", "name": "self" }, { "type": "field", "name": "estimator_name" }, { "type": "field", "name": "__class__" }, { "type": "field", "name": "y_pred" }, { "type": "field", "name": "matplotlib" }, { "type": "field", "name": "X" }, { "type": "field", "name": "viz" }, { "type": "field", "name": "base" }, { "type": "field", "name": "pyplot" }, { "type": "field", "name": "__name__" }, { "type": "field", "name": "ax_" }, { "type": "field", "name": "pos_label" }, { "type": "file", "name": "sklearn/metrics/_plot/det_curve.py" }, { "type": "field", "name": "sample_weight" }, { "type": "field", "name": "figure_" } ] }
[ { "path": "doc/modules/classes.rst", "old_path": "a/doc/modules/classes.rst", "new_path": "b/doc/modules/classes.rst", "metadata": "diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst\nindex f5a0e71e07d1c..2ec617df85cc0 100644\n--- a/doc/modules/classes.rst\n+++ b/doc/modules/classes.rst\n@@ -947,7 +947,7 @@ details.\n metrics.cohen_kappa_score\n metrics.confusion_matrix\n metrics.dcg_score\n- metrics.detection_error_tradeoff_curve\n+ metrics.det_curve\n metrics.f1_score\n metrics.fbeta_score\n metrics.hamming_loss\n@@ -1100,6 +1100,7 @@ See the :ref:`visualizations` section of the user guide for further details.\n :template: function.rst\n \n metrics.plot_confusion_matrix\n+ metrics.plot_det_curve\n metrics.plot_precision_recall_curve\n metrics.plot_roc_curve\n \n@@ -1108,6 +1109,7 @@ See the :ref:`visualizations` section of the user guide for further details.\n :template: class.rst\n \n metrics.ConfusionMatrixDisplay\n+ metrics.DetCurveDisplay\n metrics.PrecisionRecallDisplay\n metrics.RocCurveDisplay\n \n" }, { "path": "doc/modules/model_evaluation.rst", "old_path": "a/doc/modules/model_evaluation.rst", "new_path": "b/doc/modules/model_evaluation.rst", "metadata": "diff --git a/doc/modules/model_evaluation.rst b/doc/modules/model_evaluation.rst\nindex e64aee2075e06..58c30d3091830 100644\n--- a/doc/modules/model_evaluation.rst\n+++ b/doc/modules/model_evaluation.rst\n@@ -306,7 +306,7 @@ Some of these are restricted to the binary classification case:\n \n precision_recall_curve\n roc_curve\n- detection_error_tradeoff_curve\n+ det_curve\n \n \n Others also work in the multiclass case:\n@@ -1443,7 +1443,7 @@ to the given limit.\n Detection error tradeoff (DET)\n ------------------------------\n \n-The function :func:`detection_error_tradeoff_curve` computes the\n+The function :func:`det_curve` computes the\n detection error tradeoff curve (DET) curve [WikipediaDET2017]_.\n Quoting Wikipedia:\n \n" }, { "path": "doc/visualizations.rst", "old_path": "a/doc/visualizations.rst", "new_path": "b/doc/visualizations.rst", "metadata": "diff --git a/doc/visualizations.rst b/doc/visualizations.rst\nindex ad316205b3c90..a2d40408b403f 100644\n--- a/doc/visualizations.rst\n+++ b/doc/visualizations.rst\n@@ -78,6 +78,7 @@ Functions\n \n inspection.plot_partial_dependence\n metrics.plot_confusion_matrix\n+ metrics.plot_det_curve\n metrics.plot_precision_recall_curve\n metrics.plot_roc_curve\n \n@@ -91,5 +92,6 @@ Display Objects\n \n inspection.PartialDependenceDisplay\n metrics.ConfusionMatrixDisplay\n+ metrics.DetCurveDisplay\n metrics.PrecisionRecallDisplay\n metrics.RocCurveDisplay\n" }, { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex aaf86a2f0576d..1da9670307b75 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -280,11 +280,15 @@ Changelog\n :mod:`sklearn.metrics`\n ......................\n \n-- |Feature| Added :func:`metrics.detection_error_tradeoff_curve` to compute\n- Detection Error Tradeoff curve classification metric.\n+- |Feature| Added :func:`metrics.det_curve` to compute Detection Error Tradeoff\n+ curve classification metric.\n :pr:`<PRID>` by :user:`<NAME>` and\n :user:`<NAME>`.\n \n+- |Feature| Added :func:`metrics.plot_det_curve` and :class:`DetCurveDisplay`\n+ to ease the plot of DET curves.\n+ :pr:`<PRID>` by :user:`<NAME>`.\n+\n - |Feature| Added :func:`metrics.mean_absolute_percentage_error` metric and\n the associated scorer for regression problems. :issue:`<PRID>` fixed with the\n PR :pr:`<PRID>` by :user:`<NAME>`. The scorer and\n" } ]
diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst index f5a0e71e07d1c..2ec617df85cc0 100644 --- a/doc/modules/classes.rst +++ b/doc/modules/classes.rst @@ -947,7 +947,7 @@ details. metrics.cohen_kappa_score metrics.confusion_matrix metrics.dcg_score - metrics.detection_error_tradeoff_curve + metrics.det_curve metrics.f1_score metrics.fbeta_score metrics.hamming_loss @@ -1100,6 +1100,7 @@ See the :ref:`visualizations` section of the user guide for further details. :template: function.rst metrics.plot_confusion_matrix + metrics.plot_det_curve metrics.plot_precision_recall_curve metrics.plot_roc_curve @@ -1108,6 +1109,7 @@ See the :ref:`visualizations` section of the user guide for further details. :template: class.rst metrics.ConfusionMatrixDisplay + metrics.DetCurveDisplay metrics.PrecisionRecallDisplay metrics.RocCurveDisplay diff --git a/doc/modules/model_evaluation.rst b/doc/modules/model_evaluation.rst index e64aee2075e06..58c30d3091830 100644 --- a/doc/modules/model_evaluation.rst +++ b/doc/modules/model_evaluation.rst @@ -306,7 +306,7 @@ Some of these are restricted to the binary classification case: precision_recall_curve roc_curve - detection_error_tradeoff_curve + det_curve Others also work in the multiclass case: @@ -1443,7 +1443,7 @@ to the given limit. Detection error tradeoff (DET) ------------------------------ -The function :func:`detection_error_tradeoff_curve` computes the +The function :func:`det_curve` computes the detection error tradeoff curve (DET) curve [WikipediaDET2017]_. Quoting Wikipedia: diff --git a/doc/visualizations.rst b/doc/visualizations.rst index ad316205b3c90..a2d40408b403f 100644 --- a/doc/visualizations.rst +++ b/doc/visualizations.rst @@ -78,6 +78,7 @@ Functions inspection.plot_partial_dependence metrics.plot_confusion_matrix + metrics.plot_det_curve metrics.plot_precision_recall_curve metrics.plot_roc_curve @@ -91,5 +92,6 @@ Display Objects inspection.PartialDependenceDisplay metrics.ConfusionMatrixDisplay + metrics.DetCurveDisplay metrics.PrecisionRecallDisplay metrics.RocCurveDisplay diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index aaf86a2f0576d..1da9670307b75 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -280,11 +280,15 @@ Changelog :mod:`sklearn.metrics` ...................... -- |Feature| Added :func:`metrics.detection_error_tradeoff_curve` to compute - Detection Error Tradeoff curve classification metric. +- |Feature| Added :func:`metrics.det_curve` to compute Detection Error Tradeoff + curve classification metric. :pr:`<PRID>` by :user:`<NAME>` and :user:`<NAME>`. +- |Feature| Added :func:`metrics.plot_det_curve` and :class:`DetCurveDisplay` + to ease the plot of DET curves. + :pr:`<PRID>` by :user:`<NAME>`. + - |Feature| Added :func:`metrics.mean_absolute_percentage_error` metric and the associated scorer for regression problems. :issue:`<PRID>` fixed with the PR :pr:`<PRID>` by :user:`<NAME>`. The scorer and If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names: [{'type': 'field', 'name': 'fpr'}, {'type': 'field', 'name': 'response_method'}, {'type': 'field', 'name': 'line_'}, {'type': 'field', 'name': 'figure'}, {'type': 'field', 'name': 'fnr'}, {'type': 'field', 'name': 'name'}, {'type': 'field', 'name': 'self'}, {'type': 'field', 'name': 'estimator_name'}, {'type': 'field', 'name': '__class__'}, {'type': 'field', 'name': 'y_pred'}, {'type': 'field', 'name': 'matplotlib'}, {'type': 'field', 'name': 'X'}, {'type': 'field', 'name': 'viz'}, {'type': 'field', 'name': 'base'}, {'type': 'field', 'name': 'pyplot'}, {'type': 'field', 'name': '__name__'}, {'type': 'field', 'name': 'ax_'}, {'type': 'field', 'name': 'pos_label'}, {'type': 'file', 'name': 'sklearn/metrics/_plot/det_curve.py'}, {'type': 'field', 'name': 'sample_weight'}, {'type': 'field', 'name': 'figure_'}]
scikit-learn/scikit-learn
scikit-learn__scikit-learn-20657
https://github.com/scikit-learn/scikit-learn/pull/20657
diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index 9cf628dfda5f5..5f50465f5aef3 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -723,6 +723,12 @@ Changelog unavailable on the basis of state, in a more readable way. :pr:`19948` by `Joel Nothman`_. +_ |Enhancement| :func:`utils.validation.check_is_fitted` now uses + ``__sklearn_is_fitted__`` if available, instead of checking for attributes ending with + an underscore. This also makes :class:`Pipeline` and + :class:`preprocessing.FunctionTransformer` pass + ``check_is_fitted(estimator)``. :pr:`20657` by `Adrin Jalali`_. + - |Fix| Fixed a bug in :func:`utils.sparsefuncs.mean_variance_axis` where the precision of the computed variance was very poor when the real variance is exactly zero. :pr:`19766` by :user:`Jérémie du Boisberranger <jeremiedbb>`. diff --git a/sklearn/pipeline.py b/sklearn/pipeline.py index 0814632721ba4..35f0fa3768b45 100644 --- a/sklearn/pipeline.py +++ b/sklearn/pipeline.py @@ -26,7 +26,9 @@ from .utils.deprecation import deprecated from .utils._tags import _safe_tags from .utils.validation import check_memory +from .utils.validation import check_is_fitted from .utils.fixes import delayed +from .exceptions import NotFittedError from .utils.metaestimators import _BaseComposition @@ -657,6 +659,18 @@ def n_features_in_(self): # delegate to first step (which will call _check_is_fitted) return self.steps[0][1].n_features_in_ + def __sklearn_is_fitted__(self): + """Indicate whether pipeline has been fit.""" + try: + # check if the last step of the pipeline is fitted + # we only check the last step since if the last step is fit, it + # means the previous steps should also be fit. This is faster than + # checking if every step of the pipeline is fit. + check_is_fitted(self.steps[-1][1]) + return True + except NotFittedError: + return False + def _sk_visual_block_(self): _, estimators = zip(*self.steps) diff --git a/sklearn/preprocessing/_function_transformer.py b/sklearn/preprocessing/_function_transformer.py index 345cc96bb1c2e..202b6ec2f6cdd 100644 --- a/sklearn/preprocessing/_function_transformer.py +++ b/sklearn/preprocessing/_function_transformer.py @@ -176,5 +176,9 @@ def _transform(self, X, func=None, kw_args=None): return func(X, **(kw_args if kw_args else {})) + def __sklearn_is_fitted__(self): + """Return True since FunctionTransfomer is stateless.""" + return True + def _more_tags(self): return {"no_validation": not self.validate, "stateless": True} diff --git a/sklearn/utils/estimator_checks.py b/sklearn/utils/estimator_checks.py index 7749484ea5b22..612c61753a1cb 100644 --- a/sklearn/utils/estimator_checks.py +++ b/sklearn/utils/estimator_checks.py @@ -51,6 +51,7 @@ from ..model_selection import ShuffleSplit from ..model_selection._validation import _safe_split from ..metrics.pairwise import rbf_kernel, linear_kernel, pairwise_distances +from ..utils.validation import check_is_fitted from . import shuffle from ._tags import ( @@ -305,6 +306,7 @@ def _yield_all_checks(estimator): yield check_dict_unchanged yield check_dont_overwrite_parameters yield check_fit_idempotent + yield check_fit_check_is_fitted if not tags["no_validation"]: yield check_n_features_in yield check_fit1d @@ -3493,6 +3495,45 @@ def check_fit_idempotent(name, estimator_orig): ) +def check_fit_check_is_fitted(name, estimator_orig): + # Make sure that estimator doesn't pass check_is_fitted before calling fit + # and that passes check_is_fitted once it's fit. + + rng = np.random.RandomState(42) + + estimator = clone(estimator_orig) + set_random_state(estimator) + if "warm_start" in estimator.get_params(): + estimator.set_params(warm_start=False) + + n_samples = 100 + X = rng.normal(loc=100, size=(n_samples, 2)) + X = _pairwise_estimator_convert_X(X, estimator) + if is_regressor(estimator_orig): + y = rng.normal(size=n_samples) + else: + y = rng.randint(low=0, high=2, size=n_samples) + y = _enforce_estimator_tags_y(estimator, y) + + if not _safe_tags(estimator).get("stateless", False): + # stateless estimators (such as FunctionTransformer) are always "fit"! + try: + check_is_fitted(estimator) + raise AssertionError( + f"{estimator.__class__.__name__} passes check_is_fitted before being" + " fit!" + ) + except NotFittedError: + pass + estimator.fit(X, y) + try: + check_is_fitted(estimator) + except NotFittedError as e: + raise NotFittedError( + "Estimator fails to pass `check_is_fitted` even though it has been fit." + ) from e + + def check_n_features_in(name, estimator_orig): # Make sure that n_features_in_ attribute doesn't exist until fit is # called, and that its value is correct. diff --git a/sklearn/utils/validation.py b/sklearn/utils/validation.py index 98bf6ac8bdb6a..aa7a23ffcdf9c 100644 --- a/sklearn/utils/validation.py +++ b/sklearn/utils/validation.py @@ -1142,8 +1142,9 @@ def check_is_fitted(estimator, attributes=None, *, msg=None, all_or_any=all): fitted attributes (ending with a trailing underscore) and otherwise raises a NotFittedError with the given message. - This utility is meant to be used internally by estimators themselves, - typically in their own predict / transform methods. + If an estimator does not set any attributes with a trailing underscore, it + can define a ``__sklearn_is_fitted__`` method returning a boolean to specify if the + estimator is fitted or not. Parameters ---------- @@ -1194,13 +1195,15 @@ def check_is_fitted(estimator, attributes=None, *, msg=None, all_or_any=all): if attributes is not None: if not isinstance(attributes, (list, tuple)): attributes = [attributes] - attrs = all_or_any([hasattr(estimator, attr) for attr in attributes]) + fitted = all_or_any([hasattr(estimator, attr) for attr in attributes]) + elif hasattr(estimator, "__sklearn_is_fitted__"): + fitted = estimator.__sklearn_is_fitted__() else: - attrs = [ + fitted = [ v for v in vars(estimator) if v.endswith("_") and not v.startswith("__") ] - if not attrs: + if not fitted: raise NotFittedError(msg % {"name": type(estimator).__name__})
diff --git a/sklearn/tests/test_pipeline.py b/sklearn/tests/test_pipeline.py index 4176e1a65f4b2..4ec5c7f081a15 100644 --- a/sklearn/tests/test_pipeline.py +++ b/sklearn/tests/test_pipeline.py @@ -21,7 +21,8 @@ MinimalRegressor, MinimalTransformer, ) - +from sklearn.exceptions import NotFittedError +from sklearn.utils.validation import check_is_fitted from sklearn.base import clone, is_classifier, BaseEstimator, TransformerMixin from sklearn.pipeline import Pipeline, FeatureUnion, make_pipeline, make_union from sklearn.svm import SVC @@ -1361,3 +1362,16 @@ def test_search_cv_using_minimal_compatible_estimator(Predictor): else: assert_allclose(y_pred, y.mean()) assert model.score(X, y) == pytest.approx(r2_score(y, y_pred)) + + +def test_pipeline_check_if_fitted(): + class Estimator(BaseEstimator): + def fit(self, X, y): + self.fitted_ = True + return self + + pipeline = Pipeline([("clf", Estimator())]) + with pytest.raises(NotFittedError): + check_is_fitted(pipeline) + pipeline.fit(iris.data, iris.target) + check_is_fitted(pipeline) diff --git a/sklearn/utils/tests/test_estimator_checks.py b/sklearn/utils/tests/test_estimator_checks.py index ea158234ea785..89e2e43651088 100644 --- a/sklearn/utils/tests/test_estimator_checks.py +++ b/sklearn/utils/tests/test_estimator_checks.py @@ -34,6 +34,7 @@ from sklearn.utils.validation import check_array from sklearn.utils import all_estimators from sklearn.exceptions import SkipTestWarning +from sklearn.utils.metaestimators import available_if from sklearn.utils.estimator_checks import ( _NotAnArray, @@ -51,6 +52,7 @@ check_regressor_data_not_an_array, check_outlier_corruption, set_random_state, + check_fit_check_is_fitted, ) @@ -986,3 +988,28 @@ def test_minimal_class_implementation_checks(): minimal_estimators = [MinimalTransformer(), MinimalRegressor(), MinimalClassifier()] for estimator in minimal_estimators: check_estimator(estimator) + + +def test_check_fit_check_is_fitted(): + class Estimator(BaseEstimator): + def __init__(self, behavior="attribute"): + self.behavior = behavior + + def fit(self, X, y, **kwargs): + if self.behavior == "attribute": + self.is_fitted_ = True + elif self.behavior == "method": + self._is_fitted = True + return self + + @available_if(lambda self: self.behavior in {"method", "always-true"}) + def __sklearn_is_fitted__(self): + if self.behavior == "always-true": + return True + return hasattr(self, "_is_fitted") + + with raises(Exception, match="passes check_is_fitted before being fit"): + check_fit_check_is_fitted("estimator", Estimator(behavior="always-true")) + + check_fit_check_is_fitted("estimator", Estimator(behavior="method")) + check_fit_check_is_fitted("estimator", Estimator(behavior="attribute")) diff --git a/sklearn/utils/tests/test_validation.py b/sklearn/utils/tests/test_validation.py index 1a1449ecc209f..35afff12b7ca4 100644 --- a/sklearn/utils/tests/test_validation.py +++ b/sklearn/utils/tests/test_validation.py @@ -51,7 +51,7 @@ FLOAT_DTYPES, ) from sklearn.utils.validation import _check_fit_params - +from sklearn.base import BaseEstimator import sklearn from sklearn.exceptions import NotFittedError, PositiveSpectrumWarning @@ -750,6 +750,20 @@ def test_check_symmetric(): assert_array_equal(output, arr_sym) +def test_check_is_fitted_with_is_fitted(): + class Estimator(BaseEstimator): + def fit(self, **kwargs): + self._is_fitted = True + return self + + def __sklearn_is_fitted__(self): + return hasattr(self, "_is_fitted") and self._is_fitted + + with pytest.raises(NotFittedError): + check_is_fitted(Estimator()) + check_is_fitted(Estimator().fit()) + + def test_check_is_fitted(): # Check is TypeError raised when non estimator instance passed with pytest.raises(TypeError):
[ { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 9cf628dfda5f5..5f50465f5aef3 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -723,6 +723,12 @@ Changelog\n unavailable on the basis of state, in a more readable way.\n :pr:`19948` by `Joel Nothman`_.\n \n+_ |Enhancement| :func:`utils.validation.check_is_fitted` now uses\n+ ``__sklearn_is_fitted__`` if available, instead of checking for attributes ending with\n+ an underscore. This also makes :class:`Pipeline` and\n+ :class:`preprocessing.FunctionTransformer` pass\n+ ``check_is_fitted(estimator)``. :pr:`20657` by `Adrin Jalali`_.\n+\n - |Fix| Fixed a bug in :func:`utils.sparsefuncs.mean_variance_axis` where the\n precision of the computed variance was very poor when the real variance is\n exactly zero. :pr:`19766` by :user:`Jérémie du Boisberranger <jeremiedbb>`.\n" } ]
1.00
ec941a86c01e98dc0b41c406631f86b1caf3f2e0
[ "sklearn/utils/tests/test_validation.py::test_check_symmetric", "sklearn/utils/tests/test_validation.py::test_ordering", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[array-int]", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_valid[True-insignificant pos]", "sklearn/utils/tests/test_validation.py::test_check_array_dtype_numeric_errors[X0]", "sklearn/utils/tests/test_validation.py::test_deprecate_positional_args_warns_for_class", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[series-dict]", "sklearn/tests/test_pipeline.py::test_fit_predict_with_intermediate_fit_params", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_not_equals[array]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[series-int]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_raise_exception[coo]", "sklearn/tests/test_pipeline.py::test_score_samples_on_pipeline_without_score_samples", "sklearn/utils/tests/test_validation.py::test_check_fit_params[None]", "sklearn/utils/tests/test_validation.py::test_check_array_min_samples_and_features_messages", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[list-bool]", "sklearn/tests/test_pipeline.py::test_pipeline_get_tags_none[None]", "sklearn/utils/tests/test_validation.py::test_check_array_dtype_warning", "sklearn/tests/test_pipeline.py::test_pipeline_correctly_adjusts_steps[None]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[csr_matrix-nan-allow-inf-force_all_finite should be a bool or \"allow-nan\"]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[short-int16-integer]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[tuple-dict]", "sklearn/tests/test_pipeline.py::test_search_cv_using_minimal_compatible_estimator[MinimalRegressor]", "sklearn/tests/test_pipeline.py::test_feature_union_fit_params", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[uint16-ushort-unsignedinteger]", "sklearn/utils/tests/test_validation.py::test_check_array_memmap[True]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[dtype0-float32-UInt8]", "sklearn/utils/tests/test_validation.py::test_check_non_negative[asarray]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[asarray-nan-1-Input contains NaN, infinity]", "sklearn/tests/test_pipeline.py::test_pipeline_slice[1-None]", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_invalid[significant neg float64]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_no_exception[coo]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_sparse_type_exception", "sklearn/tests/test_pipeline.py::test_verbose[est6-\\\\[Pipeline\\\\].*\\\\(step 1 of 2\\\\) Processing transf.* total=.*\\\\n\\\\[Pipeline\\\\].*\\\\(step 2 of 2\\\\) Processing clf.* total=.*\\\\n$-fit]", "sklearn/tests/test_pipeline.py::test_pipeline_sample_weight_unsupported", "sklearn/utils/tests/test_validation.py::test_check_sparse_pandas_sp_format[bsr]", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_valid[True-insignificant_imag]", "sklearn/tests/test_pipeline.py::test_step_name_validation", "sklearn/tests/test_pipeline.py::test_verbose[est15-\\\\[FeatureUnion\\\\].*\\\\(step 1 of 1\\\\) Processing mult2.* total=.*\\\\n$-fit_transform]", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_invalid[significant neg]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[int16-int32]", "sklearn/utils/tests/test_validation.py::test_check_array_deprecated_matrix", "sklearn/tests/test_pipeline.py::test_pipeline_with_cache_attribute", "sklearn/utils/tests/test_validation.py::test_check_sparse_pandas_sp_format[coo]", "sklearn/tests/test_pipeline.py::test_verbose[est11-\\\\[Pipeline\\\\].*\\\\(step 1 of 2\\\\) Processing transf.* total=.*\\\\n\\\\[Pipeline\\\\].*\\\\(step 2 of 2\\\\) Processing mult.* total=.*\\\\n$-fit_transform]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[float64-float64-UInt16]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[numeric-float64-Int8]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_scalars[str]", "sklearn/utils/tests/test_validation.py::test_check_array_dtype_numeric_errors[X2]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[byte-uint16]", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_equals[csc_matrix]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[list-int]", "sklearn/utils/tests/test_validation.py::test_suppress_validation", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_valid[True-insignificant neg float32]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[float64-float64-Int16]", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_equals[csr_matrix]", "sklearn/utils/tests/test_validation.py::test_check_non_negative[dok_matrix]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[asarray-inf-True-Input contains NaN, infinity]", "sklearn/utils/tests/test_validation.py::test_check_array_numeric_warns[X4]", "sklearn/utils/tests/test_validation.py::test_check_dataframe_fit_attribute", "sklearn/tests/test_pipeline.py::test_predict_methods_with_predict_params[predict]", "sklearn/utils/tests/test_validation.py::test_check_is_fitted_with_attributes[list]", "sklearn/tests/test_pipeline.py::test_fit_predict_on_pipeline_without_fit_predict", "sklearn/tests/test_pipeline.py::test_make_pipeline", "sklearn/tests/test_pipeline.py::test_make_pipeline_memory", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[True-X0-Input contains NaN, infinity or a value too large for.*int]", "sklearn/utils/tests/test_validation.py::test_check_array_numeric_warns[X1]", "sklearn/utils/tests/test_validation.py::test_num_features[list]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[False-X2-Input contains NaN, infinity or a value too large for.*int]", "sklearn/tests/test_pipeline.py::test_pipeline_methods_anova", "sklearn/tests/test_pipeline.py::test_n_features_in_pipeline", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[False-X3-cannot convert float NaN to integer]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[list-float]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[series-bool]", "sklearn/tests/test_pipeline.py::test_pipeline_sample_weight_supported", "sklearn/tests/test_pipeline.py::test_verbose[est13-\\\\[FeatureUnion\\\\].*\\\\(step 1 of 2\\\\) Processing mult1.* total=.*\\\\n\\\\[FeatureUnion\\\\].*\\\\(step 2 of 2\\\\) Processing mult2.* total=.*\\\\n$-fit_transform]", "sklearn/tests/test_pipeline.py::test_verbose[est9-\\\\[Pipeline\\\\].*\\\\(step 1 of 2\\\\) Processing transf.* total=.*\\\\n\\\\[Pipeline\\\\].*\\\\(step 2 of 2\\\\) Processing mult.* total=.*\\\\n$-fit_transform]", "sklearn/utils/tests/test_validation.py::test_check_array_dtype_numeric_errors[X1]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[array-str]", "sklearn/utils/tests/test_validation.py::test_check_dataframe_mixed_float_dtypes", "sklearn/utils/tests/test_validation.py::test_check_non_negative[csr_matrix]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_valid[asarray-nan-allow-nan]", "sklearn/tests/test_pipeline.py::test_pipeline_slice[1-2]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[numeric-float64-Int16]", "sklearn/utils/tests/test_validation.py::test_check_scalar_invalid[1-test_name1-float-2-4-err_msg0]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[asarray-nan-True-Input contains NaN, infinity]", "sklearn/tests/test_pipeline.py::test_pipeline_missing_values_leniency", "sklearn/tests/test_pipeline.py::test_predict_methods_with_predict_params[predict_log_proba]", "sklearn/utils/tests/test_validation.py::test_num_features[dataframe]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[array-float]", "sklearn/tests/test_pipeline.py::test_pipeline_fit_params", "sklearn/tests/test_pipeline.py::test_verbose[est5-\\\\[Pipeline\\\\].*\\\\(step 1 of 3\\\\) Processing transf.* total=.*\\\\n\\\\[Pipeline\\\\].*\\\\(step 2 of 3\\\\) Processing noop.* total=.*\\\\n\\\\[Pipeline\\\\].*\\\\(step 3 of 3\\\\) Processing clf.* total=.*\\\\n$-fit_predict]", "sklearn/tests/test_pipeline.py::test_pipeline_score_samples_pca_lof", "sklearn/tests/test_pipeline.py::test_verbose[est4-\\\\[Pipeline\\\\].*\\\\(step 1 of 3\\\\) Processing transf.* total=.*\\\\n\\\\[Pipeline\\\\].*\\\\(step 2 of 3\\\\) Processing noop.* total=.*\\\\n\\\\[Pipeline\\\\].*\\\\(step 3 of 3\\\\) Processing clf.* total=.*\\\\n$-fit]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[list-dict]", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_not_equals[csr_matrix]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_raise_exception[csc]", "sklearn/tests/test_pipeline.py::test_feature_union_warns_unknown_transformer_weight", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[tuple-bool]", "sklearn/utils/tests/test_validation.py::test_check_array_complex_data_error", "sklearn/tests/test_pipeline.py::test_pipeline_methods_pca_svm", "sklearn/utils/tests/test_validation.py::test_check_array_dtype_numeric_errors[X3]", "sklearn/utils/tests/test_validation.py::test_check_is_fitted_with_attributes[tuple]", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_invalid[significant_imag]", "sklearn/utils/tests/test_validation.py::test_num_features[sparse_csr]", "sklearn/tests/test_pipeline.py::test_verbose[est14-\\\\[FeatureUnion\\\\].*\\\\(step 1 of 1\\\\) Processing mult2.* total=.*\\\\n$-fit]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[False-X0-Input contains NaN, infinity or a value too large for.*int]", "sklearn/tests/test_pipeline.py::test_feature_union_feature_names", "sklearn/tests/test_pipeline.py::test_verbose[est3-\\\\[Pipeline\\\\].*\\\\(step 1 of 3\\\\) Processing transf.* total=.*\\\\n\\\\[Pipeline\\\\].*\\\\(step 2 of 3\\\\) Processing noop.* total=.*\\\\n\\\\[Pipeline\\\\].*\\\\(step 3 of 3\\\\) Processing clf.* total=.*\\\\n$-fit_predict]", "sklearn/tests/test_pipeline.py::test_pipeline_index", "sklearn/tests/test_pipeline.py::test_pipeline_raise_set_params_error", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_no_exception[bsr]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_valid[asarray-inf-False]", "sklearn/utils/tests/test_validation.py::test_check_array", "sklearn/utils/tests/test_validation.py::test_check_X_y_informative_error", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[list-str]", "sklearn/tests/test_pipeline.py::test_predict_methods_with_predict_params[predict_proba]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[tuple-float]", "sklearn/tests/test_pipeline.py::test_set_pipeline_step_passthrough[passthrough]", "sklearn/utils/tests/test_validation.py::test_check_consistent_length", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[int32-long]", "sklearn/utils/tests/test_validation.py::test_deprecate_positional_args_warns_for_function", "sklearn/tests/test_pipeline.py::test_set_params_nested_pipeline", "sklearn/tests/test_pipeline.py::test_set_pipeline_steps", "sklearn/utils/tests/test_validation.py::test_check_array_accept_sparse_no_exception", "sklearn/tests/test_pipeline.py::test_pipeline_init_tuple", "sklearn/utils/tests/test_validation.py::test_check_is_fitted", "sklearn/tests/test_pipeline.py::test_verbose[est0-\\\\[Pipeline\\\\].*\\\\(step 1 of 2\\\\) Processing transf.* total=.*\\\\n\\\\[Pipeline\\\\].*\\\\(step 2 of 2\\\\) Processing clf.* total=.*\\\\n$-fit]", "sklearn/tests/test_pipeline.py::test_pipeline_slice[1-3]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_dtype_casting", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_raise_exception[csr]", "sklearn/utils/tests/test_validation.py::test_check_array_series", "sklearn/tests/test_pipeline.py::test_verbose[est12-\\\\[FeatureUnion\\\\].*\\\\(step 1 of 2\\\\) Processing mult1.* total=.*\\\\n\\\\[FeatureUnion\\\\].*\\\\(step 2 of 2\\\\) Processing mult2.* total=.*\\\\n$-fit]", "sklearn/utils/tests/test_validation.py::test_check_non_negative[lil_matrix]", "sklearn/utils/tests/test_validation.py::test_check_scalar_invalid[1-test_name2-int-2-4-err_msg1]", "sklearn/tests/test_pipeline.py::test_pipeline_fit_transform", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[uintp-ulonglong-unsignedinteger]", "sklearn/utils/tests/test_validation.py::test_num_features[sparse_csc]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[csr_matrix-nan-True-Input contains NaN, infinity]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[True-X3-cannot convert float NaN to integer]", "sklearn/tests/test_pipeline.py::test_make_union", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[csr_matrix-inf-True-Input contains NaN, infinity]", "sklearn/utils/tests/test_validation.py::test_check_sparse_pandas_sp_format[csr]", "sklearn/tests/test_pipeline.py::test_pipeline_get_tags_none[passthrough]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_valid[csr_matrix-nan-False]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[csr_matrix-nan-1-Input contains NaN, infinity]", "sklearn/utils/tests/test_validation.py::test_check_array_dtype_stability", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_raise_exception[bsr]", "sklearn/utils/tests/test_validation.py::test_check_sparse_pandas_sp_format[True]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[numeric-float64-UInt16]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[dtype0-float32-Int8]", "sklearn/tests/test_pipeline.py::test_make_union_kwargs", "sklearn/tests/test_pipeline.py::test_verbose[est2-\\\\[Pipeline\\\\].*\\\\(step 1 of 3\\\\) Processing transf.* total=.*\\\\n\\\\[Pipeline\\\\].*\\\\(step 2 of 3\\\\) Processing noop.* total=.*\\\\n\\\\[Pipeline\\\\].*\\\\(step 3 of 3\\\\) Processing clf.* total=.*\\\\n$-fit]", "sklearn/utils/tests/test_validation.py::test_as_float_array_nan[X0]", "sklearn/utils/tests/test_validation.py::test_has_fit_parameter", "sklearn/utils/tests/test_validation.py::test_check_non_negative[bsr_matrix]", "sklearn/utils/tests/test_validation.py::test_check_sparse_pandas_sp_format[csc]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[numeric-float64-UInt8]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[asarray-inf-allow-nan-Input contains infinity]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_scalars[float]", "sklearn/tests/test_pipeline.py::test_verbose[est7-\\\\[Pipeline\\\\].*\\\\(step 1 of 2\\\\) Processing transf.* total=.*\\\\n\\\\[Pipeline\\\\].*\\\\(step 2 of 2\\\\) Processing clf.* total=.*\\\\n$-fit_transform]", "sklearn/tests/test_pipeline.py::test_pipeline_slice[0-2]", "sklearn/tests/test_pipeline.py::test_set_pipeline_step_passthrough[None]", "sklearn/utils/tests/test_validation.py::test_num_features[array]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[dtype0-float32-Int16]", "sklearn/tests/test_pipeline.py::test_verbose[est8-\\\\[Pipeline\\\\].*\\\\(step 1 of 2\\\\) Processing transf.* total=.*\\\\n\\\\[Pipeline\\\\].*\\\\(step 2 of 2\\\\) Processing mult.* total=.*\\\\n$-fit]", "sklearn/utils/tests/test_validation.py::test_check_is_fitted_with_attributes[single]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[float64-float64-UInt8]", "sklearn/utils/tests/test_validation.py::test_check_array_numeric_warns[X0]", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_not_equals[csc_matrix]", "sklearn/utils/tests/test_validation.py::test_check_non_negative[coo_matrix]", "sklearn/utils/tests/test_validation.py::test_check_array_numeric_warns[X3]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[tuple-int]", "sklearn/utils/tests/test_validation.py::test_check_scalar_invalid[5-test_name3-int-2-4-err_msg2]", "sklearn/tests/test_pipeline.py::test_pipeline_ducktyping", "sklearn/tests/test_pipeline.py::test_pipeline_wrong_memory", "sklearn/utils/tests/test_validation.py::test_num_features_errors_scalars[bool]", "sklearn/tests/test_pipeline.py::test_fit_predict_on_pipeline", "sklearn/tests/test_pipeline.py::test_classes_property", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_valid[True-insignificant neg]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_no_exception[csr]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[True-X2-Input contains NaN, infinity or a value too large for.*int]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[ushort-uint32]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[series-float]", "sklearn/tests/test_pipeline.py::test_pipeline_slice[0-1]", "sklearn/tests/test_pipeline.py::test_pipeline_param_error", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[int_-intp-integer]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[uint32-uint64]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[ubyte-uint8-unsignedinteger]", "sklearn/tests/test_pipeline.py::test_feature_union_weights", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_valid[asarray-nan-False]", "sklearn/utils/tests/test_validation.py::test_check_is_fitted_attributes", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[intc-int32-integer]", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_invalid[all negative]", "sklearn/tests/test_pipeline.py::test_feature_union_parallel", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[asarray-nan-allow-inf-force_all_finite should be a bool or \"allow-nan\"]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_no_exception[csc]", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_equals[array]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[series-str]", "sklearn/utils/tests/test_validation.py::test_as_float_array", "sklearn/utils/tests/test_validation.py::test_memmap", "sklearn/tests/test_pipeline.py::test_verbose[est10-\\\\[Pipeline\\\\].*\\\\(step 1 of 2\\\\) Processing transf.* total=.*\\\\n\\\\[Pipeline\\\\].*\\\\(step 2 of 2\\\\) Processing mult.* total=.*\\\\n$-fit]", "sklearn/utils/tests/test_validation.py::test_check_array_numeric_warns[X2]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[False-X1-Input contains NaN, infinity or a value too large for.*int]", "sklearn/utils/tests/test_validation.py::test_retrieve_samples_from_non_standard_shape", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_valid[True-insignificant neg float64]", "sklearn/utils/tests/test_validation.py::test_check_sample_weight", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[uint-uint64-unsignedinteger]", "sklearn/utils/tests/test_validation.py::test_num_features[tuple]", "sklearn/utils/tests/test_validation.py::test_check_array_memmap[False]", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_raise[csr_matrix]", "sklearn/tests/test_pipeline.py::test_pipeline_named_steps", "sklearn/tests/test_pipeline.py::test_pipeline_correctly_adjusts_steps[passthrough]", "sklearn/tests/test_pipeline.py::test_pipeline_memory", "sklearn/utils/tests/test_validation.py::test_np_matrix", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_valid[csr_matrix-nan-allow-nan]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[int64-longlong-integer]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[int8-byte-integer]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_scalars[int]", "sklearn/tests/test_pipeline.py::test_pipeline_slice[None-None]", "sklearn/utils/tests/test_validation.py::test_check_fit_params[indices1]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_invalid[uint8-int8]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_dtype_object_conversion", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[array-dict]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_object_unsafe_casting[True-X1-Input contains NaN, infinity or a value too large for.*int]", "sklearn/utils/tests/test_validation.py::test_as_float_array_nan[X1]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_valid[csr_matrix-inf-False]", "sklearn/tests/test_pipeline.py::test_search_cv_using_minimal_compatible_estimator[MinimalClassifier]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[dtype0-float32-UInt16]", "sklearn/utils/tests/test_validation.py::test_check_non_negative[dia_matrix]", "sklearn/utils/tests/test_validation.py::test_check_array_on_mock_dataframe", "sklearn/tests/test_pipeline.py::test_pipeline_slice[None-1]", "sklearn/tests/test_pipeline.py::test_pipeline_methods_preprocessing_svm", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[uintc-uint32-unsignedinteger]", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[int0-long-integer]", "sklearn/tests/test_pipeline.py::test_verbose[est1-\\\\[Pipeline\\\\].*\\\\(step 1 of 2\\\\) Processing transf.* total=.*\\\\n\\\\[Pipeline\\\\].*\\\\(step 2 of 2\\\\) Processing clf.* total=.*\\\\n$-fit_predict]", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[tuple-str]", "sklearn/utils/tests/test_validation.py::test_check_psd_eigenvalues_invalid[significant neg float32]", "sklearn/tests/test_pipeline.py::test_pipeline_transform", "sklearn/utils/tests/test_validation.py::test_check_pandas_sparse_valid[int-long-integer]", "sklearn/tests/test_pipeline.py::test_set_feature_union_steps", "sklearn/utils/tests/test_validation.py::test_num_features_errors_1d_containers[array-bool]", "sklearn/tests/test_pipeline.py::test_n_features_in_feature_union", "sklearn/utils/tests/test_validation.py::test_check_non_negative[csc_matrix]", "sklearn/utils/tests/test_validation.py::test_deprecate_positional_args_warns_for_function_version", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finiteinvalid[csr_matrix-inf-allow-nan-Input contains infinity]", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_na_support[float64-float64-Int8]", "sklearn/utils/tests/test_validation.py::test_allclose_dense_sparse_raise[csc_matrix]" ]
[ "sklearn/tests/test_pipeline.py::test_pipeline_check_if_fitted", "sklearn/utils/tests/test_validation.py::test_check_is_fitted_with_is_fitted" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 9cf628dfda5f5..5f50465f5aef3 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -723,6 +723,12 @@ Changelog\n unavailable on the basis of state, in a more readable way.\n :pr:`<PRID>` by `<NAME>`_.\n \n+_ |Enhancement| :func:`utils.validation.check_is_fitted` now uses\n+ ``__sklearn_is_fitted__`` if available, instead of checking for attributes ending with\n+ an underscore. This also makes :class:`Pipeline` and\n+ :class:`preprocessing.FunctionTransformer` pass\n+ ``check_is_fitted(estimator)``. :pr:`<PRID>` by `<NAME>`_.\n+\n - |Fix| Fixed a bug in :func:`utils.sparsefuncs.mean_variance_axis` where the\n precision of the computed variance was very poor when the real variance is\n exactly zero. :pr:`<PRID>` by :user:`<NAME>`.\n" } ]
diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst index 9cf628dfda5f5..5f50465f5aef3 100644 --- a/doc/whats_new/v1.0.rst +++ b/doc/whats_new/v1.0.rst @@ -723,6 +723,12 @@ Changelog unavailable on the basis of state, in a more readable way. :pr:`<PRID>` by `<NAME>`_. +_ |Enhancement| :func:`utils.validation.check_is_fitted` now uses + ``__sklearn_is_fitted__`` if available, instead of checking for attributes ending with + an underscore. This also makes :class:`Pipeline` and + :class:`preprocessing.FunctionTransformer` pass + ``check_is_fitted(estimator)``. :pr:`<PRID>` by `<NAME>`_. + - |Fix| Fixed a bug in :func:`utils.sparsefuncs.mean_variance_axis` where the precision of the computed variance was very poor when the real variance is exactly zero. :pr:`<PRID>` by :user:`<NAME>`.
scikit-learn/scikit-learn
scikit-learn__scikit-learn-17526
https://github.com/scikit-learn/scikit-learn/pull/17526
diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index 848b415890452..9cd8902f0643f 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -61,6 +61,10 @@ Changelog change since `None` was defaulting to these values already. :pr:`16493` by :user:`Darshan N <DarshanGowda0>`. +- |Feature| :class:`impute.SimpleImputer` now supports a list of strings + when ``strategy='most_frequent'`` or ``strategy='constant'``. + :pr:`17526` by :user:`Ayako YAGI <yagi-3>` and :user:`Juan Carlos Alfaro Jiménez <alfaro96>`. + :mod:`sklearn.metrics` ...................... diff --git a/sklearn/impute/_base.py b/sklearn/impute/_base.py index 517de982d8478..cedc97872333c 100644 --- a/sklearn/impute/_base.py +++ b/sklearn/impute/_base.py @@ -228,7 +228,15 @@ def _validate_input(self, X, in_fit): self.strategy)) if self.strategy in ("most_frequent", "constant"): - dtype = None + # If input is a list of strings, dtype = object. + # Otherwise ValueError is raised in SimpleImputer + # with strategy='most_frequent' or 'constant' + # because the list is converted to Unicode numpy array + if isinstance(X, list) and \ + any(isinstance(elem, str) for row in X for elem in row): + dtype = object + else: + dtype = None else: dtype = FLOAT_DTYPES
diff --git a/sklearn/impute/tests/test_impute.py b/sklearn/impute/tests/test_impute.py index 960f671915e6a..53580f32c34ca 100644 --- a/sklearn/impute/tests/test_impute.py +++ b/sklearn/impute/tests/test_impute.py @@ -1342,6 +1342,25 @@ def test_simple_imputation_add_indicator_sparse_matrix(arr_type): assert_allclose(X_trans.toarray(), X_true) [email protected]( + 'strategy, expected', + [('most_frequent', 'b'), ('constant', 'missing_value')] +) +def test_simple_imputation_string_list(strategy, expected): + X = [['a', 'b'], + ['c', np.nan]] + + X_true = np.array([ + ['a', 'b'], + ['c', expected] + ], dtype=object) + + imputer = SimpleImputer(strategy=strategy) + X_trans = imputer.fit_transform(X) + + assert_array_equal(X_trans, X_true) + + @pytest.mark.parametrize( "order, idx_order", [
[ { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex 848b415890452..9cd8902f0643f 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -61,6 +61,10 @@ Changelog\n change since `None` was defaulting to these values already.\n :pr:`16493` by :user:`Darshan N <DarshanGowda0>`.\n \n+- |Feature| :class:`impute.SimpleImputer` now supports a list of strings\n+ when ``strategy='most_frequent'`` or ``strategy='constant'``.\n+ :pr:`17526` by :user:`Ayako YAGI <yagi-3>` and :user:`Juan Carlos Alfaro Jiménez <alfaro96>`.\n+\n :mod:`sklearn.metrics`\n ......................\n \n" } ]
0.24
53befd82e389da5fa1c96156759bd1bc908a8658
[ "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[all-3-features_indices1-0-int32-array]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[all-3-features_indices1-nan-float64-csc_matrix]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_min_max_array_like[lists]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_no_missing", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[nan-coo_matrix-auto]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_imputation_order[random]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_imputation_order[descending]", "sklearn/impute/tests/test_impute.py::test_imputation_deletion_warning[mean]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_verbose", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_min_max_array_like[scalars]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[all-3-features_indices1--1-int32-bsr_matrix]", "sklearn/impute/tests/test_impute.py::test_imputation_shape[mean]", "sklearn/impute/tests/test_impute.py::test_imputation_error_sparse_0[constant]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[missing-only-3-features_indices0--1-int32-array]", "sklearn/impute/tests/test_impute.py::test_imputation_most_frequent_pandas[object]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_no_explicit_zeros", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[nan-array-True]", "sklearn/impute/tests/test_impute.py::test_imputation_error_sparse_0[median]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_early_stopping", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_min_max_array_like[None-default]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[missing-only-3-features_indices0--1-int32-lil_matrix]", "sklearn/impute/tests/test_impute.py::test_imputation_constant_pandas[object]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[missing-only-3-features_indices0--1-int32-csc_matrix]", "sklearn/impute/tests/test_impute.py::test_simple_imputation_add_indicator_sparse_matrix[coo_matrix]", "sklearn/impute/tests/test_impute.py::test_imputation_const_mostf_error_invalid_types[dtype2-most_frequent]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[all-3-features_indices1-nan-float64-array]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_error_param[1--0.001-ValueError-should be a non-negative float]", "sklearn/impute/tests/test_impute.py::test_imputation_const_mostf_error_invalid_types[dtype1-most_frequent]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_string", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[0-array-True]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[nan-csr_matrix-auto]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[nan-array-False]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[all-3-features_indices1-nan-float64-lil_matrix]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_one_feature[X0]", "sklearn/impute/tests/test_impute.py::test_simple_imputation_add_indicator_sparse_matrix[csr_matrix]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_clip_truncnorm", "sklearn/impute/tests/test_impute.py::test_imputation_error_sparse_0[mean]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_estimators[estimator3]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[all-3-features_indices1--1-int32-csc_matrix]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_with_imputer[X0-a-X_trans_exp0]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_catch_min_max_error[min_value2-max_value2-_value' should be of shape]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_one_feature[X1]", "sklearn/impute/tests/test_impute.py::test_imputation_constant_object[nan]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_additive_matrix", "sklearn/impute/tests/test_impute.py::test_simple_imputation_add_indicator_sparse_matrix[bsr_matrix]", "sklearn/impute/tests/test_impute.py::test_imputation_constant_object[0]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[nan-csc_matrix-True]", "sklearn/impute/tests/test_impute.py::test_inconsistent_dtype_X_missing_values[-1--1-types are expected to be both numerical.-IterativeImputer]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[all-3-features_indices1--1-int32-array]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_error[X_fit3-X_trans3-params3-MissingIndicator does not support data with dtype]", "sklearn/impute/tests/test_impute.py::test_imputation_order[ascending-idx_order0]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[nan-csr_matrix-False]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[missing-only-3-features_indices0--1-int32-csr_matrix]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_raise_on_sparse_with_missing_0[bsr_matrix]", "sklearn/impute/tests/test_impute.py::test_imputer_without_indicator[SimpleImputer]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[missing-only-3-features_indices0-nan-float64-array]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_min_max_array_like_imputation[Scalar-vs-vector]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[nan-lil_matrix-False]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_error_param[-1-0.001-ValueError-should be a positive integer]", "sklearn/impute/tests/test_impute.py::test_imputation_mean_median_error_invalid_type[str-median]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_estimators[estimator4]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[all-3-features_indices1--1-int32-coo_matrix]", "sklearn/impute/tests/test_impute.py::test_imputation_mean_median", "sklearn/impute/tests/test_impute.py::test_imputation_shape[median]", "sklearn/impute/tests/test_impute.py::test_imputation_order[descending-idx_order1]", "sklearn/impute/tests/test_impute.py::test_imputation_most_frequent_objects[NAN]", "sklearn/impute/tests/test_impute.py::test_imputation_mean_median_error_invalid_type[object-mean]", "sklearn/impute/tests/test_impute.py::test_inconsistent_dtype_X_missing_values[-1--1-types are expected to be both numerical.-SimpleImputer]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[missing-only-3-features_indices0-nan-float64-lil_matrix]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_transform_recovery[3]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_truncated_normal_posterior", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_catch_min_max_error[inf--inf-min_value >= max_value.]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_missing_at_transform[most_frequent]", "sklearn/impute/tests/test_impute.py::test_imputation_const_mostf_error_invalid_types[str-most_frequent]", "sklearn/impute/tests/test_impute.py::test_imputation_const_mostf_error_invalid_types[dtype2-constant]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[missing-only-3-features_indices0-0-int32-array]", "sklearn/impute/tests/test_impute.py::test_imputation_constant_float[asarray]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[0-array-auto]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_all_missing", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_rank_one", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_skip_non_missing[False]", "sklearn/impute/tests/test_impute.py::test_imputation_most_frequent_objects[0]", "sklearn/impute/tests/test_impute.py::test_imputation_mean_median_error_invalid_type[None-median]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_with_imputer[X3-None-X_trans_exp3]", "sklearn/impute/tests/test_impute.py::test_imputation_constant_object[None]", "sklearn/impute/tests/test_impute.py::test_imputation_mean_median_error_invalid_type[object-median]", "sklearn/impute/tests/test_impute.py::test_imputation_mean_median_error_invalid_type_list_pandas[dataframe-median]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[missing-only-3-features_indices0-nan-float64-coo_matrix]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_raise_on_sparse_with_missing_0[lil_matrix]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_estimators[estimator1]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_imputation_order[ascending]", "sklearn/impute/tests/test_impute.py::test_imputation_error_invalid_strategy[101]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[nan-array-auto]", "sklearn/impute/tests/test_impute.py::test_imputation_constant_object[NAN]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_min_max_array_like_imputation[None-vs-inf]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_imputation_order[arabic]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_skip_non_missing[True]", "sklearn/impute/tests/test_impute.py::test_imputation_copy", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_min_max_array_like[inf]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_imputation_order[roman]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[missing-only-3-features_indices0--1-int32-coo_matrix]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_missing_at_transform[median]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[nan-coo_matrix-True]", "sklearn/impute/tests/test_impute.py::test_imputation_mean_median_error_invalid_type_list_pandas[list-median]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[all-3-features_indices1--1-int32-lil_matrix]", "sklearn/impute/tests/test_impute.py::test_imputer_without_indicator[IterativeImputer]", "sklearn/impute/tests/test_impute.py::test_simple_imputation_add_indicator_sparse_matrix[csc_matrix]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_raise_on_sparse_with_missing_0[csr_matrix]", "sklearn/impute/tests/test_impute.py::test_imputation_most_frequent_objects[nan]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_with_imputer[X1-nan-X_trans_exp1]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_estimators[estimator2]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_catch_min_max_error[100-0-min_value >= max_value.]", "sklearn/impute/tests/test_impute.py::test_imputation_shape[most_frequent]", "sklearn/impute/tests/test_impute.py::test_imputation_shape[constant]", "sklearn/impute/tests/test_impute.py::test_imputation_median_special_cases", "sklearn/impute/tests/test_impute.py::test_imputation_most_frequent_objects[None]", "sklearn/impute/tests/test_impute.py::test_inconsistent_dtype_X_missing_values[NaN-nan-Input contains NaN-IterativeImputer]", "sklearn/impute/tests/test_impute.py::test_imputation_error_sparse_0[most_frequent]", "sklearn/impute/tests/test_impute.py::test_imputation_deletion_warning[most_frequent]", "sklearn/impute/tests/test_impute.py::test_imputation_const_mostf_error_invalid_types[str-constant]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_error[X_fit1-X_trans1-params1-'features' has to be either 'missing-only' or 'all']", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[0-array-False]", "sklearn/impute/tests/test_impute.py::test_imputation_mean_median_error_invalid_type[None-mean]", "sklearn/impute/tests/test_impute.py::test_imputation_most_frequent_pandas[category]", "sklearn/impute/tests/test_impute.py::test_inconsistent_dtype_X_missing_values[NaN-nan-Input contains NaN-SimpleImputer]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[nan-lil_matrix-True]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[missing-only-3-features_indices0-nan-float64-bsr_matrix]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_zero_iters", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_missing_at_transform[mean]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_transform_recovery[5]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[all-3-features_indices1--1-int32-csr_matrix]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[all-3-features_indices1-nan-float64-coo_matrix]", "sklearn/impute/tests/test_impute.py::test_imputation_constant_error_invalid_type[1-0]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[nan-lil_matrix-auto]", "sklearn/impute/tests/test_impute.py::test_imputation_most_frequent", "sklearn/impute/tests/test_impute.py::test_missing_indicator_with_imputer[X2-nan-X_trans_exp2]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_estimators[None]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[nan-csc_matrix-False]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[nan-csc_matrix-auto]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[missing-only-3-features_indices0--1-int32-bsr_matrix]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[nan-coo_matrix-False]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_sparse_param[nan-csr_matrix-True]", "sklearn/impute/tests/test_impute.py::test_imputation_deletion_warning[median]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[all-3-features_indices1-nan-float64-csr_matrix]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_error[X_fit0-X_trans0-params0-have missing values in transform but have no missing values in fit]", "sklearn/impute/tests/test_impute.py::test_imputation_const_mostf_error_invalid_types[dtype1-constant]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_clip", "sklearn/impute/tests/test_impute.py::test_imputation_mean_median_error_invalid_type_list_pandas[dataframe-mean]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_min_max_array_like[lists-with-inf]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_no_missing", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[missing-only-3-features_indices0-nan-float64-csc_matrix]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_raise_on_sparse_with_missing_0[coo_matrix]", "sklearn/impute/tests/test_impute.py::test_imputation_error_invalid_strategy[None]", "sklearn/impute/tests/test_impute.py::test_simple_imputation_add_indicator_sparse_matrix[lil_matrix]", "sklearn/impute/tests/test_impute.py::test_imputation_constant_pandas[category]", "sklearn/impute/tests/test_impute.py::test_imputation_constant_error_invalid_type[1.0-nan]", "sklearn/impute/tests/test_impute.py::test_imputation_pipeline_grid_search", "sklearn/impute/tests/test_impute.py::test_imputation_constant_integer", "sklearn/impute/tests/test_impute.py::test_imputation_most_frequent_objects[]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[missing-only-3-features_indices0-nan-float64-csr_matrix]", "sklearn/impute/tests/test_impute.py::test_imputation_mean_median_error_invalid_type[str-mean]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_error[X_fit2-X_trans2-params2-'sparse' has to be a boolean or 'auto']", "sklearn/impute/tests/test_impute.py::test_missing_indicator_new[all-3-features_indices1-nan-float64-bsr_matrix]", "sklearn/impute/tests/test_impute.py::test_missing_indicator_raise_on_sparse_with_missing_0[csc_matrix]", "sklearn/impute/tests/test_impute.py::test_imputation_constant_float[csr_matrix]", "sklearn/impute/tests/test_impute.py::test_iterative_imputer_transform_stochasticity", "sklearn/impute/tests/test_impute.py::test_imputation_error_invalid_strategy[const]", "sklearn/impute/tests/test_impute.py::test_imputation_constant_object[]", "sklearn/impute/tests/test_impute.py::test_imputation_mean_median_error_invalid_type_list_pandas[list-mean]" ]
[ "sklearn/impute/tests/test_impute.py::test_simple_imputation_string_list[constant-missing_value]", "sklearn/impute/tests/test_impute.py::test_simple_imputation_string_list[most_frequent-b]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex 848b415890452..9cd8902f0643f 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -61,6 +61,10 @@ Changelog\n change since `None` was defaulting to these values already.\n :pr:`<PRID>` by :user:`<NAME>`.\n \n+- |Feature| :class:`impute.SimpleImputer` now supports a list of strings\n+ when ``strategy='most_frequent'`` or ``strategy='constant'``.\n+ :pr:`<PRID>` by :user:`<NAME>` and :user:`<NAME>`.\n+\n :mod:`sklearn.metrics`\n ......................\n \n" } ]
diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index 848b415890452..9cd8902f0643f 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -61,6 +61,10 @@ Changelog change since `None` was defaulting to these values already. :pr:`<PRID>` by :user:`<NAME>`. +- |Feature| :class:`impute.SimpleImputer` now supports a list of strings + when ``strategy='most_frequent'`` or ``strategy='constant'``. + :pr:`<PRID>` by :user:`<NAME>` and :user:`<NAME>`. + :mod:`sklearn.metrics` ......................
scikit-learn/scikit-learn
scikit-learn__scikit-learn-17225
https://github.com/scikit-learn/scikit-learn/pull/17225
diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index db6959fcc164f..76ec91d93e264 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -76,7 +76,13 @@ Changelog attribute name/path or a `callable` for extracting feature importance from the estimator. :pr:`15361` by :user:`Venkatachalam N <venkyyuvy>` - +:mod:`sklearn.metrics` +...................... + +- |Enhancement| Add `sample_weight` parameter to + :class:`metrics.median_absolute_error`. + :pr:`17225` by :user:`Lucy Liu <lucyleeow>`. + :mod:`sklearn.tree` ................... diff --git a/sklearn/metrics/_regression.py b/sklearn/metrics/_regression.py index fd89d32a07c29..bf728b1d2dd31 100644 --- a/sklearn/metrics/_regression.py +++ b/sklearn/metrics/_regression.py @@ -30,6 +30,8 @@ _num_samples) from ..utils.validation import column_or_1d from ..utils.validation import _deprecate_positional_args +from ..utils.validation import _check_sample_weight +from ..utils.stats import _weighted_percentile from ..exceptions import UndefinedMetricWarning @@ -335,7 +337,8 @@ def mean_squared_log_error(y_true, y_pred, *, @_deprecate_positional_args -def median_absolute_error(y_true, y_pred, *, multioutput='uniform_average'): +def median_absolute_error(y_true, y_pred, *, multioutput='uniform_average', + sample_weight=None): """Median absolute error regression loss Median absolute error output is non-negative floating point. The best value @@ -360,6 +363,11 @@ def median_absolute_error(y_true, y_pred, *, multioutput='uniform_average'): 'uniform_average' : Errors of all outputs are averaged with uniform weight. + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + .. versionadded:: 0.24 + Returns ------- loss : float or ndarray of floats @@ -387,7 +395,12 @@ def median_absolute_error(y_true, y_pred, *, multioutput='uniform_average'): """ y_type, y_true, y_pred, multioutput = _check_reg_targets( y_true, y_pred, multioutput) - output_errors = np.median(np.abs(y_pred - y_true), axis=0) + if sample_weight is None: + output_errors = np.median(np.abs(y_pred - y_true), axis=0) + else: + sample_weight = _check_sample_weight(sample_weight, y_pred) + output_errors = _weighted_percentile(np.abs(y_pred - y_true), + sample_weight=sample_weight) if isinstance(multioutput, str): if multioutput == 'raw_values': return output_errors diff --git a/sklearn/utils/fixes.py b/sklearn/utils/fixes.py index f912df19c323b..adc1b6d0091bc 100644 --- a/sklearn/utils/fixes.py +++ b/sklearn/utils/fixes.py @@ -165,3 +165,39 @@ class loguniform(scipy.stats.reciprocal): ) class MaskedArray(_MaskedArray): pass # TODO: remove in 0.25 + + +def _take_along_axis(arr, indices, axis): + """Implements a simplified version of np.take_along_axis if numpy + version < 1.15""" + if np_version > (1, 14): + return np.take_along_axis(arr=arr, indices=indices, axis=axis) + else: + if axis is None: + arr = arr.flatten() + + if not np.issubdtype(indices.dtype, np.intp): + raise IndexError('`indices` must be an integer array') + if arr.ndim != indices.ndim: + raise ValueError( + "`indices` and `arr` must have the same number of dimensions") + + shape_ones = (1,) * indices.ndim + dest_dims = ( + list(range(axis)) + + [None] + + list(range(axis+1, indices.ndim)) + ) + + # build a fancy index, consisting of orthogonal aranges, with the + # requested index inserted at the right location + fancy_index = [] + for dim, n in zip(dest_dims, arr.shape): + if dim is None: + fancy_index.append(indices) + else: + ind_shape = shape_ones[:dim] + (-1,) + shape_ones[dim+1:] + fancy_index.append(np.arange(n).reshape(ind_shape)) + + fancy_index = tuple(fancy_index) + return arr[fancy_index] diff --git a/sklearn/utils/stats.py b/sklearn/utils/stats.py index 5a8a136305179..7b44575e97b33 100644 --- a/sklearn/utils/stats.py +++ b/sklearn/utils/stats.py @@ -1,18 +1,61 @@ import numpy as np from .extmath import stable_cumsum +from .fixes import _take_along_axis def _weighted_percentile(array, sample_weight, percentile=50): + """Compute weighted percentile + + Computes lower weighted percentile. If `array` is a 2D array, the + `percentile` is computed along the axis 0. + + .. versionchanged:: 0.24 + Accepts 2D `array`. + + Parameters + ---------- + array : 1D or 2D array + Values to take the weighted percentile of. + + sample_weight: 1D or 2D array + Weights for each value in `array`. Must be same shape as `array` or + of shape `(array.shape[0],)`. + + percentile: int, default=50 + Percentile to compute. Must be value between 0 and 100. + + Returns + ------- + percentile : int if `array` 1D, ndarray if `array` 2D + Weighted percentile. """ - Compute the weighted ``percentile`` of ``array`` with ``sample_weight``. - """ - sorted_idx = np.argsort(array) + n_dim = array.ndim + if n_dim == 0: + return array[()] + if array.ndim == 1: + array = array.reshape((-1, 1)) + # When sample_weight 1D, repeat for each array.shape[1] + if (array.shape != sample_weight.shape and + array.shape[0] == sample_weight.shape[0]): + sample_weight = np.tile(sample_weight, (array.shape[1], 1)).T + sorted_idx = np.argsort(array, axis=0) + sorted_weights = _take_along_axis(sample_weight, sorted_idx, axis=0) # Find index of median prediction for each sample - weight_cdf = stable_cumsum(sample_weight[sorted_idx]) - percentile_idx = np.searchsorted( - weight_cdf, (percentile / 100.) * weight_cdf[-1]) - # in rare cases, percentile_idx equals to len(sorted_idx) - percentile_idx = np.clip(percentile_idx, 0, len(sorted_idx)-1) - return array[sorted_idx[percentile_idx]] + weight_cdf = stable_cumsum(sorted_weights, axis=0) + adjusted_percentile = percentile / 100 * weight_cdf[-1] + percentile_idx = np.array([ + np.searchsorted(weight_cdf[:, i], adjusted_percentile[i]) + for i in range(weight_cdf.shape[1]) + ]) + percentile_idx = np.array(percentile_idx) + # In rare cases, percentile_idx equals to sorted_idx.shape[0] + max_idx = sorted_idx.shape[0] - 1 + percentile_idx = np.apply_along_axis(lambda x: np.clip(x, 0, max_idx), + axis=0, arr=percentile_idx) + + col_index = np.arange(array.shape[1]) + percentile_in_sorted = sorted_idx[percentile_idx, col_index] + percentile = array[percentile_in_sorted, col_index] + return percentile[0] if n_dim == 1 else percentile
diff --git a/sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py b/sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py index 6b24f90d0239d..b5bc17eeeb14c 100644 --- a/sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py +++ b/sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py @@ -8,7 +8,6 @@ import pytest from sklearn.utils import check_random_state -from sklearn.utils.stats import _weighted_percentile from sklearn.ensemble._gb_losses import RegressionLossFunction from sklearn.ensemble._gb_losses import LeastSquaresError from sklearn.ensemble._gb_losses import LeastAbsoluteError @@ -103,36 +102,6 @@ def test_sample_weight_init_estimators(): assert_allclose(out, sw_out, rtol=1e-2) -def test_weighted_percentile(): - y = np.empty(102, dtype=np.float64) - y[:50] = 0 - y[-51:] = 2 - y[-1] = 100000 - y[50] = 1 - sw = np.ones(102, dtype=np.float64) - sw[-1] = 0.0 - score = _weighted_percentile(y, sw, 50) - assert score == 1 - - -def test_weighted_percentile_equal(): - y = np.empty(102, dtype=np.float64) - y.fill(0.0) - sw = np.ones(102, dtype=np.float64) - sw[-1] = 0.0 - score = _weighted_percentile(y, sw, 50) - assert score == 0 - - -def test_weighted_percentile_zero_weight(): - y = np.empty(102, dtype=np.float64) - y.fill(1.0) - sw = np.ones(102, dtype=np.float64) - sw.fill(0.0) - score = _weighted_percentile(y, sw, 50) - assert score == 1.0 - - def test_quantile_loss_function(): # Non regression test for the QuantileLossFunction object # There was a sign problem when evaluating the function diff --git a/sklearn/metrics/tests/test_score_objects.py b/sklearn/metrics/tests/test_score_objects.py index f4ef238983c41..f49197a706e70 100644 --- a/sklearn/metrics/tests/test_score_objects.py +++ b/sklearn/metrics/tests/test_score_objects.py @@ -33,7 +33,7 @@ from sklearn.linear_model import Ridge, LogisticRegression, Perceptron from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor from sklearn.datasets import make_blobs -from sklearn.datasets import make_classification +from sklearn.datasets import make_classification, make_regression from sklearn.datasets import make_multilabel_classification from sklearn.datasets import load_diabetes from sklearn.model_selection import train_test_split, cross_val_score @@ -89,7 +89,7 @@ def _make_estimators(X_train, y_train, y_ml_train): # Make estimators that make sense to test various scoring methods sensible_regr = DecisionTreeRegressor(random_state=0) # some of the regressions scorers require strictly positive input. - sensible_regr.fit(X_train, y_train + 1) + sensible_regr.fit(X_train, _require_positive_y(y_train)) sensible_clf = DecisionTreeClassifier(random_state=0) sensible_clf.fit(X_train, y_train) sensible_ml_clf = DecisionTreeClassifier(random_state=0) @@ -474,8 +474,9 @@ def test_raises_on_score_list(): @ignore_warnings -def test_scorer_sample_weight(): - # Test that scorers support sample_weight or raise sensible errors +def test_classification_scorer_sample_weight(): + # Test that classification scorers support sample_weight or raise sensible + # errors # Unlike the metrics invariance test, in the scorer case it's harder # to ensure that, on the classifier output, weighted and unweighted @@ -493,31 +494,70 @@ def test_scorer_sample_weight(): estimator = _make_estimators(X_train, y_train, y_ml_train) for name, scorer in SCORERS.items(): + if name in REGRESSION_SCORERS: + # skip the regression scores + continue if name in MULTILABEL_ONLY_SCORERS: target = y_ml_test else: target = y_test - if name in REQUIRE_POSITIVE_Y_SCORERS: - target = _require_positive_y(target) try: weighted = scorer(estimator[name], X_test, target, sample_weight=sample_weight) ignored = scorer(estimator[name], X_test[10:], target[10:]) unweighted = scorer(estimator[name], X_test, target) assert weighted != unweighted, ( - "scorer {0} behaves identically when " - "called with sample weights: {1} vs " - "{2}".format(name, weighted, unweighted)) + f"scorer {name} behaves identically when called with " + f"sample weights: {weighted} vs {unweighted}") assert_almost_equal(weighted, ignored, - err_msg="scorer {0} behaves differently when " - "ignoring samples and setting sample_weight to" - " 0: {1} vs {2}".format(name, weighted, - ignored)) + err_msg=f"scorer {name} behaves differently " + f"when ignoring samples and setting " + f"sample_weight to 0: {weighted} vs {ignored}") except TypeError as e: assert "sample_weight" in str(e), ( - "scorer {0} raises unhelpful exception when called " - "with sample weights: {1}".format(name, str(e))) + f"scorer {name} raises unhelpful exception when called " + f"with sample weights: {str(e)}") + + +@ignore_warnings +def test_regression_scorer_sample_weight(): + # Test that regression scorers support sample_weight or raise sensible + # errors + + # Odd number of test samples req for neg_median_absolute_error + X, y = make_regression(n_samples=101, n_features=20, random_state=0) + y = _require_positive_y(y) + X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) + + sample_weight = np.ones_like(y_test) + # Odd number req for neg_median_absolute_error + sample_weight[:11] = 0 + + reg = DecisionTreeRegressor(random_state=0) + reg.fit(X_train, y_train) + + for name, scorer in SCORERS.items(): + if name not in REGRESSION_SCORERS: + # skip classification scorers + continue + try: + weighted = scorer(reg, X_test, y_test, + sample_weight=sample_weight) + ignored = scorer(reg, X_test[11:], y_test[11:]) + unweighted = scorer(reg, X_test, y_test) + assert weighted != unweighted, ( + f"scorer {name} behaves identically when called with " + f"sample weights: {weighted} vs {unweighted}") + assert_almost_equal(weighted, ignored, + err_msg=f"scorer {name} behaves differently " + f"when ignoring samples and setting " + f"sample_weight to 0: {weighted} vs {ignored}") + + except TypeError as e: + assert "sample_weight" in str(e), ( + f"scorer {name} raises unhelpful exception when called " + f"with sample weights: {str(e)}") @pytest.mark.parametrize('name', SCORERS) diff --git a/sklearn/utils/tests/test_stats.py b/sklearn/utils/tests/test_stats.py new file mode 100644 index 0000000000000..fe0d267393db0 --- /dev/null +++ b/sklearn/utils/tests/test_stats.py @@ -0,0 +1,89 @@ +import numpy as np +from numpy.testing import assert_allclose +from pytest import approx + +from sklearn.utils.stats import _weighted_percentile + + +def test_weighted_percentile(): + y = np.empty(102, dtype=np.float64) + y[:50] = 0 + y[-51:] = 2 + y[-1] = 100000 + y[50] = 1 + sw = np.ones(102, dtype=np.float64) + sw[-1] = 0.0 + score = _weighted_percentile(y, sw, 50) + assert approx(score) == 1 + + +def test_weighted_percentile_equal(): + y = np.empty(102, dtype=np.float64) + y.fill(0.0) + sw = np.ones(102, dtype=np.float64) + sw[-1] = 0.0 + score = _weighted_percentile(y, sw, 50) + assert score == 0 + + +def test_weighted_percentile_zero_weight(): + y = np.empty(102, dtype=np.float64) + y.fill(1.0) + sw = np.ones(102, dtype=np.float64) + sw.fill(0.0) + score = _weighted_percentile(y, sw, 50) + assert approx(score) == 1.0 + + +def test_weighted_median_equal_weights(): + # Checks weighted percentile=0.5 is same as median when weights equal + rng = np.random.RandomState(0) + # Odd size as _weighted_percentile takes lower weighted percentile + x = rng.randint(10, size=11) + weights = np.ones(x.shape) + + median = np.median(x) + w_median = _weighted_percentile(x, weights) + assert median == approx(w_median) + + +def test_weighted_median_integer_weights(): + # Checks weighted percentile=0.5 is same as median when manually weight + # data + rng = np.random.RandomState(0) + x = rng.randint(20, size=10) + weights = rng.choice(5, size=10) + x_manual = np.repeat(x, weights) + + median = np.median(x_manual) + w_median = _weighted_percentile(x, weights) + + assert median == approx(w_median) + + +def test_weighted_percentile_2d(): + # Check for when array 2D and sample_weight 1D + rng = np.random.RandomState(0) + x1 = rng.randint(10, size=10) + w1 = rng.choice(5, size=10) + + x2 = rng.randint(20, size=10) + x_2d = np.vstack((x1, x2)).T + + w_median = _weighted_percentile(x_2d, w1) + p_axis_0 = [ + _weighted_percentile(x_2d[:, i], w1) + for i in range(x_2d.shape[1]) + ] + assert_allclose(w_median, p_axis_0) + + # Check when array and sample_weight boht 2D + w2 = rng.choice(5, size=10) + w_2d = np.vstack((w1, w2)).T + + w_median = _weighted_percentile(x_2d, w_2d) + p_axis_0 = [ + _weighted_percentile(x_2d[:, i], w_2d[:, i]) + for i in range(x_2d.shape[1]) + ] + assert_allclose(w_median, p_axis_0)
[ { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex db6959fcc164f..76ec91d93e264 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -76,7 +76,13 @@ Changelog\n attribute name/path or a `callable` for extracting feature importance from\n the estimator. :pr:`15361` by :user:`Venkatachalam N <venkyyuvy>`\n \n- \n+:mod:`sklearn.metrics`\n+......................\n+\n+- |Enhancement| Add `sample_weight` parameter to\n+ :class:`metrics.median_absolute_error`.\n+ :pr:`17225` by :user:`Lucy Liu <lucyleeow>`.\n+\n :mod:`sklearn.tree`\n ...................\n \n" } ]
0.24
2f26540ee99cb4519d7471933359913c7be36ac9
[ "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[precision_macro]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[recall]", "sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py::test_lad_equals_quantile_50[0]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[recall_weighted]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[jaccard_samples]", "sklearn/metrics/tests/test_score_objects.py::test_multimetric_scorer_calls_method_once[scorers2-1-1-0]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[neg_root_mean_squared_error]", "sklearn/metrics/tests/test_score_objects.py::test_multiclass_roc_proba_scorer[roc_auc_ovo-metric1]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[balanced_accuracy]", "sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py::test_sample_weight_init_estimators", "sklearn/metrics/tests/test_score_objects.py::test_supervised_cluster_scorers", "sklearn/metrics/tests/test_score_objects.py::test_make_scorer", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[accuracy]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[normalized_mutual_info_score]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[f1]", "sklearn/utils/tests/test_stats.py::test_weighted_percentile_equal", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[roc_auc_ovr_weighted]", "sklearn/metrics/tests/test_score_objects.py::test_classification_scorer_sample_weight", "sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py::test_sample_weight_deviance", "sklearn/metrics/tests/test_score_objects.py::test_thresholded_scorers_multilabel_indicator_data", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[precision_samples]", "sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py::test_lad_equals_quantile_50[1]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[jaccard]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[roc_auc_ovo]", "sklearn/utils/tests/test_stats.py::test_weighted_percentile", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[precision]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[neg_brier_score]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[precision_micro]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[neg_mean_absolute_error]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[f1_macro]", "sklearn/utils/tests/test_stats.py::test_weighted_median_equal_weights", "sklearn/metrics/tests/test_score_objects.py::test_regression_scorers", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[f1_micro]", "sklearn/metrics/tests/test_score_objects.py::test_multiclass_roc_no_proba_scorer_errors[roc_auc_ovr_weighted]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[average_precision]", "sklearn/metrics/tests/test_score_objects.py::test_multiclass_roc_no_proba_scorer_errors[roc_auc_ovr]", "sklearn/metrics/tests/test_score_objects.py::test_multimetric_scorer_calls_method_once[scorers1-1-0-1]", "sklearn/metrics/tests/test_score_objects.py::test_check_scoring_gridsearchcv", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[recall_macro]", "sklearn/metrics/tests/test_score_objects.py::test_multimetric_scorer_sanity_check", "sklearn/metrics/tests/test_score_objects.py::test_multiclass_roc_no_proba_scorer_errors[roc_auc_ovo]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[neg_log_loss]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[f1_weighted]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[recall_micro]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[jaccard_micro]", "sklearn/metrics/tests/test_score_objects.py::test_multiclass_roc_proba_scorer[roc_auc_ovr_weighted-metric2]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[neg_mean_squared_error]", "sklearn/metrics/tests/test_score_objects.py::test_multiclass_roc_proba_scorer[roc_auc_ovo_weighted-metric3]", "sklearn/metrics/tests/test_score_objects.py::test_multiclass_roc_proba_scorer[roc_auc_ovr-metric0]", "sklearn/metrics/tests/test_score_objects.py::test_thresholded_scorers", "sklearn/metrics/tests/test_score_objects.py::test_multimetric_scorer_calls_method_once_regressor_threshold", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[adjusted_mutual_info_score]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[roc_auc]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[v_measure_score]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[mutual_info_score]", "sklearn/metrics/tests/test_score_objects.py::test_regression_scorer_sample_weight", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[homogeneity_score]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[neg_mean_squared_log_error]", "sklearn/metrics/tests/test_score_objects.py::test_multiclass_roc_proba_scorer_label", "sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py::test_init_raw_predictions_values", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[neg_mean_gamma_deviance]", "sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py::test_lad_equals_quantile_50[4]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[fowlkes_mallows_score]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[neg_mean_poisson_deviance]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[adjusted_rand_score]", "sklearn/utils/tests/test_stats.py::test_weighted_median_integer_weights", "sklearn/metrics/tests/test_score_objects.py::test_classification_scores", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[jaccard_weighted]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[roc_auc_ovo_weighted]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[max_error]", "sklearn/metrics/tests/test_score_objects.py::test_multimetric_scorer_calls_method_once_classifier_no_decision", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[roc_auc_ovr]", "sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py::test_quantile_loss_function", "sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py::test_sample_weight_smoke", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[completeness_score]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[jaccard_macro]", "sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py::test_lad_equals_quantile_50[2]", "sklearn/metrics/tests/test_score_objects.py::test_all_scorers_repr", "sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py::test_lad_equals_quantile_50[3]", "sklearn/metrics/tests/test_score_objects.py::test_raises_on_score_list", "sklearn/metrics/tests/test_score_objects.py::test_check_scoring_and_check_multimetric_scoring", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[neg_median_absolute_error]", "sklearn/metrics/tests/test_score_objects.py::test_scoring_is_not_metric", "sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py::test_init_raw_predictions_shapes", "sklearn/metrics/tests/test_score_objects.py::test_multimetric_scorer_calls_method_once[scorers0-1-1-1]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[recall_samples]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[precision_weighted]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[explained_variance]", "sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py::test_binomial_deviance", "sklearn/metrics/tests/test_score_objects.py::test_multiclass_roc_no_proba_scorer_errors[roc_auc_ovo_weighted]", "sklearn/utils/tests/test_stats.py::test_weighted_percentile_zero_weight", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[r2]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[f1_samples]" ]
[ "sklearn/utils/tests/test_stats.py::test_weighted_percentile_2d" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex db6959fcc164f..76ec91d93e264 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -76,7 +76,13 @@ Changelog\n attribute name/path or a `callable` for extracting feature importance from\n the estimator. :pr:`<PRID>` by :user:`<NAME>`\n \n- \n+:mod:`sklearn.metrics`\n+......................\n+\n+- |Enhancement| Add `sample_weight` parameter to\n+ :class:`metrics.median_absolute_error`.\n+ :pr:`<PRID>` by :user:`<NAME>`.\n+\n :mod:`sklearn.tree`\n ...................\n \n" } ]
diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index db6959fcc164f..76ec91d93e264 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -76,7 +76,13 @@ Changelog attribute name/path or a `callable` for extracting feature importance from the estimator. :pr:`<PRID>` by :user:`<NAME>` - +:mod:`sklearn.metrics` +...................... + +- |Enhancement| Add `sample_weight` parameter to + :class:`metrics.median_absolute_error`. + :pr:`<PRID>` by :user:`<NAME>`. + :mod:`sklearn.tree` ...................
scikit-learn/scikit-learn
scikit-learn__scikit-learn-13900
https://github.com/scikit-learn/scikit-learn/pull/13900
diff --git a/doc/conf.py b/doc/conf.py index ccf5dcd068131..b09c5a15b133d 100644 --- a/doc/conf.py +++ b/doc/conf.py @@ -356,6 +356,7 @@ def __call__(self, directory): # discovered properly by sphinx from sklearn.experimental import enable_hist_gradient_boosting # noqa from sklearn.experimental import enable_iterative_imputer # noqa +from sklearn.experimental import enable_successive_halving # noqa def make_carousel_thumbs(app, exception): diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst index a0ee97aed260a..07fbaf384efd9 100644 --- a/doc/modules/classes.rst +++ b/doc/modules/classes.rst @@ -1194,9 +1194,11 @@ Hyper-parameter optimizers :template: class.rst model_selection.GridSearchCV + model_selection.HalvingGridSearchCV model_selection.ParameterGrid model_selection.ParameterSampler model_selection.RandomizedSearchCV + model_selection.HalvingRandomSearchCV Model validation diff --git a/doc/modules/grid_search.rst b/doc/modules/grid_search.rst index 9d6c1c7e58170..c88a6eb986b5a 100644 --- a/doc/modules/grid_search.rst +++ b/doc/modules/grid_search.rst @@ -30,14 +30,18 @@ A search consists of: - a cross-validation scheme; and - a :ref:`score function <gridsearch_scoring>`. -Some models allow for specialized, efficient parameter search strategies, -:ref:`outlined below <alternative_cv>`. -Two generic approaches to sampling search candidates are provided in +Two generic approaches to parameter search are provided in scikit-learn: for given values, :class:`GridSearchCV` exhaustively considers all parameter combinations, while :class:`RandomizedSearchCV` can sample a given number of candidates from a parameter space with a specified -distribution. After describing these tools we detail -:ref:`best practice <grid_search_tips>` applicable to both approaches. +distribution. Both these tools have successive halving counterparts +:class:`HalvingGridSearchCV` and :class:`HalvingRandomSearchCV`, which can be +much faster at finding a good parameter combination. + +After describing these tools we detail :ref:`best practices +<grid_search_tips>` applicable to these approaches. Some models allow for +specialized, efficient parameter search strategies, outlined in +:ref:`alternative_cv`. Note that it is common that a small subset of those parameters can have a large impact on the predictive or computation performance of the model while others @@ -167,6 +171,373 @@ variable that is log-uniformly distributed between ``1e0`` and ``1e3``:: Random search for hyper-parameter optimization, The Journal of Machine Learning Research (2012) +.. _successive_halving_user_guide: + +Searching for optimal parameters with successive halving +======================================================== + +Scikit-learn also provides the :class:`HalvingGridSearchCV` and +:class:`HalvingRandomSearchCV` estimators that can be used to +search a parameter space using successive halving [1]_ [2]_. Successive +halving (SH) is like a tournament among candidate parameter combinations. +SH is an iterative selection process where all candidates (the +parameter combinations) are evaluated with a small amount of resources at +the first iteration. Only some of these candidates are selected for the next +iteration, which will be allocated more resources. For parameter tuning, the +resource is typically the number of training samples, but it can also be an +arbitrary numeric parameter such as `n_estimators` in a random forest. + +As illustrated in the figure below, only a subset of candidates +'survive' until the last iteration. These are the candidates that have +consistently ranked among the top-scoring candidates across all iterations. +Each iteration is allocated an increasing amount of resources per candidate, +here the number of samples. + +.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_successive_halving_iterations_001.png + :target: ../auto_examples/model_selection/plot_successive_halving_iterations.html + :align: center + +We here briefly describe the main parameters, but each parameter and their +interactions are described in more details in the sections below. The +``factor`` (> 1) parameter controls the rate at which the resources grow, and +the rate at which the number of candidates decreases. In each iteration, the +number of resources per candidate is multiplied by ``factor`` and the number +of candidates is divided by the same factor. Along with ``resource`` and +``min_resources``, ``factor`` is the most important parameter to control the +search in our implementation, though a value of 3 usually works well. +``factor`` effectively controls the number of iterations in +:class:`HalvingGridSearchCV` and the number of candidates (by default) and +iterations in :class:`HalvingRandomSearchCV`. ``aggressive_elimination=True`` +can also be used if the number of available resources is small. More control +is available through tuning the ``min_resources`` parameter. + +These estimators are still **experimental**: their predictions +and their API might change without any deprecation cycle. To use them, you +need to explicitly import ``enable_successive_halving``:: + + >>> # explicitly require this experimental feature + >>> from sklearn.experimental import enable_successive_halving # noqa + >>> # now you can import normally from model_selection + >>> from sklearn.model_selection import HalvingGridSearchCV + >>> from sklearn.model_selection import HalvingRandomSearchCV + +.. topic:: Examples: + + * :ref:`sphx_glr_auto_examples_model_selection_plot_successive_halving_heatmap.py` + * :ref:`sphx_glr_auto_examples_model_selection_plot_successive_halving_iterations.py` + +Choosing ``min_resources`` and the number of candidates +------------------------------------------------------- + +Beside ``factor``, the two main parameters that influence the behaviour of a +successive halving search are the ``min_resources`` parameter, and the +number of candidates (or parameter combinations) that are evaluated. +``min_resources`` is the amount of resources allocated at the first +iteration for each candidate. The number of candidates is specified directly +in :class:`HalvingRandomSearchCV`, and is determined from the ``param_grid`` +parameter of :class:`HalvingGridSearchCV`. + +Consider a case where the resource is the number of samples, and where we +have 1000 samples. In theory, with ``min_resources=10`` and ``factor=2``, we +are able to run **at most** 7 iterations with the following number of +samples: ``[10, 20, 40, 80, 160, 320, 640]``. + +But depending on the number of candidates, we might run less than 7 +iterations: if we start with a **small** number of candidates, the last +iteration might use less than 640 samples, which means not using all the +available resources (samples). For example if we start with 5 candidates, we +only need 2 iterations: 5 candidates for the first iteration, then +`5 // 2 = 2` candidates at the second iteration, after which we know which +candidate performs the best (so we don't need a third one). We would only be +using at most 20 samples which is a waste since we have 1000 samples at our +disposal. On the other hand, if we start with a **high** number of +candidates, we might end up with a lot of candidates at the last iteration, +which may not always be ideal: it means that many candidates will run with +the full resources, basically reducing the procedure to standard search. + +In the case of :class:`HalvingRandomSearchCV`, the number of candidates is set +by default such that the last iteration uses as much of the available +resources as possible. For :class:`HalvingGridSearchCV`, the number of +candidates is determined by the `param_grid` parameter. Changing the value of +``min_resources`` will impact the number of possible iterations, and as a +result will also have an effect on the ideal number of candidates. + +Another consideration when choosing ``min_resources`` is whether or not it +is easy to discriminate between good and bad candidates with a small amount +of resources. For example, if you need a lot of samples to distinguish +between good and bad parameters, a high ``min_resources`` is recommended. On +the other hand if the distinction is clear even with a small amount of +samples, then a small ``min_resources`` may be preferable since it would +speed up the computation. + +Notice in the example above that the last iteration does not use the maximum +amount of resources available: 1000 samples are available, yet only 640 are +used, at most. By default, both :class:`HalvingRandomSearchCV` and +:class:`HalvingGridSearchCV` try to use as many resources as possible in the +last iteration, with the constraint that this amount of resources must be a +multiple of both `min_resources` and `factor` (this constraint will be clear +in the next section). :class:`HalvingRandomSearchCV` achieves this by +sampling the right amount of candidates, while :class:`HalvingGridSearchCV` +achieves this by properly setting `min_resources`. Please see +:ref:`exhausting_the_resources` for details. + +.. _amount_of_resource_and_number_of_candidates: + +Amount of resource and number of candidates at each iteration +------------------------------------------------------------- + +At any iteration `i`, each candidate is allocated a given amount of resources +which we denote `n_resources_i`. This quantity is controlled by the +parameters ``factor`` and ``min_resources`` as follows (`factor` is strictly +greater than 1):: + + n_resources_i = factor**i * min_resources, + +or equivalently:: + + n_resources_{i+1} = n_resources_i * factor + +where ``min_resources == n_resources_0`` is the amount of resources used at +the first iteration. ``factor`` also defines the proportions of candidates +that will be selected for the next iteration:: + + n_candidates_i = n_candidates // (factor ** i) + +or equivalently:: + + n_candidates_0 = n_candidates + n_candidates_{i+1} = n_candidates_i // factor + +So in the first iteration, we use ``min_resources`` resources +``n_candidates`` times. In the second iteration, we use ``min_resources * +factor`` resources ``n_candidates // factor`` times. The third again +multiplies the resources per candidate and divides the number of candidates. +This process stops when the maximum amount of resource per candidate is +reached, or when we have identified the best candidate. The best candidate +is identified at the iteration that is evaluating `factor` or less candidates +(see just below for an explanation). + +Here is an example with ``min_resources=3`` and ``factor=2``, starting with +70 candidates: + ++-----------------------+-----------------------+ +| ``n_resources_i`` | ``n_candidates_i`` | ++=======================+=======================+ +| 3 (=min_resources) | 70 (=n_candidates) | ++-----------------------+-----------------------+ +| 3 * 2 = 6 | 70 // 2 = 35 | ++-----------------------+-----------------------+ +| 6 * 2 = 12 | 35 // 2 = 17 | ++-----------------------+-----------------------+ +| 12 * 2 = 24 | 17 // 2 = 8 | ++-----------------------+-----------------------+ +| 24 * 2 = 48 | 8 // 2 = 4 | ++-----------------------+-----------------------+ +| 48 * 2 = 96 | 4 // 2 = 2 | ++-----------------------+-----------------------+ + +We can note that: + +- the process stops at the first iteration which evaluates `factor=2` + candidates: the best candidate is the best out of these 2 candidates. It + is not necessary to run an additional iteration, since it would only + evaluate one candidate (namely the best one, which we have already + identified). For this reason, in general, we want the last iteration to + run at most ``factor`` candidates. If the last iteration evaluates more + than `factor` candidates, then this last iteration reduces to a regular + search (as in :class:`RandomizedSearchCV` or :class:`GridSearchCV`). +- each ``n_resources_i`` is a multiple of both ``factor`` and + ``min_resources`` (which is confirmed by its definition above). + +The amount of resources that is used at each iteration can be found in the +`n_resources_` attribute. + +Choosing a resource +------------------- + +By default, the resource is defined in terms of number of samples. That is, +each iteration will use an increasing amount of samples to train on. You can +however manually specify a parameter to use as the resource with the +``resource`` parameter. Here is an example where the resource is defined in +terms of the number of estimators of a random forest:: + + >>> from sklearn.datasets import make_classification + >>> from sklearn.ensemble import RandomForestClassifier + >>> from sklearn.experimental import enable_successive_halving # noqa + >>> from sklearn.model_selection import HalvingGridSearchCV + >>> import pandas as pd + >>> + >>> param_grid = {'max_depth': [3, 5, 10], + ... 'min_samples_split': [2, 5, 10]} + >>> base_estimator = RandomForestClassifier(random_state=0) + >>> X, y = make_classification(n_samples=1000, random_state=0) + >>> sh = HalvingGridSearchCV(base_estimator, param_grid, cv=5, + ... factor=2, resource='n_estimators', + ... max_resources=30).fit(X, y) + >>> sh.best_estimator_ + RandomForestClassifier(max_depth=5, n_estimators=24, random_state=0) + +Note that it is not possible to budget on a parameter that is part of the +parameter grid. + +.. _exhausting_the_resources: + +Exhausting the available resources +---------------------------------- + +As mentioned above, the number of resources that is used at each iteration +depends on the `min_resources` parameter. +If you have a lot of resources available but start with a low number of +resources, some of them might be wasted (i.e. not used):: + + >>> from sklearn.datasets import make_classification + >>> from sklearn.svm import SVC + >>> from sklearn.experimental import enable_successive_halving # noqa + >>> from sklearn.model_selection import HalvingGridSearchCV + >>> import pandas as pd + >>> param_grid= {'kernel': ('linear', 'rbf'), + ... 'C': [1, 10, 100]} + >>> base_estimator = SVC(gamma='scale') + >>> X, y = make_classification(n_samples=1000) + >>> sh = HalvingGridSearchCV(base_estimator, param_grid, cv=5, + ... factor=2, min_resources=20).fit(X, y) + >>> sh.n_resources_ + [20, 40, 80] + +The search process will only use 80 resources at most, while our maximum +amount of available resources is ``n_samples=1000``. Here, we have +``min_resources = r_0 = 20``. + +For :class:`HalvingGridSearchCV`, by default, the `min_resources` parameter +is set to 'exhaust'. This means that `min_resources` is automatically set +such that the last iteration can use as many resources as possible, within +the `max_resources` limit:: + + >>> sh = HalvingGridSearchCV(base_estimator, param_grid, cv=5, + ... factor=2, min_resources='exhaust').fit(X, y) + >>> sh.n_resources_ + [250, 500, 1000] + +`min_resources` was here automatically set to 250, which results in the last +iteration using all the resources. The exact value that is used depends on +the number of candidate parameter, on `max_resources` and on `factor`. + +For :class:`HalvingRandomSearchCV`, exhausting the resources can be done in 2 +ways: + +- by setting `min_resources='exhaust'`, just like for + :class:`HalvingGridSearchCV`; +- by setting `n_candidates='exhaust'`. + +Both options are mutally exclusive: using `min_resources='exhaust'` requires +knowing the number of candidates, and symmetrically `n_candidates='exhaust'` +requires knowing `min_resources`. + +In general, exhausting the total number of resources leads to a better final +candidate parameter, and is slightly more time-intensive. + +.. _aggressive_elimination: + +Aggressive elimination of candidates +------------------------------------ + +Ideally, we want the last iteration to evaluate ``factor`` candidates (see +:ref:`amount_of_resource_and_number_of_candidates`). We then just have to +pick the best one. When the number of available resources is small with +respect to the number of candidates, the last iteration may have to evaluate +more than ``factor`` candidates:: + + >>> from sklearn.datasets import make_classification + >>> from sklearn.svm import SVC + >>> from sklearn.experimental import enable_successive_halving # noqa + >>> from sklearn.model_selection import HalvingGridSearchCV + >>> import pandas as pd + >>> + >>> + >>> param_grid = {'kernel': ('linear', 'rbf'), + ... 'C': [1, 10, 100]} + >>> base_estimator = SVC(gamma='scale') + >>> X, y = make_classification(n_samples=1000) + >>> sh = HalvingGridSearchCV(base_estimator, param_grid, cv=5, + ... factor=2, max_resources=40, + ... aggressive_elimination=False).fit(X, y) + >>> sh.n_resources_ + [20, 40] + >>> sh.n_candidates_ + [6, 3] + +Since we cannot use more than ``max_resources=40`` resources, the process +has to stop at the second iteration which evaluates more than ``factor=2`` +candidates. + +Using the ``aggressive_elimination`` parameter, you can force the search +process to end up with less than ``factor`` candidates at the last +iteration. To do this, the process will eliminate as many candidates as +necessary using ``min_resources`` resources:: + + >>> sh = HalvingGridSearchCV(base_estimator, param_grid, cv=5, + ... factor=2, + ... max_resources=40, + ... aggressive_elimination=True, + ... ).fit(X, y) + >>> sh.n_resources_ + [20, 20, 40] + >>> sh.n_candidates_ + [6, 3, 2] + +Notice that we end with 2 candidates at the last iteration since we have +eliminated enough candidates during the first iterations, using ``n_resources = +min_resources = 20``. + +.. _successive_halving_cv_results: + +Analysing results with the `cv_results_` attribute +-------------------------------------------------- + +The ``cv_results_`` attribute contains useful information for analysing the +results of a search. It can be converted to a pandas dataframe with ``df = +pd.DataFrame(est.cv_results_)``. The ``cv_results_`` attribute of +:class:`HalvingGridSearchCV` and :class:`HalvingRandomSearchCV` is similar +to that of :class:`GridSearchCV` and :class:`RandomizedSearchCV`, with +additional information related to the successive halving process. + +Here is an example with some of the columns of a (truncated) dataframe: + +==== ====== =============== ================= ======================================================================================= + .. iter n_resources mean_test_score params +==== ====== =============== ================= ======================================================================================= + 0 0 125 0.983667 {'criterion': 'entropy', 'max_depth': None, 'max_features': 9, 'min_samples_split': 5} + 1 0 125 0.983667 {'criterion': 'gini', 'max_depth': None, 'max_features': 8, 'min_samples_split': 7} + 2 0 125 0.983667 {'criterion': 'gini', 'max_depth': None, 'max_features': 10, 'min_samples_split': 10} + 3 0 125 0.983667 {'criterion': 'entropy', 'max_depth': None, 'max_features': 6, 'min_samples_split': 6} + ... ... ... ... ... + 15 2 500 0.951958 {'criterion': 'entropy', 'max_depth': None, 'max_features': 9, 'min_samples_split': 10} + 16 2 500 0.947958 {'criterion': 'gini', 'max_depth': None, 'max_features': 10, 'min_samples_split': 10} + 17 2 500 0.951958 {'criterion': 'gini', 'max_depth': None, 'max_features': 10, 'min_samples_split': 4} + 18 3 1000 0.961009 {'criterion': 'entropy', 'max_depth': None, 'max_features': 9, 'min_samples_split': 10} + 19 3 1000 0.955989 {'criterion': 'gini', 'max_depth': None, 'max_features': 10, 'min_samples_split': 4} +==== ====== =============== ================= ======================================================================================= + +Each row corresponds to a given parameter combination (a candidate) and a given +iteration. The iteration is given by the ``iter`` column. The ``n_resources`` +column tells you how many resources were used. + +In the example above, the best parameter combination is ``{'criterion': +'entropy', 'max_depth': None, 'max_features': 9, 'min_samples_split': 10}`` +since it has reached the last iteration (3) with the highest score: +0.96. + +.. topic:: References: + + .. [1] K. Jamieson, A. Talwalkar, + `Non-stochastic Best Arm Identification and Hyperparameter + Optimization <http://proceedings.mlr.press/v51/jamieson16.html>`_, in + proc. of Machine Learning Research, 2016. + .. [2] L. Li, K. Jamieson, G. DeSalvo, A. Rostamizadeh, A. Talwalkar, + `Hyperband: A Novel Bandit-Based Approach to Hyperparameter Optimization + <https://arxiv.org/abs/1603.06560>`_, in Machine Learning Research + 18, 2018. + .. _grid_search_tips: Tips for parameter search @@ -183,18 +554,16 @@ to evaluate a parameter setting. These are the :func:`sklearn.metrics.r2_score` for regression. For some applications, other scoring functions are better suited (for example in unbalanced classification, the accuracy score is often uninformative). An alternative -scoring function can be specified via the ``scoring`` parameter to -:class:`GridSearchCV`, :class:`RandomizedSearchCV` and many of the -specialized cross-validation tools described below. -See :ref:`scoring_parameter` for more details. +scoring function can be specified via the ``scoring`` parameter of most +parameter search tools. See :ref:`scoring_parameter` for more details. .. _multimetric_grid_search: Specifying multiple metrics for evaluation ------------------------------------------ -``GridSearchCV`` and ``RandomizedSearchCV`` allow specifying multiple metrics -for the ``scoring`` parameter. +:class:`GridSearchCV` and :class:`RandomizedSearchCV` allow specifying +multiple metrics for the ``scoring`` parameter. Multimetric scoring can either be specified as a list of strings of predefined scores names or a dict mapping the scorer name to the scorer function and/or @@ -209,6 +578,9 @@ result in an error when using multiple metrics. See :ref:`sphx_glr_auto_examples_model_selection_plot_multi_metric_evaluation.py` for an example usage. +:class:`HalvingRandomSearchCV` and :class:`HalvingGridSearchCV` do not support +multimetric scoring. + .. _composite_grid_search: Composite estimators and parameter spaces @@ -253,6 +625,8 @@ levels of nesting:: ... 'model__base_estimator__max_depth': [2, 4, 6, 8]} >>> search = GridSearchCV(pipe, param_grid, cv=5).fit(X, y) +Please refer to :ref:`pipeline` for performing parameter searches over +pipelines. Model selection: development and evaluation ------------------------------------------- @@ -263,7 +637,7 @@ to use the labeled data to "train" the parameters of the grid. When evaluating the resulting model it is important to do it on held-out samples that were not seen during the grid search process: it is recommended to split the data into a **development set** (to -be fed to the ``GridSearchCV`` instance) and an **evaluation set** +be fed to the :class:`GridSearchCV` instance) and an **evaluation set** to compute performance metrics. This can be done by using the :func:`train_test_split` @@ -272,10 +646,10 @@ utility function. Parallelism ----------- -:class:`GridSearchCV` and :class:`RandomizedSearchCV` evaluate each parameter -setting independently. Computations can be run in parallel if your OS -supports it, by using the keyword ``n_jobs=-1``. See function signature for -more details. +The parameter search tools evaluate each parameter combination on each data +fold independently. Computations can be run in parallel by using the keyword +``n_jobs=-1``. See function signature for more details, and also the Glossary +entry for :term:`n_jobs`. Robustness to failure --------------------- diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index c57f097ec3218..e757fee299af7 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -412,6 +412,14 @@ Changelog :pr:`17478` by :user:`Teon Brooks <teonbrooks>` and :user:`Mohamed Maskani <maskani-moh>`. +- |Feature| Added (experimental) parameter search estimators + :class:`model_selection.HalvingRandomSearchCV` and + :class:`model_selection.HalvingGridSearchCV` which implement Successive + Halving, and can be used as a drop-in replacements for + :class:`model_selection.RandomizedSearchCV` and + :class:`model_selection.GridSearchCV`. :pr:`13900` by `Nicolas Hug`_, `Joel + Nothman`_ and `Andreas Müller`_. + - |Fix| Fixed the `len` of :class:`model_selection.ParameterSampler` when all distributions are lists and `n_iter` is more than the number of unique parameter combinations. :pr:`18222` by `Nicolas Hug`_. diff --git a/examples/model_selection/plot_successive_halving_heatmap.py b/examples/model_selection/plot_successive_halving_heatmap.py new file mode 100644 index 0000000000000..6964fafd77811 --- /dev/null +++ b/examples/model_selection/plot_successive_halving_heatmap.py @@ -0,0 +1,122 @@ +""" +Comparison between grid search and successive halving +===================================================== + +This example compares the parameter search performed by +:class:`~sklearn.model_selection.HalvingGridSearchCV` and +:class:`~sklearn.model_selection.GridSearchCV`. + +""" +from time import time + +import matplotlib.pyplot as plt +import numpy as np +import pandas as pd + +from sklearn.svm import SVC +from sklearn import datasets +from sklearn.model_selection import GridSearchCV +from sklearn.experimental import enable_successive_halving # noqa +from sklearn.model_selection import HalvingGridSearchCV + + +print(__doc__) + +# %% +# We first define the parameter space for an :class:`~sklearn.svm.SVC` +# estimator, and compute the time required to train a +# :class:`~sklearn.model_selection.HalvingGridSearchCV` instance, as well as a +# :class:`~sklearn.model_selection.GridSearchCV` instance. + +rng = np.random.RandomState(0) +X, y = datasets.make_classification(n_samples=1000, random_state=rng) + +gammas = [1e-1, 1e-2, 1e-3, 1e-4, 1e-5, 1e-6, 1e-7] +Cs = [1, 10, 100, 1e3, 1e4, 1e5] +param_grid = {'gamma': gammas, 'C': Cs} + +clf = SVC(random_state=rng) + +tic = time() +gsh = HalvingGridSearchCV(estimator=clf, param_grid=param_grid, factor=2, + random_state=rng) +gsh.fit(X, y) +gsh_time = time() - tic + +tic = time() +gs = GridSearchCV(estimator=clf, param_grid=param_grid) +gs.fit(X, y) +gs_time = time() - tic + +# %% +# We now plot heatmaps for both search estimators. + + +def make_heatmap(ax, gs, is_sh=False, make_cbar=False): + """Helper to make a heatmap.""" + results = pd.DataFrame.from_dict(gs.cv_results_) + results['params_str'] = results.params.apply(str) + if is_sh: + # SH dataframe: get mean_test_score values for the highest iter + scores_matrix = results.sort_values('iter').pivot_table( + index='param_gamma', columns='param_C', + values='mean_test_score', aggfunc='last' + ) + else: + scores_matrix = results.pivot(index='param_gamma', columns='param_C', + values='mean_test_score') + + im = ax.imshow(scores_matrix) + + ax.set_xticks(np.arange(len(Cs))) + ax.set_xticklabels(['{:.0E}'.format(x) for x in Cs]) + ax.set_xlabel('C', fontsize=15) + + ax.set_yticks(np.arange(len(gammas))) + ax.set_yticklabels(['{:.0E}'.format(x) for x in gammas]) + ax.set_ylabel('gamma', fontsize=15) + + # Rotate the tick labels and set their alignment. + plt.setp(ax.get_xticklabels(), rotation=45, ha="right", + rotation_mode="anchor") + + if is_sh: + iterations = results.pivot_table(index='param_gamma', + columns='param_C', values='iter', + aggfunc='max').values + for i in range(len(gammas)): + for j in range(len(Cs)): + ax.text(j, i, iterations[i, j], + ha="center", va="center", color="w", fontsize=20) + + if make_cbar: + fig.subplots_adjust(right=0.8) + cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7]) + fig.colorbar(im, cax=cbar_ax) + cbar_ax.set_ylabel('mean_test_score', rotation=-90, va="bottom", + fontsize=15) + + +fig, axes = plt.subplots(ncols=2, sharey=True) +ax1, ax2 = axes + +make_heatmap(ax1, gsh, is_sh=True) +make_heatmap(ax2, gs, make_cbar=True) + +ax1.set_title('Successive Halving\ntime = {:.3f}s'.format(gsh_time), + fontsize=15) +ax2.set_title('GridSearch\ntime = {:.3f}s'.format(gs_time), fontsize=15) + +plt.show() + +# %% +# The heatmaps show the mean test score of the parameter combinations for an +# :class:`~sklearn.svm.SVC` instance. The +# :class:`~sklearn.model_selection.HalvingGridSearchCV` also shows the +# iteration at which the combinations where last used. The combinations marked +# as ``0`` were only evaluated at the first iteration, while the ones with +# ``5`` are the parameter combinations that are considered the best ones. +# +# We can see that the :class:`~sklearn.model_selection.HalvingGridSearchCV` +# class is able to find parameter combinations that are just as accurate as +# :class:`~sklearn.model_selection.GridSearchCV`, in much less time. diff --git a/examples/model_selection/plot_successive_halving_iterations.py b/examples/model_selection/plot_successive_halving_iterations.py new file mode 100644 index 0000000000000..17723710be7d6 --- /dev/null +++ b/examples/model_selection/plot_successive_halving_iterations.py @@ -0,0 +1,84 @@ +""" +Successive Halving Iterations +============================= + +This example illustrates how a successive halving search ( +:class:`~sklearn.model_selection.HalvingGridSearchCV` and +:class:`~sklearn.model_selection.HalvingRandomSearchCV`) iteratively chooses +the best parameter combination out of multiple candidates. + +""" +import pandas as pd +from sklearn import datasets +import matplotlib.pyplot as plt +from scipy.stats import randint +import numpy as np + +from sklearn.experimental import enable_successive_halving # noqa +from sklearn.model_selection import HalvingRandomSearchCV +from sklearn.ensemble import RandomForestClassifier + + +print(__doc__) + +# %% +# We first define the parameter space and train a +# :class:`~sklearn.model_selection.HalvingRandomSearchCV` instance. + +rng = np.random.RandomState(0) + +X, y = datasets.make_classification(n_samples=700, random_state=rng) + +clf = RandomForestClassifier(n_estimators=20, random_state=rng) + +param_dist = {"max_depth": [3, None], + "max_features": randint(1, 11), + "min_samples_split": randint(2, 11), + "bootstrap": [True, False], + "criterion": ["gini", "entropy"]} + +rsh = HalvingRandomSearchCV( + estimator=clf, + param_distributions=param_dist, + factor=2, + random_state=rng) +rsh.fit(X, y) + +# %% +# We can now use the `cv_results_` attribute of the search estimator to inspect +# and plot the evolution of the search. + +results = pd.DataFrame(rsh.cv_results_) +results['params_str'] = results.params.apply(str) +results.drop_duplicates(subset=('params_str', 'iter'), inplace=True) +mean_scores = results.pivot(index='iter', columns='params_str', + values='mean_test_score') +ax = mean_scores.plot(legend=False, alpha=.6) + +labels = [ + f'iter={i}\nn_samples={rsh.n_resources_[i]}\n' + f'n_candidates={rsh.n_candidates_[i]}' + for i in range(rsh.n_iterations_) +] +ax.set_xticklabels(labels, rotation=45, multialignment='left') +ax.set_title('Scores of candidates over iterations') +ax.set_ylabel('mean test score', fontsize=15) +ax.set_xlabel('iterations', fontsize=15) +plt.tight_layout() +plt.show() + +# %% +# Number of candidates and amount of resource at each iteration +# ------------------------------------------------------------- +# +# At the first iteration, a small amount of resources is used. The resource +# here is the number of samples that the estimators are trained on. All +# candidates are evaluated. +# +# At the second iteration, only the best half of the candidates is evaluated. +# The number of allocated resources is doubled: candidates are evaluated on +# twice as many samples. +# +# This process is repeated until the last iteration, where only 2 candidates +# are left. The best candidate is the candidate that has the best score at the +# last iteration. diff --git a/sklearn/experimental/enable_successive_halving.py b/sklearn/experimental/enable_successive_halving.py new file mode 100644 index 0000000000000..147a622d4fdae --- /dev/null +++ b/sklearn/experimental/enable_successive_halving.py @@ -0,0 +1,35 @@ +"""Enables Successive Halving search-estimators + +The API and results of these estimators might change without any deprecation +cycle. + +Importing this file dynamically sets the +:class:`~sklearn.model_selection.HalvingRandomSearchCV` and +:class:`~sklearn.model_selection.HalvingGridSearchCV` as attributes of the +`model_selection` module:: + + >>> # explicitly require this experimental feature + >>> from sklearn.experimental import enable_successive_halving # noqa + >>> # now you can import normally from model_selection + >>> from sklearn.model_selection import HalvingRandomSearchCV + >>> from sklearn.model_selection import HalvingGridSearchCV + + +The ``# noqa`` comment comment can be removed: it just tells linters like +flake8 to ignore the import, which appears as unused. +""" + +from ..model_selection._search_successive_halving import ( + HalvingRandomSearchCV, + HalvingGridSearchCV +) + +from .. import model_selection + +# use settattr to avoid mypy errors when monkeypatching +setattr(model_selection, "HalvingRandomSearchCV", + HalvingRandomSearchCV) +setattr(model_selection, "HalvingGridSearchCV", + HalvingGridSearchCV) + +model_selection.__all__ += ['HalvingRandomSearchCV', 'HalvingGridSearchCV'] diff --git a/sklearn/model_selection/__init__.py b/sklearn/model_selection/__init__.py index 82a9b9371710d..897183414b5a6 100644 --- a/sklearn/model_selection/__init__.py +++ b/sklearn/model_selection/__init__.py @@ -1,3 +1,5 @@ +import typing + from ._split import BaseCrossValidator from ._split import KFold from ._split import GroupKFold @@ -29,7 +31,15 @@ from ._search import ParameterSampler from ._search import fit_grid_point -__all__ = ('BaseCrossValidator', +if typing.TYPE_CHECKING: + # Avoid errors in type checkers (e.g. mypy) for experimental estimators. + # TODO: remove this check once the estimator is no longer experimental. + from ._search_successive_halving import ( # noqa + HalvingGridSearchCV, HalvingRandomSearchCV + ) + + +__all__ = ['BaseCrossValidator', 'GridSearchCV', 'TimeSeriesSplit', 'KFold', @@ -56,4 +66,4 @@ 'learning_curve', 'permutation_test_score', 'train_test_split', - 'validation_curve') + 'validation_curve'] diff --git a/sklearn/model_selection/_search.py b/sklearn/model_selection/_search.py index 37296686b9369..cade49345d539 100644 --- a/sklearn/model_selection/_search.py +++ b/sklearn/model_selection/_search.py @@ -641,13 +641,39 @@ def _run_search(self, evaluate_candidates): collected evaluation results. This makes it possible to implement Bayesian optimization or more generally sequential model-based optimization by deriving from the BaseSearchCV abstract base class. + For example, Successive Halving is implemented by calling + `evaluate_candidates` multiples times (once per iteration of the SH + process), each time passing a different set of candidates with `X` + and `y` of increasing sizes. Parameters ---------- evaluate_candidates : callable - This callback accepts a list of candidates, where each candidate is - a dict of parameter settings. It returns a dict of all results so - far, formatted like ``cv_results_``. + This callback accepts: + - a list of candidates, where each candidate is a dict of + parameter settings. + - an optional `cv` parameter which can be used to e.g. + evaluate candidates on different dataset splits, or + evaluate candidates on subsampled data (as done in the + SucessiveHaling estimators). By default, the original `cv` + parameter is used, and it is available as a private + `_checked_cv_orig` attribute. + - an optional `more_results` dict. Each key will be added to + the `cv_results_` attribute. Values should be lists of + length `n_candidates` + + It returns a dict of all results so far, formatted like + ``cv_results_``. + + Important note (relevant whether the default cv is used or not): + in randomized splitters, and unless the random_state parameter of + cv was set to an int, calling cv.split() multiple times will + yield different splits. Since cv.split() is called in + evaluate_candidates, this means that candidates will be evaluated + on different splits each time evaluate_candidates is called. This + might be a methodological issue depending on the search strategy + that you're implementing. To prevent randomized splitters from + being used, you may use _split._yields_constant_splits() Examples -------- @@ -705,8 +731,6 @@ def fit(self, X, y=None, *, groups=None, **fit_params): Parameters passed to the ``fit`` method of the estimator """ estimator = self.estimator - cv = check_cv(self.cv, y, classifier=is_classifier(estimator)) - refit_metric = "score" if callable(self.scoring): @@ -721,7 +745,8 @@ def fit(self, X, y=None, *, groups=None, **fit_params): X, y, groups = indexable(X, y, groups) fit_params = _check_fit_params(X, fit_params) - n_splits = cv.get_n_splits(X, y, groups) + cv_orig = check_cv(self.cv, y, classifier=is_classifier(estimator)) + n_splits = cv_orig.get_n_splits(X, y, groups) base_estimator = clone(self.estimator) @@ -740,8 +765,11 @@ def fit(self, X, y=None, *, groups=None, **fit_params): with parallel: all_candidate_params = [] all_out = [] + all_more_results = defaultdict(list) - def evaluate_candidates(candidate_params): + def evaluate_candidates(candidate_params, cv=None, + more_results=None): + cv = cv or cv_orig candidate_params = list(candidate_params) n_candidates = len(candidate_params) @@ -785,10 +813,15 @@ def evaluate_candidates(candidate_params): _insert_error_scores(out, self.error_score) all_candidate_params.extend(candidate_params) all_out.extend(out) + if more_results is not None: + for key, value in more_results.items(): + all_more_results[key].extend(value) nonlocal results results = self._format_results( - all_candidate_params, n_splits, all_out) + all_candidate_params, n_splits, all_out, + all_more_results) + return results self._run_search(evaluate_candidates) @@ -844,11 +877,12 @@ def evaluate_candidates(candidate_params): return self - def _format_results(self, candidate_params, n_splits, out): + def _format_results(self, candidate_params, n_splits, out, + more_results=None): n_candidates = len(candidate_params) out = _aggregate_score_dicts(out) - results = {} + results = dict(more_results or {}) def _store(key_name, array, weights=None, splits=False, rank=False): """A small helper to store the scores/times to the cv_results_""" diff --git a/sklearn/model_selection/_search_successive_halving.py b/sklearn/model_selection/_search_successive_halving.py new file mode 100644 index 0000000000000..064948a30f006 --- /dev/null +++ b/sklearn/model_selection/_search_successive_halving.py @@ -0,0 +1,910 @@ +from math import ceil, floor, log +from abc import abstractmethod +from numbers import Integral + +import numpy as np +from ._search import _check_param_grid +from ._search import BaseSearchCV +from . import ParameterGrid, ParameterSampler +from ..utils.validation import _num_samples +from ..base import is_classifier +from ._split import check_cv, _yields_constant_splits +from ..utils import resample + + +__all__ = ['HalvingGridSearchCV', 'HalvingRandomSearchCV'] + + +class _SubsampleMetaSplitter: + """Splitter that subsamples a given fraction of the dataset""" + def __init__(self, *, base_cv, fraction, subsample_test, random_state): + self.base_cv = base_cv + self.fraction = fraction + self.subsample_test = subsample_test + self.random_state = random_state + + def split(self, X, y, groups=None): + for train_idx, test_idx in self.base_cv.split(X, y, groups): + train_idx = resample( + train_idx, replace=False, random_state=self.random_state, + n_samples=int(self.fraction * train_idx.shape[0]) + ) + if self.subsample_test: + test_idx = resample( + test_idx, replace=False, random_state=self.random_state, + n_samples=int(self.fraction * test_idx.shape[0]) + ) + yield train_idx, test_idx + + +def _refit_callable(results): + # Custom refit callable to return the index of the best candidate. We want + # the best candidate out of the last iteration. By default BaseSearchCV + # would return the best candidate out of all iterations. + + last_iter = np.max(results['iter']) + last_iter_indices = np.flatnonzero(results['iter'] == last_iter) + best_idx = np.argmax(results['mean_test_score'][last_iter_indices]) + return last_iter_indices[best_idx] + + +def _top_k(results, k, itr): + # Return the best candidates of a given iteration + iteration, mean_test_score, params = ( + np.asarray(a) for a in (results['iter'], + results['mean_test_score'], + results['params']) + ) + iter_indices = np.flatnonzero(iteration == itr) + sorted_indices = np.argsort(mean_test_score[iter_indices]) + return np.array(params[iter_indices][sorted_indices[-k:]]) + + +class BaseSuccessiveHalving(BaseSearchCV): + """Implements successive halving. + + Ref: + Almost optimal exploration in multi-armed bandits, ICML 13 + Zohar Karnin, Tomer Koren, Oren Somekh + """ + def __init__(self, estimator, *, scoring=None, + n_jobs=None, refit=True, cv=5, verbose=0, random_state=None, + error_score=np.nan, return_train_score=True, + max_resources='auto', min_resources='exhaust', + resource='n_samples', factor=3, aggressive_elimination=False): + + refit = _refit_callable if refit else False + super().__init__(estimator, scoring=scoring, + n_jobs=n_jobs, refit=refit, cv=cv, + verbose=verbose, + error_score=error_score, + return_train_score=return_train_score) + + self.random_state = random_state + self.max_resources = max_resources + self.resource = resource + self.factor = factor + self.min_resources = min_resources + self.aggressive_elimination = aggressive_elimination + + def _check_input_parameters(self, X, y, groups): + + if self.scoring is not None and not (isinstance(self.scoring, str) + or callable(self.scoring)): + raise ValueError('scoring parameter must be a string, ' + 'a callable or None. Multimetric scoring is not ' + 'supported.') + + # We need to enforce that successive calls to cv.split() yield the same + # splits: see https://github.com/scikit-learn/scikit-learn/issues/15149 + if not _yields_constant_splits(self._checked_cv_orig): + raise ValueError( + "The cv parameter must yield consistent folds across " + "calls to split(). Set its random_state to an int, or set " + "shuffle=False." + ) + + if (self.resource != 'n_samples' + and self.resource not in self.estimator.get_params()): + raise ValueError( + f'Cannot use resource={self.resource} which is not supported ' + f'by estimator {self.estimator.__class__.__name__}' + ) + + if (isinstance(self.max_resources, str) and + self.max_resources != 'auto'): + raise ValueError( + "max_resources must be either 'auto' or a positive integer" + ) + if self.max_resources != 'auto' and ( + not isinstance(self.max_resources, Integral) or + self.max_resources <= 0): + raise ValueError( + "max_resources must be either 'auto' or a positive integer" + ) + + if self.min_resources not in ('smallest', 'exhaust') and ( + not isinstance(self.min_resources, Integral) or + self.min_resources <= 0): + raise ValueError( + "min_resources must be either 'smallest', 'exhaust', " + "or a positive integer " + "no greater than max_resources." + ) + + if isinstance(self, HalvingRandomSearchCV): + if self.min_resources == self.n_candidates == 'exhaust': + # for n_candidates=exhaust to work, we need to know what + # min_resources is. Similarly min_resources=exhaust needs to + # know the actual number of candidates. + raise ValueError( + "n_candidates and min_resources cannot be both set to " + "'exhaust'." + ) + if self.n_candidates != 'exhaust' and ( + not isinstance(self.n_candidates, Integral) or + self.n_candidates <= 0): + raise ValueError( + "n_candidates must be either 'exhaust' " + "or a positive integer" + ) + + self.min_resources_ = self.min_resources + if self.min_resources_ in ('smallest', 'exhaust'): + if self.resource == 'n_samples': + n_splits = self._checked_cv_orig.get_n_splits(X, y, groups) + # please see https://gph.is/1KjihQe for a justification + magic_factor = 2 + self.min_resources_ = n_splits * magic_factor + if is_classifier(self.estimator): + n_classes = np.unique(y).shape[0] + self.min_resources_ *= n_classes + else: + self.min_resources_ = 1 + # if 'exhaust', min_resources_ might be set to a higher value later + # in _run_search + + self.max_resources_ = self.max_resources + if self.max_resources_ == 'auto': + if not self.resource == 'n_samples': + raise ValueError( + "max_resources can only be 'auto' if resource='n_samples'") + self.max_resources_ = _num_samples(X) + + if self.min_resources_ > self.max_resources_: + raise ValueError( + f'min_resources_={self.min_resources_} is greater ' + f'than max_resources_={self.max_resources_}.' + ) + + def fit(self, X, y=None, groups=None, **fit_params): + """Run fit with all sets of parameters. + + Parameters + ---------- + + X : array-like, shape (n_samples, n_features) + Training vector, where n_samples is the number of samples and + n_features is the number of features. + + y : array-like, shape (n_samples,) or (n_samples, n_output), optional + Target relative to X for classification or regression; + None for unsupervised learning. + + groups : array-like of shape (n_samples,), default=None + Group labels for the samples used while splitting the dataset into + train/test set. Only used in conjunction with a "Group" :term:`cv` + instance (e.g., :class:`~sklearn.model_selection.GroupKFold`). + + **fit_params : dict of string -> object + Parameters passed to the ``fit`` method of the estimator + """ + self._checked_cv_orig = check_cv( + self.cv, y, classifier=is_classifier(self.estimator)) + + self._check_input_parameters( + X=X, + y=y, + groups=groups, + ) + + self._n_samples_orig = _num_samples(X) + + super().fit(X, y=y, groups=None, **fit_params) + + # Set best_score_: BaseSearchCV does not set it, as refit is a callable + self.best_score_ = ( + self.cv_results_['mean_test_score'][self.best_index_]) + + return self + + def _run_search(self, evaluate_candidates): + candidate_params = self._generate_candidate_params() + + if self.resource != 'n_samples' and any( + self.resource in candidate for candidate in candidate_params): + # Can only check this now since we need the candidates list + raise ValueError( + f"Cannot use parameter {self.resource} as the resource since " + "it is part of the searched parameters." + ) + + # n_required_iterations is the number of iterations needed so that the + # last iterations evaluates less than `factor` candidates. + n_required_iterations = 1 + floor(log(len(candidate_params), + self.factor)) + + if self.min_resources == 'exhaust': + # To exhaust the resources, we want to start with the biggest + # min_resources possible so that the last (required) iteration + # uses as many resources as possible + last_iteration = n_required_iterations - 1 + self.min_resources_ = max( + self.min_resources_, + self.max_resources_ // self.factor**last_iteration + ) + + # n_possible_iterations is the number of iterations that we can + # actually do starting from min_resources and without exceeding + # max_resources. Depending on max_resources and the number of + # candidates, this may be higher or smaller than + # n_required_iterations. + n_possible_iterations = 1 + floor(log( + self.max_resources_ // self.min_resources_, self.factor)) + + if self.aggressive_elimination: + n_iterations = n_required_iterations + else: + n_iterations = min(n_possible_iterations, n_required_iterations) + + if self.verbose: + print(f'n_iterations: {n_iterations}') + print(f'n_required_iterations: {n_required_iterations}') + print(f'n_possible_iterations: {n_possible_iterations}') + print(f'min_resources_: {self.min_resources_}') + print(f'max_resources_: {self.max_resources_}') + print(f'aggressive_elimination: {self.aggressive_elimination}') + print(f'factor: {self.factor}') + + self.n_resources_ = [] + self.n_candidates_ = [] + + for itr in range(n_iterations): + + power = itr # default + if self.aggressive_elimination: + # this will set n_resources to the initial value (i.e. the + # value of n_resources at the first iteration) for as many + # iterations as needed (while candidates are being + # eliminated), and then go on as usual. + power = max( + 0, + itr - n_required_iterations + n_possible_iterations + ) + + n_resources = int(self.factor**power * self.min_resources_) + # guard, probably not needed + n_resources = min(n_resources, self.max_resources_) + self.n_resources_.append(n_resources) + + n_candidates = len(candidate_params) + self.n_candidates_.append(n_candidates) + + if self.verbose: + print('-' * 10) + print(f'iter: {itr}') + print(f'n_candidates: {n_candidates}') + print(f'n_resources: {n_resources}') + + if self.resource == 'n_samples': + # subsampling will be done in cv.split() + cv = _SubsampleMetaSplitter( + base_cv=self._checked_cv_orig, + fraction=n_resources / self._n_samples_orig, + subsample_test=True, + random_state=self.random_state + ) + + else: + # Need copy so that the n_resources of next iteration does + # not overwrite + candidate_params = [c.copy() for c in candidate_params] + for candidate in candidate_params: + candidate[self.resource] = n_resources + cv = self._checked_cv_orig + + more_results = {'iter': [itr] * n_candidates, + 'n_resources': [n_resources] * n_candidates} + + results = evaluate_candidates(candidate_params, cv, + more_results=more_results) + + n_candidates_to_keep = ceil(n_candidates / self.factor) + candidate_params = _top_k(results, n_candidates_to_keep, itr) + + self.n_remaining_candidates_ = len(candidate_params) + self.n_required_iterations_ = n_required_iterations + self.n_possible_iterations_ = n_possible_iterations + self.n_iterations_ = n_iterations + + @abstractmethod + def _generate_candidate_params(self): + pass + + +class HalvingGridSearchCV(BaseSuccessiveHalving): + """Search over specified parameter values with successive halving. + + The search strategy starts evaluating all the candidates with a small + amount of resources and iteratively selects the best candidates, using + more and more resources. + + Read more in the :ref:`User guide <successive_halving_user_guide>`. + + .. note:: + + This estimator is still **experimental** for now: the predictions + and the API might change without any deprecation cycle. To use it, + you need to explicitly import ``enable_successive_halving``:: + + >>> # explicitly require this experimental feature + >>> from sklearn.experimental import enable_successive_halving # noqa + >>> # now you can import normally from model_selection + >>> from sklearn.model_selection import HalvingGridSearchCV + + Parameters + ---------- + estimator : estimator object. + This is assumed to implement the scikit-learn estimator interface. + Either estimator needs to provide a ``score`` function, + or ``scoring`` must be passed. + + param_grid : dict or list of dictionaries + Dictionary with parameters names (string) as keys and lists of + parameter settings to try as values, or a list of such + dictionaries, in which case the grids spanned by each dictionary + in the list are explored. This enables searching over any sequence + of parameter settings. + + factor : int or float, default=3 + The 'halving' parameter, which determines the proportion of candidates + that are selected for each subsequent iteration. For example, + ``factor=3`` means that only one third of the candidates are selected. + + resource : ``'n_samples'`` or str, default='n_samples' + Defines the resource that increases with each iteration. By default, + the resource is the number of samples. It can also be set to any + parameter of the base estimator that accepts positive integer + values, e.g. 'n_iterations' or 'n_estimators' for a gradient + boosting estimator. In this case ``max_resources`` cannot be 'auto' + and must be set explicitly. + + max_resources : int, default='auto' + The maximum amount of resource that any candidate is allowed to use + for a given iteration. By default, this is set to ``n_samples`` when + ``resource='n_samples'`` (default), else an error is raised. + + min_resources : {'exhaust', 'smallest'} or int, default='exhaust' + The minimum amount of resource that any candidate is allowed to use + for a given iteration. Equivalently, this defines the amount of + resources `r0` that are allocated for each candidate at the first + iteration. + + - 'smallest' is a heuristic that sets `r0` to a small value: + - ``n_splits * 2`` when ``resource='n_samples'`` for a regression + problem + - ``n_classes * n_splits * 2`` when ``resource='n_samples'`` for a + regression problem + - ``1`` when ``resource != 'n_samples'`` + - 'exhaust' will set `r0` such that the **last** iteration uses as + much resources as possible. Namely, the last iteration will use the + highest value smaller than ``max_resources`` that is a multiple of + both ``min_resources`` and ``factor``. In general, using 'exhaust' + leads to a more accurate estimator, but is slightly more time + consuming. + + Note that the amount of resources used at each iteration is always a + multiple of ``min_resources``. + + aggressive_elimination : bool, default=False + This is only relevant in cases where there isn't enough resources to + reduce the remaining candidates to at most `factor` after the last + iteration. If ``True``, then the search process will 'replay' the + first iteration for as long as needed until the number of candidates + is small enough. This is ``False`` by default, which means that the + last iteration may evaluate more than ``factor`` candidates. See + :ref:`aggressive_elimination` for more details. + + cv : int, cross-validation generator or iterable, default=5 + Determines the cross-validation splitting strategy. + Possible inputs for cv are: + + - integer, to specify the number of folds in a `(Stratified)KFold`, + - :term:`CV splitter`, + - An iterable yielding (train, test) splits as arrays of indices. + + For integer/None inputs, if the estimator is a classifier and ``y`` is + either binary or multiclass, :class:`StratifiedKFold` is used. In all + other cases, :class:`KFold` is used. + + Refer :ref:`User Guide <cross_validation>` for the various + cross-validation strategies that can be used here. + + .. note:: + Due to implementation details, the folds produced by `cv` must be + the same across multiple calls to `cv.split()`. For + built-in `scikit-learn` iterators, this can be achieved by + deactivating shuffling (`shuffle=False`), or by setting the + `cv`'s `random_state` parameter to an integer. + + scoring : string, callable, or None, default=None + A single string (see :ref:`scoring_parameter`) or a callable + (see :ref:`scoring`) to evaluate the predictions on the test set. + If None, the estimator's score method is used. + + refit : bool, default=True + If True, refit an estimator using the best found parameters on the + whole dataset. + + The refitted estimator is made available at the ``best_estimator_`` + attribute and permits using ``predict`` directly on this + ``GridSearchCV`` instance. + + error_score : 'raise' or numeric + Value to assign to the score if an error occurs in estimator fitting. + If set to 'raise', the error is raised. If a numeric value is given, + FitFailedWarning is raised. This parameter does not affect the refit + step, which will always raise the error. Default is ``np.nan`` + + return_train_score : bool, default=False + If ``False``, the ``cv_results_`` attribute will not include training + scores. + Computing training scores is used to get insights on how different + parameter settings impact the overfitting/underfitting trade-off. + However computing the scores on the training set can be computationally + expensive and is not strictly required to select the parameters that + yield the best generalization performance. + + random_state : int, RandomState instance or None, default=None + Pseudo random number generator state used for subsampling the dataset + when `resources != 'n_samples'`. Ignored otherwise. + Pass an int for reproducible output across multiple function calls. + See :term:`Glossary <random_state>`. + + n_jobs : int or None, default=None + Number of jobs to run in parallel. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary <n_jobs>` + for more details. + + verbose : int + Controls the verbosity: the higher, the more messages. + + Attributes + ---------- + n_resources_ : list of int + The amount of resources used at each iteration. + + n_candidates_ : list of int + The number of candidate parameters that were evaluated at each + iteration. + + n_remaining_candidates_ : int + The number of candidate parameters that are left after the last + iteration. It corresponds to `ceil(n_candidates[-1] / factor)` + + max_resources_ : int + The maximum number of resources that any candidate is allowed to use + for a given iteration. Note that since the number of resources used + at each iteration must be a multiple of ``min_resources_``, the + actual number of resources used at the last iteration may be smaller + than ``max_resources_``. + + min_resources_ : int + The amount of resources that are allocated for each candidate at the + first iteration. + + n_iterations_ : int + The actual number of iterations that were run. This is equal to + ``n_required_iterations_`` if ``aggressive_elimination`` is ``True``. + Else, this is equal to ``min(n_possible_iterations_, + n_required_iterations_)``. + + n_possible_iterations_ : int + The number of iterations that are possible starting with + ``min_resources_`` resources and without exceeding + ``max_resources_``. + + n_required_iterations_ : int + The number of iterations that are required to end up with less than + ``factor`` candidates at the last iteration, starting with + ``min_resources_`` resources. This will be smaller than + ``n_possible_iterations_`` when there isn't enough resources. + + cv_results_ : dict of numpy (masked) ndarrays + A dict with keys as column headers and values as columns, that can be + imported into a pandas ``DataFrame``. It contains many informations for + analysing the results of a search. + Please refer to the :ref:`User guide<successive_halving_cv_results>` + for details. + + best_estimator_ : estimator or dict + Estimator that was chosen by the search, i.e. estimator + which gave highest score (or smallest loss if specified) + on the left out data. Not available if ``refit=False``. + + best_score_ : float + Mean cross-validated score of the best_estimator. + + best_params_ : dict + Parameter setting that gave the best results on the hold out data. + + best_index_ : int + The index (of the ``cv_results_`` arrays) which corresponds to the best + candidate parameter setting. + + The dict at ``search.cv_results_['params'][search.best_index_]`` gives + the parameter setting for the best model, that gives the highest + mean score (``search.best_score_``). + + scorer_ : function or a dict + Scorer function used on the held out data to choose the best + parameters for the model. + + n_splits_ : int + The number of cross-validation splits (folds/iterations). + + refit_time_ : float + Seconds used for refitting the best model on the whole dataset. + + This is present only if ``refit`` is not False. + + See Also + -------- + :class:`HalvingRandomSearchCV`: + Random search over a set of parameters using successive halving. + + Notes + ----- + The parameters selected are those that maximize the score of the held-out + data, according to the scoring parameter. + + Examples + -------- + + >>> from sklearn.datasets import load_iris + >>> from sklearn.ensemble import RandomForestClassifier + >>> from sklearn.experimental import enable_successive_halving # noqa + >>> from sklearn.model_selection import HalvingGridSearchCV + ... + >>> X, y = load_iris(return_X_y=True) + >>> clf = RandomForestClassifier(random_state=0) + ... + >>> param_grid = {"max_depth": [3, None], + ... "min_samples_split": [5, 10]} + >>> search = HalvingGridSearchCV(clf, param_grid, resource='n_estimators', + ... max_resources=10, + ... random_state=0).fit(X, y) + >>> search.best_params_ # doctest: +SKIP + {'max_depth': None, 'min_samples_split': 10, 'n_estimators': 9} + """ + _required_parameters = ["estimator", "param_grid"] + + def __init__(self, estimator, param_grid, *, + factor=3, resource='n_samples', max_resources='auto', + min_resources='exhaust', aggressive_elimination=False, + cv=5, scoring=None, refit=True, error_score=np.nan, + return_train_score=True, random_state=None, n_jobs=None, + verbose=0): + super().__init__(estimator, scoring=scoring, + n_jobs=n_jobs, refit=refit, verbose=verbose, cv=cv, + random_state=random_state, error_score=error_score, + return_train_score=return_train_score, + max_resources=max_resources, resource=resource, + factor=factor, min_resources=min_resources, + aggressive_elimination=aggressive_elimination) + self.param_grid = param_grid + _check_param_grid(self.param_grid) + + def _generate_candidate_params(self): + return ParameterGrid(self.param_grid) + + +class HalvingRandomSearchCV(BaseSuccessiveHalving): + """Randomized search on hyper parameters. + + The search strategy starts evaluating all the candidates with a small + amount of resources and iteratively selects the best candidates, using more + and more resources. + + The candidates are sampled at random from the parameter space and the + number of sampled candidates is determined by ``n_candidates``. + + Read more in the :ref:`User guide<successive_halving_user_guide>`. + + .. note:: + + This estimator is still **experimental** for now: the predictions + and the API might change without any deprecation cycle. To use it, + you need to explicitly import ``enable_successive_halving``:: + + >>> # explicitly require this experimental feature + >>> from sklearn.experimental import enable_successive_halving # noqa + >>> # now you can import normally from model_selection + >>> from sklearn.model_selection import HalvingRandomSearchCV + + Parameters + ---------- + estimator : estimator object. + This is assumed to implement the scikit-learn estimator interface. + Either estimator needs to provide a ``score`` function, + or ``scoring`` must be passed. + + param_distributions : dict + Dictionary with parameters names (string) as keys and distributions + or lists of parameters to try. Distributions must provide a ``rvs`` + method for sampling (such as those from scipy.stats.distributions). + If a list is given, it is sampled uniformly. + + n_candidates : int, default='exhaust' + The number of candidate parameters to sample, at the first + iteration. Using 'exhaust' will sample enough candidates so that the + last iteration uses as many resources as possible, based on + `min_resources`, `max_resources` and `factor`. In this case, + `min_resources` cannot be 'exhaust'. + + factor : int or float, default=3 + The 'halving' parameter, which determines the proportion of candidates + that are selected for each subsequent iteration. For example, + ``factor=3`` means that only one third of the candidates are selected. + + resource : ``'n_samples'`` or str, default='n_samples' + Defines the resource that increases with each iteration. By default, + the resource is the number of samples. It can also be set to any + parameter of the base estimator that accepts positive integer + values, e.g. 'n_iterations' or 'n_estimators' for a gradient + boosting estimator. In this case ``max_resources`` cannot be 'auto' + and must be set explicitly. + + max_resources : int, default='auto' + The maximum number of resources that any candidate is allowed to use + for a given iteration. By default, this is set ``n_samples`` when + ``resource='n_samples'`` (default), else an error is raised. + + min_resources : {'exhaust', 'smallest'} or int, default='smallest' + The minimum amount of resource that any candidate is allowed to use + for a given iteration. Equivalently, this defines the amount of + resources `r0` that are allocated for each candidate at the first + iteration. + + - 'smallest' is a heuristic that sets `r0` to a small value: + - ``n_splits * 2`` when ``resource='n_samples'`` for a regression + problem + - ``n_classes * n_splits * 2`` when ``resource='n_samples'`` for a + regression problem + - ``1`` when ``resource != 'n_samples'`` + - 'exhaust' will set `r0` such that the **last** iteration uses as + much resources as possible. Namely, the last iteration will use the + highest value smaller than ``max_resources`` that is a multiple of + both ``min_resources`` and ``factor``. In general, using 'exhaust' + leads to a more accurate estimator, but is slightly more time + consuming. 'exhaust' isn't available when `n_candidates='exhaust'`. + + Note that the amount of resources used at each iteration is always a + multiple of ``min_resources``. + + aggressive_elimination : bool, default=False + This is only relevant in cases where there isn't enough resources to + reduce the remaining candidates to at most `factor` after the last + iteration. If ``True``, then the search process will 'replay' the + first iteration for as long as needed until the number of candidates + is small enough. This is ``False`` by default, which means that the + last iteration may evaluate more than ``factor`` candidates. See + :ref:`aggressive_elimination` for more details. + + cv : int, cross-validation generator or an iterable, default=5 + Determines the cross-validation splitting strategy. + Possible inputs for cv are: + + - integer, to specify the number of folds in a `(Stratified)KFold`, + - :term:`CV splitter`, + - An iterable yielding (train, test) splits as arrays of indices. + + For integer/None inputs, if the estimator is a classifier and ``y`` is + either binary or multiclass, :class:`StratifiedKFold` is used. In all + other cases, :class:`KFold` is used. + + Refer :ref:`User Guide <cross_validation>` for the various + cross-validation strategies that can be used here. + + .. note:: + Due to implementation details, the folds produced by `cv` must be + the same across multiple calls to `cv.split()`. For + built-in `scikit-learn` iterators, this can be achieved by + deactivating shuffling (`shuffle=False`), or by setting the + `cv`'s `random_state` parameter to an integer. + + scoring : string, callable, or None, default=None + A single string (see :ref:`scoring_parameter`) or a callable + (see :ref:`scoring`) to evaluate the predictions on the test set. + If None, the estimator's score method is used. + + refit : bool, default=True + If True, refit an estimator using the best found parameters on the + whole dataset. + + The refitted estimator is made available at the ``best_estimator_`` + attribute and permits using ``predict`` directly on this + ``GridSearchCV`` instance. + + error_score : 'raise' or numeric + Value to assign to the score if an error occurs in estimator fitting. + If set to 'raise', the error is raised. If a numeric value is given, + FitFailedWarning is raised. This parameter does not affect the refit + step, which will always raise the error. Default is ``np.nan`` + + return_train_score : bool, default=False + If ``False``, the ``cv_results_`` attribute will not include training + scores. + Computing training scores is used to get insights on how different + parameter settings impact the overfitting/underfitting trade-off. + However computing the scores on the training set can be computationally + expensive and is not strictly required to select the parameters that + yield the best generalization performance. + + random_state : int, RandomState instance or None, default=None + Pseudo random number generator state used for subsampling the dataset + when `resources != 'n_samples'`. Also used for random uniform + sampling from lists of possible values instead of scipy.stats + distributions. + Pass an int for reproducible output across multiple function calls. + See :term:`Glossary <random_state>`. + + n_jobs : int or None, default=None + Number of jobs to run in parallel. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary <n_jobs>` + for more details. + + verbose : int + Controls the verbosity: the higher, the more messages. + + Attributes + ---------- + n_resources_ : list of int + The amount of resources used at each iteration. + + n_candidates_ : list of int + The number of candidate parameters that were evaluated at each + iteration. + + n_remaining_candidates_ : int + The number of candidate parameters that are left after the last + iteration. It corresponds to `ceil(n_candidates[-1] / factor)` + + max_resources_ : int + The maximum number of resources that any candidate is allowed to use + for a given iteration. Note that since the number of resources used at + each iteration must be a multiple of ``min_resources_``, the actual + number of resources used at the last iteration may be smaller than + ``max_resources_``. + + min_resources_ : int + The amount of resources that are allocated for each candidate at the + first iteration. + + n_iterations_ : int + The actual number of iterations that were run. This is equal to + ``n_required_iterations_`` if ``aggressive_elimination`` is ``True``. + Else, this is equal to ``min(n_possible_iterations_, + n_required_iterations_)``. + + n_possible_iterations_ : int + The number of iterations that are possible starting with + ``min_resources_`` resources and without exceeding + ``max_resources_``. + + n_required_iterations_ : int + The number of iterations that are required to end up with less than + ``factor`` candidates at the last iteration, starting with + ``min_resources_`` resources. This will be smaller than + ``n_possible_iterations_`` when there isn't enough resources. + + cv_results_ : dict of numpy (masked) ndarrays + A dict with keys as column headers and values as columns, that can be + imported into a pandas ``DataFrame``. It contains many informations for + analysing the results of a search. + Please refer to the :ref:`User guide<successive_halving_cv_results>` + for details. + + best_estimator_ : estimator or dict + Estimator that was chosen by the search, i.e. estimator + which gave highest score (or smallest loss if specified) + on the left out data. Not available if ``refit=False``. + + best_score_ : float + Mean cross-validated score of the best_estimator. + + best_params_ : dict + Parameter setting that gave the best results on the hold out data. + + best_index_ : int + The index (of the ``cv_results_`` arrays) which corresponds to the best + candidate parameter setting. + + The dict at ``search.cv_results_['params'][search.best_index_]`` gives + the parameter setting for the best model, that gives the highest + mean score (``search.best_score_``). + + scorer_ : function or a dict + Scorer function used on the held out data to choose the best + parameters for the model. + + n_splits_ : int + The number of cross-validation splits (folds/iterations). + + refit_time_ : float + Seconds used for refitting the best model on the whole dataset. + + This is present only if ``refit`` is not False. + + See Also + -------- + :class:`HalvingGridSearchCV`: + Search over a grid of parameters using successive halving. + + Notes + ----- + The parameters selected are those that maximize the score of the held-out + data, according to the scoring parameter. + + Examples + -------- + + >>> from sklearn.datasets import load_iris + >>> from sklearn.ensemble import RandomForestClassifier + >>> from sklearn.experimental import enable_successive_halving # noqa + >>> from sklearn.model_selection import HalvingRandomSearchCV + >>> from scipy.stats import randint + ... + >>> X, y = load_iris(return_X_y=True) + >>> clf = RandomForestClassifier(random_state=0) + >>> np.random.seed(0) + ... + >>> param_distributions = {"max_depth": [3, None], + ... "min_samples_split": randint(2, 11)} + >>> search = HalvingRandomSearchCV(clf, param_distributions, + ... resource='n_estimators', + ... max_resources=10, + ... random_state=0).fit(X, y) + >>> search.best_params_ # doctest: +SKIP + {'max_depth': None, 'min_samples_split': 10, 'n_estimators': 9} + """ + _required_parameters = ["estimator", "param_distributions"] + + def __init__(self, estimator, param_distributions, *, + n_candidates='exhaust', factor=3, resource='n_samples', + max_resources='auto', min_resources='smallest', + aggressive_elimination=False, cv=5, scoring=None, + refit=True, error_score=np.nan, return_train_score=True, + random_state=None, n_jobs=None, verbose=0): + super().__init__(estimator, scoring=scoring, + n_jobs=n_jobs, refit=refit, verbose=verbose, cv=cv, + random_state=random_state, error_score=error_score, + return_train_score=return_train_score, + max_resources=max_resources, resource=resource, + factor=factor, min_resources=min_resources, + aggressive_elimination=aggressive_elimination) + self.param_distributions = param_distributions + self.n_candidates = n_candidates + + def _generate_candidate_params(self): + n_candidates_first_iter = self.n_candidates + if n_candidates_first_iter == 'exhaust': + # This will generate enough candidate so that the last iteration + # uses as much resources as possible + n_candidates_first_iter = ( + self.max_resources_ // self.min_resources_) + return ParameterSampler(self.param_distributions, + n_candidates_first_iter, + random_state=self.random_state) diff --git a/sklearn/model_selection/_split.py b/sklearn/model_selection/_split.py index 9922290d544d5..b4a9567f35291 100644 --- a/sklearn/model_selection/_split.py +++ b/sklearn/model_selection/_split.py @@ -2235,3 +2235,14 @@ def _build_repr(self): params[key] = value return '%s(%s)' % (class_name, _pprint(params, offset=len(class_name))) + + +def _yields_constant_splits(cv): + # Return True if calling cv.split() always returns the same splits + # We assume that if a cv doesn't have a shuffle parameter, it shuffles by + # default (e.g. ShuffleSplit). If it actually doesn't shuffle (e.g. + # LeaveOneOut), then it won't have a random_state parameter anyway, in + # which case it will default to 0, leading to output=True + shuffle = getattr(cv, 'shuffle', True) + random_state = getattr(cv, 'random_state', 0) + return isinstance(random_state, numbers.Integral) or not shuffle
diff --git a/doc/conftest.py b/doc/conftest.py index eacd469f2e52f..96d42fd96066d 100644 --- a/doc/conftest.py +++ b/doc/conftest.py @@ -57,6 +57,13 @@ def setup_impute(): raise SkipTest("Skipping impute.rst, pandas not installed") +def setup_grid_search(): + try: + import pandas # noqa + except ImportError: + raise SkipTest("Skipping grid_search.rst, pandas not installed") + + def setup_unsupervised_learning(): try: import skimage # noqa @@ -86,5 +93,7 @@ def pytest_runtest_setup(item): raise SkipTest('FeatureHasher is not compatible with PyPy') elif fname.endswith('modules/impute.rst'): setup_impute() + elif fname.endswith('modules/grid_search.rst'): + setup_grid_search() elif fname.endswith('statistical_inference/unsupervised_learning.rst'): setup_unsupervised_learning() diff --git a/sklearn/experimental/tests/test_enable_successive_halving.py b/sklearn/experimental/tests/test_enable_successive_halving.py new file mode 100644 index 0000000000000..bfd05bc302c79 --- /dev/null +++ b/sklearn/experimental/tests/test_enable_successive_halving.py @@ -0,0 +1,43 @@ +"""Tests for making sure experimental imports work as expected.""" + +import textwrap + +from sklearn.utils._testing import assert_run_python_script + + +def test_imports_strategies(): + # Make sure different import strategies work or fail as expected. + + # Since Python caches the imported modules, we need to run a child process + # for every test case. Else, the tests would not be independent + # (manually removing the imports from the cache (sys.modules) is not + # recommended and can lead to many complications). + + good_import = """ + from sklearn.experimental import enable_successive_halving + from sklearn.model_selection import HalvingGridSearchCV + from sklearn.model_selection import HalvingRandomSearchCV + """ + assert_run_python_script(textwrap.dedent(good_import)) + + good_import_with_model_selection_first = """ + import sklearn.model_selection + from sklearn.experimental import enable_successive_halving + from sklearn.model_selection import HalvingGridSearchCV + from sklearn.model_selection import HalvingRandomSearchCV + """ + assert_run_python_script( + textwrap.dedent(good_import_with_model_selection_first) + ) + + bad_imports = """ + import pytest + + with pytest.raises(ImportError): + from sklearn.model_selection import HalvingGridSearchCV + + import sklearn.experimental + with pytest.raises(ImportError): + from sklearn.model_selection import HalvingGridSearchCV + """ + assert_run_python_script(textwrap.dedent(bad_imports)) diff --git a/sklearn/model_selection/tests/test_split.py b/sklearn/model_selection/tests/test_split.py index 4250eb8af8748..5d91a505238ef 100644 --- a/sklearn/model_selection/tests/test_split.py +++ b/sklearn/model_selection/tests/test_split.py @@ -43,6 +43,7 @@ from sklearn.model_selection._split import _validate_shuffle_split from sklearn.model_selection._split import _build_repr +from sklearn.model_selection._split import _yields_constant_splits from sklearn.datasets import load_digits from sklearn.datasets import make_classification @@ -1619,3 +1620,41 @@ def test_random_state_shuffle_false(Klass): with pytest.raises(ValueError, match='has no effect since shuffle is False'): Klass(3, shuffle=False, random_state=0) + + [email protected]('cv, expected', [ + (KFold(), True), + (KFold(shuffle=True, random_state=123), True), + (StratifiedKFold(), True), + (StratifiedKFold(shuffle=True, random_state=123), True), + (RepeatedKFold(random_state=123), True), + (RepeatedStratifiedKFold(random_state=123), True), + (ShuffleSplit(random_state=123), True), + (GroupShuffleSplit(random_state=123), True), + (StratifiedShuffleSplit(random_state=123), True), + (GroupKFold(), True), + (TimeSeriesSplit(), True), + (LeaveOneOut(), True), + (LeaveOneGroupOut(), True), + (LeavePGroupsOut(n_groups=2), True), + (LeavePOut(p=2), True), + + (KFold(shuffle=True, random_state=None), False), + (KFold(shuffle=True, random_state=None), False), + (StratifiedKFold(shuffle=True, random_state=np.random.RandomState(0)), + False), + (StratifiedKFold(shuffle=True, random_state=np.random.RandomState(0)), + False), + (RepeatedKFold(random_state=None), False), + (RepeatedKFold(random_state=np.random.RandomState(0)), False), + (RepeatedStratifiedKFold(random_state=None), False), + (RepeatedStratifiedKFold(random_state=np.random.RandomState(0)), False), + (ShuffleSplit(random_state=None), False), + (ShuffleSplit(random_state=np.random.RandomState(0)), False), + (GroupShuffleSplit(random_state=None), False), + (GroupShuffleSplit(random_state=np.random.RandomState(0)), False), + (StratifiedShuffleSplit(random_state=None), False), + (StratifiedShuffleSplit(random_state=np.random.RandomState(0)), False), +]) +def test_yields_constant_splits(cv, expected): + assert _yields_constant_splits(cv) == expected diff --git a/sklearn/model_selection/tests/test_successive_halving.py b/sklearn/model_selection/tests/test_successive_halving.py new file mode 100644 index 0000000000000..eeb941bd25a06 --- /dev/null +++ b/sklearn/model_selection/tests/test_successive_halving.py @@ -0,0 +1,564 @@ +from math import ceil + +import pytest +from scipy.stats import norm, randint +import numpy as np + +from sklearn.datasets import make_classification +from sklearn.dummy import DummyClassifier +from sklearn.experimental import enable_successive_halving # noqa +from sklearn.model_selection import HalvingGridSearchCV +from sklearn.model_selection import HalvingRandomSearchCV +from sklearn.model_selection import KFold, ShuffleSplit +from sklearn.model_selection._search_successive_halving import ( + _SubsampleMetaSplitter, _top_k, _refit_callable) + + +class FastClassifier(DummyClassifier): + """Dummy classifier that accepts parameters a, b, ... z. + + These parameter don't affect the predictions and are useful for fast + grid searching.""" + + def __init__(self, strategy='stratified', random_state=None, + constant=None, **kwargs): + super().__init__(strategy=strategy, random_state=random_state, + constant=constant) + + def get_params(self, deep=False): + params = super().get_params(deep=deep) + for char in range(ord('a'), ord('z') + 1): + params[chr(char)] = 'whatever' + return params + + [email protected]('Est', (HalvingGridSearchCV, HalvingRandomSearchCV)) [email protected]( + ('aggressive_elimination,' + 'max_resources,' + 'expected_n_iterations,' + 'expected_n_required_iterations,' + 'expected_n_possible_iterations,' + 'expected_n_remaining_candidates,' + 'expected_n_candidates,' + 'expected_n_resources,'), [ + # notice how it loops at the beginning + # also, the number of candidates evaluated at the last iteration is + # <= factor + (True, 'limited', 4, 4, 3, 1, [60, 20, 7, 3], [20, 20, 60, 180]), + # no aggressive elimination: we end up with less iterations, and + # the number of candidates at the last iter is > factor, which isn't + # ideal + (False, 'limited', 3, 4, 3, 3, [60, 20, 7], [20, 60, 180]), + # # When the amount of resource isn't limited, aggressive_elimination + # # has no effect. Here the default min_resources='exhaust' will take + # # over. + (True, 'unlimited', 4, 4, 4, 1, [60, 20, 7, 3], [37, 111, 333, 999]), + (False, 'unlimited', 4, 4, 4, 1, [60, 20, 7, 3], [37, 111, 333, 999]), + ] +) +def test_aggressive_elimination( + Est, aggressive_elimination, max_resources, expected_n_iterations, + expected_n_required_iterations, expected_n_possible_iterations, + expected_n_remaining_candidates, expected_n_candidates, + expected_n_resources): + # Test the aggressive_elimination parameter. + + n_samples = 1000 + X, y = make_classification(n_samples=n_samples, random_state=0) + param_grid = {'a': ('l1', 'l2'), 'b': list(range(30))} + base_estimator = FastClassifier() + + if max_resources == 'limited': + max_resources = 180 + else: + max_resources = n_samples + + sh = Est(base_estimator, param_grid, + aggressive_elimination=aggressive_elimination, + max_resources=max_resources, factor=3) + sh.set_params(verbose=True) # just for test coverage + + if Est is HalvingRandomSearchCV: + # same number of candidates as with the grid + sh.set_params(n_candidates=2 * 30, min_resources='exhaust') + + sh.fit(X, y) + + assert sh.n_iterations_ == expected_n_iterations + assert sh.n_required_iterations_ == expected_n_required_iterations + assert sh.n_possible_iterations_ == expected_n_possible_iterations + assert sh.n_resources_ == expected_n_resources + assert sh.n_candidates_ == expected_n_candidates + assert sh.n_remaining_candidates_ == expected_n_remaining_candidates + assert ceil(sh.n_candidates_[-1] / sh.factor) == sh.n_remaining_candidates_ + + [email protected]('Est', (HalvingGridSearchCV, HalvingRandomSearchCV)) [email protected]( + ('min_resources,' + 'max_resources,' + 'expected_n_iterations,' + 'expected_n_possible_iterations,' + 'expected_n_resources,'), [ + # with enough resources + ('smallest', 'auto', 2, 4, [20, 60]), + # with enough resources but min_resources set manually + (50, 'auto', 2, 3, [50, 150]), + # without enough resources, only one iteration can be done + ('smallest', 30, 1, 1, [20]), + # with exhaust: use as much resources as possible at the last iter + ('exhaust', 'auto', 2, 2, [333, 999]), + ('exhaust', 1000, 2, 2, [333, 999]), + ('exhaust', 999, 2, 2, [333, 999]), + ('exhaust', 600, 2, 2, [200, 600]), + ('exhaust', 599, 2, 2, [199, 597]), + ('exhaust', 300, 2, 2, [100, 300]), + ('exhaust', 60, 2, 2, [20, 60]), + ('exhaust', 50, 1, 1, [20]), + ('exhaust', 20, 1, 1, [20]), + ] +) +def test_min_max_resources( + Est, min_resources, max_resources, expected_n_iterations, + expected_n_possible_iterations, + expected_n_resources): + # Test the min_resources and max_resources parameters, and how they affect + # the number of resources used at each iteration + n_samples = 1000 + X, y = make_classification(n_samples=n_samples, random_state=0) + param_grid = {'a': [1, 2], 'b': [1, 2, 3]} + base_estimator = FastClassifier() + + sh = Est(base_estimator, param_grid, factor=3, min_resources=min_resources, + max_resources=max_resources) + if Est is HalvingRandomSearchCV: + sh.set_params(n_candidates=6) # same number as with the grid + + sh.fit(X, y) + + expected_n_required_iterations = 2 # given 6 combinations and factor = 3 + assert sh.n_iterations_ == expected_n_iterations + assert sh.n_required_iterations_ == expected_n_required_iterations + assert sh.n_possible_iterations_ == expected_n_possible_iterations + assert sh.n_resources_ == expected_n_resources + if min_resources == 'exhaust': + assert (sh.n_possible_iterations_ == sh.n_iterations_ == + len(sh.n_resources_)) + + [email protected]('Est', (HalvingRandomSearchCV, HalvingGridSearchCV)) [email protected]( + 'max_resources, n_iterations, n_possible_iterations', [ + ('auto', 5, 9), # all resources are used + (1024, 5, 9), + (700, 5, 8), + (512, 5, 8), + (511, 5, 7), + (32, 4, 4), + (31, 3, 3), + (16, 3, 3), + (4, 1, 1), # max_resources == min_resources, only one iteration is + # possible + ]) +def test_n_iterations(Est, max_resources, n_iterations, n_possible_iterations): + # test the number of actual iterations that were run depending on + # max_resources + + n_samples = 1024 + X, y = make_classification(n_samples=n_samples, random_state=1) + param_grid = {'a': [1, 2], 'b': list(range(10))} + base_estimator = FastClassifier() + factor = 2 + + sh = Est(base_estimator, param_grid, cv=2, factor=factor, + max_resources=max_resources, min_resources=4) + if Est is HalvingRandomSearchCV: + sh.set_params(n_candidates=20) # same as for HalvingGridSearchCV + sh.fit(X, y) + assert sh.n_required_iterations_ == 5 + assert sh.n_iterations_ == n_iterations + assert sh.n_possible_iterations_ == n_possible_iterations + + [email protected]('Est', (HalvingRandomSearchCV, HalvingGridSearchCV)) +def test_resource_parameter(Est): + # Test the resource parameter + + n_samples = 1000 + X, y = make_classification(n_samples=n_samples, random_state=0) + param_grid = {'a': [1, 2], 'b': list(range(10))} + base_estimator = FastClassifier() + sh = Est(base_estimator, param_grid, cv=2, resource='c', + max_resources=10, factor=3) + sh.fit(X, y) + assert set(sh.n_resources_) == set([1, 3, 9]) + for r_i, params, param_c in zip(sh.cv_results_['n_resources'], + sh.cv_results_['params'], + sh.cv_results_['param_c']): + assert r_i == params['c'] == param_c + + with pytest.raises( + ValueError, + match='Cannot use resource=1234 which is not supported '): + sh = HalvingGridSearchCV(base_estimator, param_grid, cv=2, + resource='1234', max_resources=10) + sh.fit(X, y) + + with pytest.raises( + ValueError, + match='Cannot use parameter c as the resource since it is part ' + 'of the searched parameters.'): + param_grid = {'a': [1, 2], 'b': [1, 2], 'c': [1, 3]} + sh = HalvingGridSearchCV(base_estimator, param_grid, cv=2, + resource='c', max_resources=10) + sh.fit(X, y) + + [email protected]( + 'max_resources, n_candidates, expected_n_candidates', [ + (512, 'exhaust', 128), # generate exactly as much as needed + (32, 'exhaust', 8), + (32, 8, 8), + (32, 7, 7), # ask for less than what we could + (32, 9, 9), # ask for more than 'reasonable' + ]) +def test_random_search(max_resources, n_candidates, expected_n_candidates): + # Test random search and make sure the number of generated candidates is + # as expected + + n_samples = 1024 + X, y = make_classification(n_samples=n_samples, random_state=0) + param_grid = {'a': norm, 'b': norm} + base_estimator = FastClassifier() + sh = HalvingRandomSearchCV(base_estimator, param_grid, + n_candidates=n_candidates, cv=2, + max_resources=max_resources, factor=2, + min_resources=4) + sh.fit(X, y) + assert sh.n_candidates_[0] == expected_n_candidates + if n_candidates == 'exhaust': + # Make sure 'exhaust' makes the last iteration use as much resources as + # we can + assert sh.n_resources_[-1] == max_resources + + [email protected]('param_distributions, expected_n_candidates', [ + ({'a': [1, 2]}, 2), # all lists, sample less than n_candidates + ({'a': randint(1, 3)}, 10), # not all list, respect n_candidates +]) +def test_random_search_discrete_distributions(param_distributions, + expected_n_candidates): + # Make sure random search samples the appropriate number of candidates when + # we ask for more than what's possible. How many parameters are sampled + # depends whether the distributions are 'all lists' or not (see + # ParameterSampler for details). This is somewhat redundant with the checks + # in ParameterSampler but interaction bugs were discovered during + # developement of SH + + n_samples = 1024 + X, y = make_classification(n_samples=n_samples, random_state=0) + base_estimator = FastClassifier() + sh = HalvingRandomSearchCV(base_estimator, param_distributions, + n_candidates=10) + sh.fit(X, y) + assert sh.n_candidates_[0] == expected_n_candidates + + [email protected]('Est', (HalvingGridSearchCV, HalvingRandomSearchCV)) [email protected]('params, expected_error_message', [ + ({'scoring': {'accuracy', 'accuracy'}}, + 'Multimetric scoring is not supported'), + ({'resource': 'not_a_parameter'}, + 'Cannot use resource=not_a_parameter which is not supported'), + ({'resource': 'a', 'max_resources': 100}, + 'Cannot use parameter a as the resource since it is part of'), + ({'max_resources': 'not_auto'}, + 'max_resources must be either'), + ({'max_resources': 100.5}, + 'max_resources must be either'), + ({'max_resources': -10}, + 'max_resources must be either'), + ({'min_resources': 'bad str'}, + 'min_resources must be either'), + ({'min_resources': 0.5}, + 'min_resources must be either'), + ({'min_resources': -10}, + 'min_resources must be either'), + ({'max_resources': 'auto', 'resource': 'b'}, + "max_resources can only be 'auto' if resource='n_samples'"), + ({'min_resources': 15, 'max_resources': 14}, + "min_resources_=15 is greater than max_resources_=14"), + ({'cv': KFold(shuffle=True)}, "must yield consistent folds"), + ({'cv': ShuffleSplit()}, "must yield consistent folds"), +]) +def test_input_errors(Est, params, expected_error_message): + base_estimator = FastClassifier() + param_grid = {'a': [1]} + X, y = make_classification(100) + + sh = Est(base_estimator, param_grid, **params) + + with pytest.raises(ValueError, match=expected_error_message): + sh.fit(X, y) + + [email protected]('params, expected_error_message', [ + ({'n_candidates': 'exhaust', 'min_resources': 'exhaust'}, + "cannot be both set to 'exhaust'"), + ({'n_candidates': 'bad'}, "either 'exhaust' or a positive integer"), + ({'n_candidates': 0}, "either 'exhaust' or a positive integer"), +]) +def test_input_errors_randomized(params, expected_error_message): + # tests specific to HalvingRandomSearchCV + + base_estimator = FastClassifier() + param_grid = {'a': [1]} + X, y = make_classification(100) + + sh = HalvingRandomSearchCV(base_estimator, param_grid, **params) + + with pytest.raises(ValueError, match=expected_error_message): + sh.fit(X, y) + + [email protected]( + 'fraction, subsample_test, expected_train_size, expected_test_size', [ + (.5, True, 40, 10), + (.5, False, 40, 20), + (.2, True, 16, 4), + (.2, False, 16, 20)]) +def test_subsample_splitter_shapes(fraction, subsample_test, + expected_train_size, expected_test_size): + # Make sure splits returned by SubsampleMetaSplitter are of appropriate + # size + + n_samples = 100 + X, y = make_classification(n_samples) + cv = _SubsampleMetaSplitter(base_cv=KFold(5), fraction=fraction, + subsample_test=subsample_test, + random_state=None) + + for train, test in cv.split(X, y): + assert train.shape[0] == expected_train_size + assert test.shape[0] == expected_test_size + if subsample_test: + assert train.shape[0] + test.shape[0] == int(n_samples * fraction) + else: + assert test.shape[0] == n_samples // cv.base_cv.get_n_splits() + + [email protected]('subsample_test', (True, False)) +def test_subsample_splitter_determinism(subsample_test): + # Make sure _SubsampleMetaSplitter is consistent across calls to split(): + # - we're OK having training sets differ (they're always sampled with a + # different fraction anyway) + # - when we don't subsample the test set, we want it to be always the same. + # This check is the most important. This is ensured by the determinism + # of the base_cv. + + # Note: we could force both train and test splits to be always the same if + # we drew an int seed in _SubsampleMetaSplitter.__init__ + + n_samples = 100 + X, y = make_classification(n_samples) + cv = _SubsampleMetaSplitter(base_cv=KFold(5), fraction=.5, + subsample_test=subsample_test, + random_state=None) + + folds_a = list(cv.split(X, y, groups=None)) + folds_b = list(cv.split(X, y, groups=None)) + + for (train_a, test_a), (train_b, test_b) in zip(folds_a, folds_b): + assert not np.all(train_a == train_b) + + if subsample_test: + assert not np.all(test_a == test_b) + else: + assert np.all(test_a == test_b) + assert np.all(X[test_a] == X[test_b]) + + [email protected]('k, itr, expected', [ + (1, 0, ['c']), + (2, 0, ['a', 'c']), + (4, 0, ['d', 'b', 'a', 'c']), + (10, 0, ['d', 'b', 'a', 'c']), + + (1, 1, ['e']), + (2, 1, ['f', 'e']), + (10, 1, ['f', 'e']), + + (1, 2, ['i']), + (10, 2, ['g', 'h', 'i']), +]) +def test_top_k(k, itr, expected): + + results = { # this isn't a 'real world' result dict + 'iter': [0, 0, 0, 0, 1, 1, 2, 2, 2], + 'mean_test_score': [4, 3, 5, 1, 11, 10, 5, 6, 9], + 'params': ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'], + } + got = _top_k(results, k=k, itr=itr) + assert np.all(got == expected) + + +def test_refit_callable(): + + results = { # this isn't a 'real world' result dict + 'iter': np.array([0, 0, 0, 0, 1, 1, 2, 2, 2]), + 'mean_test_score': np.array([4, 3, 5, 1, 11, 10, 5, 6, 9]), + 'params': np.array(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']), + } + assert _refit_callable(results) == 8 # index of 'i' + + [email protected]('Est', (HalvingRandomSearchCV, HalvingGridSearchCV)) +def test_cv_results(Est): + # test that the cv_results_ matches correctly the logic of the + # tournament: in particular that the candidates continued in each + # successive iteration are those that were best in the previous iteration + pd = pytest.importorskip('pandas') + + rng = np.random.RandomState(0) + + n_samples = 1000 + X, y = make_classification(n_samples=n_samples, random_state=0) + param_grid = {'a': ('l1', 'l2'), 'b': list(range(30))} + base_estimator = FastClassifier() + + # generate random scores: we want to avoid ties, which would otherwise + # mess with the ordering and make testing harder + def scorer(est, X, y): + return rng.rand() + + sh = Est(base_estimator, param_grid, factor=2, scoring=scorer) + if Est is HalvingRandomSearchCV: + # same number of candidates as with the grid + sh.set_params(n_candidates=2 * 30, min_resources='exhaust') + + sh.fit(X, y) + cv_results_df = pd.DataFrame(sh.cv_results_) + + # just make sure we don't have ties + assert len(cv_results_df['mean_test_score'].unique()) == len(cv_results_df) + + cv_results_df['params_str'] = cv_results_df['params'].apply(str) + table = cv_results_df.pivot(index='params_str', columns='iter', + values='mean_test_score') + + # table looks like something like this: + # iter 0 1 2 3 4 5 + # params_str + # {'a': 'l2', 'b': 23} 0.75 NaN NaN NaN NaN NaN + # {'a': 'l1', 'b': 30} 0.90 0.875 NaN NaN NaN NaN + # {'a': 'l1', 'b': 0} 0.75 NaN NaN NaN NaN NaN + # {'a': 'l2', 'b': 3} 0.85 0.925 0.9125 0.90625 NaN NaN + # {'a': 'l1', 'b': 5} 0.80 NaN NaN NaN NaN NaN + # ... + + # where a NaN indicates that the candidate wasn't evaluated at a given + # iteration, because it wasn't part of the top-K at some previous + # iteration. We here make sure that candidates that aren't in the top-k at + # any given iteration are indeed not evaluated at the subsequent + # iterations. + nan_mask = pd.isna(table) + n_iter = sh.n_iterations_ + for it in range(n_iter - 1): + already_discarded_mask = nan_mask[it] + + # make sure that if a candidate is already discarded, we don't evaluate + # it later + assert (already_discarded_mask & nan_mask[it + 1] == + already_discarded_mask).all() + + # make sure that the number of discarded candidate is correct + discarded_now_mask = ~already_discarded_mask & nan_mask[it + 1] + kept_mask = ~already_discarded_mask & ~discarded_now_mask + assert kept_mask.sum() == sh.n_candidates_[it + 1] + + # make sure that all discarded candidates have a lower score than the + # kept candidates + discarded_max_score = table[it].where(discarded_now_mask).max() + kept_min_score = table[it].where(kept_mask).min() + assert discarded_max_score < kept_min_score + + # We now make sure that the best candidate is chosen only from the last + # iteration. + # We also make sure this is true even if there were higher scores in + # earlier rounds (this isn't generally the case, but worth ensuring it's + # possible). + + last_iter = cv_results_df['iter'].max() + idx_best_last_iter = ( + cv_results_df[cv_results_df['iter'] == last_iter] + ['mean_test_score'].idxmax() + ) + idx_best_all_iters = cv_results_df['mean_test_score'].idxmax() + + assert sh.best_params_ == cv_results_df.iloc[idx_best_last_iter]['params'] + assert (cv_results_df.iloc[idx_best_last_iter]['mean_test_score'] < + cv_results_df.iloc[idx_best_all_iters]['mean_test_score']) + assert (cv_results_df.iloc[idx_best_last_iter]['params'] != + cv_results_df.iloc[idx_best_all_iters]['params']) + + [email protected]('Est', (HalvingGridSearchCV, HalvingRandomSearchCV)) +def test_base_estimator_inputs(Est): + # make sure that the base estimators are passed the correct parameters and + # number of samples at each iteration. + pd = pytest.importorskip('pandas') + + passed_n_samples_fit = [] + passed_n_samples_predict = [] + passed_params = [] + + class FastClassifierBookKeeping(FastClassifier): + + def fit(self, X, y): + passed_n_samples_fit.append(X.shape[0]) + return super().fit(X, y) + + def predict(self, X): + passed_n_samples_predict.append(X.shape[0]) + return super().predict(X) + + def set_params(self, **params): + passed_params.append(params) + return super().set_params(**params) + + n_samples = 1024 + n_splits = 2 + X, y = make_classification(n_samples=n_samples, random_state=0) + param_grid = {'a': ('l1', 'l2'), 'b': list(range(30))} + base_estimator = FastClassifierBookKeeping() + + sh = Est(base_estimator, param_grid, factor=2, cv=n_splits, + return_train_score=False, refit=False) + if Est is HalvingRandomSearchCV: + # same number of candidates as with the grid + sh.set_params(n_candidates=2 * 30, min_resources='exhaust') + + sh.fit(X, y) + + assert len(passed_n_samples_fit) == len(passed_n_samples_predict) + passed_n_samples = [x + y for (x, y) in zip(passed_n_samples_fit, + passed_n_samples_predict)] + + # Lists are of length n_splits * n_iter * n_candidates_at_i. + # Each chunk of size n_splits corresponds to the n_splits folds for the + # same candidate at the same iteration, so they contain equal values. We + # subsample such that the lists are of length n_iter * n_candidates_at_it + passed_n_samples = passed_n_samples[::n_splits] + passed_params = passed_params[::n_splits] + + cv_results_df = pd.DataFrame(sh.cv_results_) + + assert len(passed_params) == len(passed_n_samples) == len(cv_results_df) + + uniques, counts = np.unique(passed_n_samples, return_counts=True) + assert (sh.n_resources_ == uniques).all() + assert (sh.n_candidates_ == counts).all() + + assert (cv_results_df['params'] == passed_params).all() + assert (cv_results_df['n_resources'] == passed_n_samples).all() diff --git a/sklearn/tests/test_docstring_parameters.py b/sklearn/tests/test_docstring_parameters.py index 966cce49eaf42..c723d61693007 100644 --- a/sklearn/tests/test_docstring_parameters.py +++ b/sklearn/tests/test_docstring_parameters.py @@ -189,7 +189,8 @@ def test_fit_docstring_attributes(name, Estimator): 'SparseCoder', 'SparseRandomProjection', 'SpectralBiclustering', 'StackingClassifier', 'StackingRegressor', 'TfidfVectorizer', 'VotingClassifier', - 'VotingRegressor', 'SequentialFeatureSelector'} + 'VotingRegressor', 'SequentialFeatureSelector', + 'HalvingGridSearchCV', 'HalvingRandomSearchCV'} if Estimator.__name__ in IGNORED or Estimator.__name__.startswith('_'): pytest.skip("Estimator cannot be fit easily to test fit attributes")
[ { "path": "doc/conf.py", "old_path": "a/doc/conf.py", "new_path": "b/doc/conf.py", "metadata": "diff --git a/doc/conf.py b/doc/conf.py\nindex ccf5dcd068131..b09c5a15b133d 100644\n--- a/doc/conf.py\n+++ b/doc/conf.py\n@@ -356,6 +356,7 @@ def __call__(self, directory):\n # discovered properly by sphinx\n from sklearn.experimental import enable_hist_gradient_boosting # noqa\n from sklearn.experimental import enable_iterative_imputer # noqa\n+from sklearn.experimental import enable_successive_halving # noqa\n \n \n def make_carousel_thumbs(app, exception):\n" }, { "path": "doc/conftest.py", "old_path": "a/doc/conftest.py", "new_path": "b/doc/conftest.py", "metadata": "diff --git a/doc/conftest.py b/doc/conftest.py\nindex eacd469f2e52f..96d42fd96066d 100644\n--- a/doc/conftest.py\n+++ b/doc/conftest.py\n@@ -57,6 +57,13 @@ def setup_impute():\n raise SkipTest(\"Skipping impute.rst, pandas not installed\")\n \n \n+def setup_grid_search():\n+ try:\n+ import pandas # noqa\n+ except ImportError:\n+ raise SkipTest(\"Skipping grid_search.rst, pandas not installed\")\n+\n+\n def setup_unsupervised_learning():\n try:\n import skimage # noqa\n@@ -86,5 +93,7 @@ def pytest_runtest_setup(item):\n raise SkipTest('FeatureHasher is not compatible with PyPy')\n elif fname.endswith('modules/impute.rst'):\n setup_impute()\n+ elif fname.endswith('modules/grid_search.rst'):\n+ setup_grid_search()\n elif fname.endswith('statistical_inference/unsupervised_learning.rst'):\n setup_unsupervised_learning()\n" }, { "path": "doc/modules/classes.rst", "old_path": "a/doc/modules/classes.rst", "new_path": "b/doc/modules/classes.rst", "metadata": "diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst\nindex a0ee97aed260a..07fbaf384efd9 100644\n--- a/doc/modules/classes.rst\n+++ b/doc/modules/classes.rst\n@@ -1194,9 +1194,11 @@ Hyper-parameter optimizers\n :template: class.rst\n \n model_selection.GridSearchCV\n+ model_selection.HalvingGridSearchCV\n model_selection.ParameterGrid\n model_selection.ParameterSampler\n model_selection.RandomizedSearchCV\n+ model_selection.HalvingRandomSearchCV\n \n \n Model validation\n" }, { "path": "doc/modules/grid_search.rst", "old_path": "a/doc/modules/grid_search.rst", "new_path": "b/doc/modules/grid_search.rst", "metadata": "diff --git a/doc/modules/grid_search.rst b/doc/modules/grid_search.rst\nindex 9d6c1c7e58170..c88a6eb986b5a 100644\n--- a/doc/modules/grid_search.rst\n+++ b/doc/modules/grid_search.rst\n@@ -30,14 +30,18 @@ A search consists of:\n - a cross-validation scheme; and\n - a :ref:`score function <gridsearch_scoring>`.\n \n-Some models allow for specialized, efficient parameter search strategies,\n-:ref:`outlined below <alternative_cv>`.\n-Two generic approaches to sampling search candidates are provided in\n+Two generic approaches to parameter search are provided in\n scikit-learn: for given values, :class:`GridSearchCV` exhaustively considers\n all parameter combinations, while :class:`RandomizedSearchCV` can sample a\n given number of candidates from a parameter space with a specified\n-distribution. After describing these tools we detail\n-:ref:`best practice <grid_search_tips>` applicable to both approaches.\n+distribution. Both these tools have successive halving counterparts\n+:class:`HalvingGridSearchCV` and :class:`HalvingRandomSearchCV`, which can be\n+much faster at finding a good parameter combination.\n+\n+After describing these tools we detail :ref:`best practices\n+<grid_search_tips>` applicable to these approaches. Some models allow for\n+specialized, efficient parameter search strategies, outlined in\n+:ref:`alternative_cv`.\n \n Note that it is common that a small subset of those parameters can have a large\n impact on the predictive or computation performance of the model while others\n@@ -167,6 +171,373 @@ variable that is log-uniformly distributed between ``1e0`` and ``1e3``::\n Random search for hyper-parameter optimization,\n The Journal of Machine Learning Research (2012)\n \n+.. _successive_halving_user_guide:\n+\n+Searching for optimal parameters with successive halving\n+========================================================\n+\n+Scikit-learn also provides the :class:`HalvingGridSearchCV` and\n+:class:`HalvingRandomSearchCV` estimators that can be used to\n+search a parameter space using successive halving [1]_ [2]_. Successive\n+halving (SH) is like a tournament among candidate parameter combinations.\n+SH is an iterative selection process where all candidates (the\n+parameter combinations) are evaluated with a small amount of resources at\n+the first iteration. Only some of these candidates are selected for the next\n+iteration, which will be allocated more resources. For parameter tuning, the\n+resource is typically the number of training samples, but it can also be an\n+arbitrary numeric parameter such as `n_estimators` in a random forest.\n+\n+As illustrated in the figure below, only a subset of candidates\n+'survive' until the last iteration. These are the candidates that have\n+consistently ranked among the top-scoring candidates across all iterations.\n+Each iteration is allocated an increasing amount of resources per candidate,\n+here the number of samples.\n+\n+.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_successive_halving_iterations_001.png\n+ :target: ../auto_examples/model_selection/plot_successive_halving_iterations.html\n+ :align: center\n+\n+We here briefly describe the main parameters, but each parameter and their\n+interactions are described in more details in the sections below. The\n+``factor`` (> 1) parameter controls the rate at which the resources grow, and\n+the rate at which the number of candidates decreases. In each iteration, the\n+number of resources per candidate is multiplied by ``factor`` and the number\n+of candidates is divided by the same factor. Along with ``resource`` and\n+``min_resources``, ``factor`` is the most important parameter to control the\n+search in our implementation, though a value of 3 usually works well.\n+``factor`` effectively controls the number of iterations in\n+:class:`HalvingGridSearchCV` and the number of candidates (by default) and\n+iterations in :class:`HalvingRandomSearchCV`. ``aggressive_elimination=True``\n+can also be used if the number of available resources is small. More control\n+is available through tuning the ``min_resources`` parameter.\n+\n+These estimators are still **experimental**: their predictions\n+and their API might change without any deprecation cycle. To use them, you\n+need to explicitly import ``enable_successive_halving``::\n+\n+ >>> # explicitly require this experimental feature\n+ >>> from sklearn.experimental import enable_successive_halving # noqa\n+ >>> # now you can import normally from model_selection\n+ >>> from sklearn.model_selection import HalvingGridSearchCV\n+ >>> from sklearn.model_selection import HalvingRandomSearchCV\n+\n+.. topic:: Examples:\n+\n+ * :ref:`sphx_glr_auto_examples_model_selection_plot_successive_halving_heatmap.py`\n+ * :ref:`sphx_glr_auto_examples_model_selection_plot_successive_halving_iterations.py`\n+\n+Choosing ``min_resources`` and the number of candidates\n+-------------------------------------------------------\n+\n+Beside ``factor``, the two main parameters that influence the behaviour of a\n+successive halving search are the ``min_resources`` parameter, and the\n+number of candidates (or parameter combinations) that are evaluated.\n+``min_resources`` is the amount of resources allocated at the first\n+iteration for each candidate. The number of candidates is specified directly\n+in :class:`HalvingRandomSearchCV`, and is determined from the ``param_grid``\n+parameter of :class:`HalvingGridSearchCV`.\n+\n+Consider a case where the resource is the number of samples, and where we\n+have 1000 samples. In theory, with ``min_resources=10`` and ``factor=2``, we\n+are able to run **at most** 7 iterations with the following number of\n+samples: ``[10, 20, 40, 80, 160, 320, 640]``.\n+\n+But depending on the number of candidates, we might run less than 7\n+iterations: if we start with a **small** number of candidates, the last\n+iteration might use less than 640 samples, which means not using all the\n+available resources (samples). For example if we start with 5 candidates, we\n+only need 2 iterations: 5 candidates for the first iteration, then\n+`5 // 2 = 2` candidates at the second iteration, after which we know which\n+candidate performs the best (so we don't need a third one). We would only be\n+using at most 20 samples which is a waste since we have 1000 samples at our\n+disposal. On the other hand, if we start with a **high** number of\n+candidates, we might end up with a lot of candidates at the last iteration,\n+which may not always be ideal: it means that many candidates will run with\n+the full resources, basically reducing the procedure to standard search.\n+\n+In the case of :class:`HalvingRandomSearchCV`, the number of candidates is set\n+by default such that the last iteration uses as much of the available\n+resources as possible. For :class:`HalvingGridSearchCV`, the number of\n+candidates is determined by the `param_grid` parameter. Changing the value of\n+``min_resources`` will impact the number of possible iterations, and as a\n+result will also have an effect on the ideal number of candidates.\n+\n+Another consideration when choosing ``min_resources`` is whether or not it\n+is easy to discriminate between good and bad candidates with a small amount\n+of resources. For example, if you need a lot of samples to distinguish\n+between good and bad parameters, a high ``min_resources`` is recommended. On\n+the other hand if the distinction is clear even with a small amount of\n+samples, then a small ``min_resources`` may be preferable since it would\n+speed up the computation.\n+\n+Notice in the example above that the last iteration does not use the maximum\n+amount of resources available: 1000 samples are available, yet only 640 are\n+used, at most. By default, both :class:`HalvingRandomSearchCV` and\n+:class:`HalvingGridSearchCV` try to use as many resources as possible in the\n+last iteration, with the constraint that this amount of resources must be a\n+multiple of both `min_resources` and `factor` (this constraint will be clear\n+in the next section). :class:`HalvingRandomSearchCV` achieves this by\n+sampling the right amount of candidates, while :class:`HalvingGridSearchCV`\n+achieves this by properly setting `min_resources`. Please see\n+:ref:`exhausting_the_resources` for details.\n+\n+.. _amount_of_resource_and_number_of_candidates:\n+\n+Amount of resource and number of candidates at each iteration\n+-------------------------------------------------------------\n+\n+At any iteration `i`, each candidate is allocated a given amount of resources\n+which we denote `n_resources_i`. This quantity is controlled by the\n+parameters ``factor`` and ``min_resources`` as follows (`factor` is strictly\n+greater than 1)::\n+\n+ n_resources_i = factor**i * min_resources,\n+\n+or equivalently::\n+\n+ n_resources_{i+1} = n_resources_i * factor\n+\n+where ``min_resources == n_resources_0`` is the amount of resources used at\n+the first iteration. ``factor`` also defines the proportions of candidates\n+that will be selected for the next iteration::\n+\n+ n_candidates_i = n_candidates // (factor ** i)\n+\n+or equivalently::\n+\n+ n_candidates_0 = n_candidates\n+ n_candidates_{i+1} = n_candidates_i // factor\n+\n+So in the first iteration, we use ``min_resources`` resources\n+``n_candidates`` times. In the second iteration, we use ``min_resources *\n+factor`` resources ``n_candidates // factor`` times. The third again\n+multiplies the resources per candidate and divides the number of candidates.\n+This process stops when the maximum amount of resource per candidate is\n+reached, or when we have identified the best candidate. The best candidate\n+is identified at the iteration that is evaluating `factor` or less candidates\n+(see just below for an explanation).\n+\n+Here is an example with ``min_resources=3`` and ``factor=2``, starting with\n+70 candidates:\n+\n++-----------------------+-----------------------+\n+| ``n_resources_i`` | ``n_candidates_i`` |\n++=======================+=======================+\n+| 3 (=min_resources) | 70 (=n_candidates) |\n++-----------------------+-----------------------+\n+| 3 * 2 = 6 | 70 // 2 = 35 |\n++-----------------------+-----------------------+\n+| 6 * 2 = 12 | 35 // 2 = 17 |\n++-----------------------+-----------------------+\n+| 12 * 2 = 24 | 17 // 2 = 8 |\n++-----------------------+-----------------------+\n+| 24 * 2 = 48 | 8 // 2 = 4 |\n++-----------------------+-----------------------+\n+| 48 * 2 = 96 | 4 // 2 = 2 |\n++-----------------------+-----------------------+\n+\n+We can note that:\n+\n+- the process stops at the first iteration which evaluates `factor=2`\n+ candidates: the best candidate is the best out of these 2 candidates. It\n+ is not necessary to run an additional iteration, since it would only\n+ evaluate one candidate (namely the best one, which we have already\n+ identified). For this reason, in general, we want the last iteration to\n+ run at most ``factor`` candidates. If the last iteration evaluates more\n+ than `factor` candidates, then this last iteration reduces to a regular\n+ search (as in :class:`RandomizedSearchCV` or :class:`GridSearchCV`).\n+- each ``n_resources_i`` is a multiple of both ``factor`` and\n+ ``min_resources`` (which is confirmed by its definition above).\n+\n+The amount of resources that is used at each iteration can be found in the\n+`n_resources_` attribute.\n+\n+Choosing a resource\n+-------------------\n+\n+By default, the resource is defined in terms of number of samples. That is,\n+each iteration will use an increasing amount of samples to train on. You can\n+however manually specify a parameter to use as the resource with the\n+``resource`` parameter. Here is an example where the resource is defined in\n+terms of the number of estimators of a random forest::\n+\n+ >>> from sklearn.datasets import make_classification\n+ >>> from sklearn.ensemble import RandomForestClassifier\n+ >>> from sklearn.experimental import enable_successive_halving # noqa\n+ >>> from sklearn.model_selection import HalvingGridSearchCV\n+ >>> import pandas as pd\n+ >>>\n+ >>> param_grid = {'max_depth': [3, 5, 10],\n+ ... 'min_samples_split': [2, 5, 10]}\n+ >>> base_estimator = RandomForestClassifier(random_state=0)\n+ >>> X, y = make_classification(n_samples=1000, random_state=0)\n+ >>> sh = HalvingGridSearchCV(base_estimator, param_grid, cv=5,\n+ ... factor=2, resource='n_estimators',\n+ ... max_resources=30).fit(X, y)\n+ >>> sh.best_estimator_\n+ RandomForestClassifier(max_depth=5, n_estimators=24, random_state=0)\n+\n+Note that it is not possible to budget on a parameter that is part of the\n+parameter grid.\n+\n+.. _exhausting_the_resources:\n+\n+Exhausting the available resources\n+----------------------------------\n+\n+As mentioned above, the number of resources that is used at each iteration\n+depends on the `min_resources` parameter.\n+If you have a lot of resources available but start with a low number of\n+resources, some of them might be wasted (i.e. not used)::\n+\n+ >>> from sklearn.datasets import make_classification\n+ >>> from sklearn.svm import SVC\n+ >>> from sklearn.experimental import enable_successive_halving # noqa\n+ >>> from sklearn.model_selection import HalvingGridSearchCV\n+ >>> import pandas as pd\n+ >>> param_grid= {'kernel': ('linear', 'rbf'),\n+ ... 'C': [1, 10, 100]}\n+ >>> base_estimator = SVC(gamma='scale')\n+ >>> X, y = make_classification(n_samples=1000)\n+ >>> sh = HalvingGridSearchCV(base_estimator, param_grid, cv=5,\n+ ... factor=2, min_resources=20).fit(X, y)\n+ >>> sh.n_resources_\n+ [20, 40, 80]\n+\n+The search process will only use 80 resources at most, while our maximum\n+amount of available resources is ``n_samples=1000``. Here, we have\n+``min_resources = r_0 = 20``.\n+\n+For :class:`HalvingGridSearchCV`, by default, the `min_resources` parameter\n+is set to 'exhaust'. This means that `min_resources` is automatically set\n+such that the last iteration can use as many resources as possible, within\n+the `max_resources` limit::\n+\n+ >>> sh = HalvingGridSearchCV(base_estimator, param_grid, cv=5,\n+ ... factor=2, min_resources='exhaust').fit(X, y)\n+ >>> sh.n_resources_\n+ [250, 500, 1000]\n+\n+`min_resources` was here automatically set to 250, which results in the last\n+iteration using all the resources. The exact value that is used depends on\n+the number of candidate parameter, on `max_resources` and on `factor`.\n+\n+For :class:`HalvingRandomSearchCV`, exhausting the resources can be done in 2\n+ways:\n+\n+- by setting `min_resources='exhaust'`, just like for\n+ :class:`HalvingGridSearchCV`;\n+- by setting `n_candidates='exhaust'`.\n+\n+Both options are mutally exclusive: using `min_resources='exhaust'` requires\n+knowing the number of candidates, and symmetrically `n_candidates='exhaust'`\n+requires knowing `min_resources`.\n+\n+In general, exhausting the total number of resources leads to a better final\n+candidate parameter, and is slightly more time-intensive.\n+\n+.. _aggressive_elimination:\n+\n+Aggressive elimination of candidates\n+------------------------------------\n+\n+Ideally, we want the last iteration to evaluate ``factor`` candidates (see\n+:ref:`amount_of_resource_and_number_of_candidates`). We then just have to\n+pick the best one. When the number of available resources is small with\n+respect to the number of candidates, the last iteration may have to evaluate\n+more than ``factor`` candidates::\n+\n+ >>> from sklearn.datasets import make_classification\n+ >>> from sklearn.svm import SVC\n+ >>> from sklearn.experimental import enable_successive_halving # noqa\n+ >>> from sklearn.model_selection import HalvingGridSearchCV\n+ >>> import pandas as pd\n+ >>>\n+ >>>\n+ >>> param_grid = {'kernel': ('linear', 'rbf'),\n+ ... 'C': [1, 10, 100]}\n+ >>> base_estimator = SVC(gamma='scale')\n+ >>> X, y = make_classification(n_samples=1000)\n+ >>> sh = HalvingGridSearchCV(base_estimator, param_grid, cv=5,\n+ ... factor=2, max_resources=40,\n+ ... aggressive_elimination=False).fit(X, y)\n+ >>> sh.n_resources_\n+ [20, 40]\n+ >>> sh.n_candidates_\n+ [6, 3]\n+\n+Since we cannot use more than ``max_resources=40`` resources, the process\n+has to stop at the second iteration which evaluates more than ``factor=2``\n+candidates.\n+\n+Using the ``aggressive_elimination`` parameter, you can force the search\n+process to end up with less than ``factor`` candidates at the last\n+iteration. To do this, the process will eliminate as many candidates as\n+necessary using ``min_resources`` resources::\n+\n+ >>> sh = HalvingGridSearchCV(base_estimator, param_grid, cv=5,\n+ ... factor=2,\n+ ... max_resources=40,\n+ ... aggressive_elimination=True,\n+ ... ).fit(X, y)\n+ >>> sh.n_resources_\n+ [20, 20, 40]\n+ >>> sh.n_candidates_\n+ [6, 3, 2]\n+\n+Notice that we end with 2 candidates at the last iteration since we have\n+eliminated enough candidates during the first iterations, using ``n_resources =\n+min_resources = 20``.\n+\n+.. _successive_halving_cv_results:\n+\n+Analysing results with the `cv_results_` attribute\n+--------------------------------------------------\n+\n+The ``cv_results_`` attribute contains useful information for analysing the\n+results of a search. It can be converted to a pandas dataframe with ``df =\n+pd.DataFrame(est.cv_results_)``. The ``cv_results_`` attribute of\n+:class:`HalvingGridSearchCV` and :class:`HalvingRandomSearchCV` is similar\n+to that of :class:`GridSearchCV` and :class:`RandomizedSearchCV`, with\n+additional information related to the successive halving process.\n+\n+Here is an example with some of the columns of a (truncated) dataframe:\n+\n+==== ====== =============== ================= =======================================================================================\n+ .. iter n_resources mean_test_score params\n+==== ====== =============== ================= =======================================================================================\n+ 0 0 125 0.983667 {'criterion': 'entropy', 'max_depth': None, 'max_features': 9, 'min_samples_split': 5}\n+ 1 0 125 0.983667 {'criterion': 'gini', 'max_depth': None, 'max_features': 8, 'min_samples_split': 7}\n+ 2 0 125 0.983667 {'criterion': 'gini', 'max_depth': None, 'max_features': 10, 'min_samples_split': 10}\n+ 3 0 125 0.983667 {'criterion': 'entropy', 'max_depth': None, 'max_features': 6, 'min_samples_split': 6}\n+ ... ... ... ... ...\n+ 15 2 500 0.951958 {'criterion': 'entropy', 'max_depth': None, 'max_features': 9, 'min_samples_split': 10}\n+ 16 2 500 0.947958 {'criterion': 'gini', 'max_depth': None, 'max_features': 10, 'min_samples_split': 10}\n+ 17 2 500 0.951958 {'criterion': 'gini', 'max_depth': None, 'max_features': 10, 'min_samples_split': 4}\n+ 18 3 1000 0.961009 {'criterion': 'entropy', 'max_depth': None, 'max_features': 9, 'min_samples_split': 10}\n+ 19 3 1000 0.955989 {'criterion': 'gini', 'max_depth': None, 'max_features': 10, 'min_samples_split': 4}\n+==== ====== =============== ================= =======================================================================================\n+\n+Each row corresponds to a given parameter combination (a candidate) and a given\n+iteration. The iteration is given by the ``iter`` column. The ``n_resources``\n+column tells you how many resources were used.\n+\n+In the example above, the best parameter combination is ``{'criterion':\n+'entropy', 'max_depth': None, 'max_features': 9, 'min_samples_split': 10}``\n+since it has reached the last iteration (3) with the highest score:\n+0.96.\n+\n+.. topic:: References:\n+\n+ .. [1] K. Jamieson, A. Talwalkar,\n+ `Non-stochastic Best Arm Identification and Hyperparameter\n+ Optimization <http://proceedings.mlr.press/v51/jamieson16.html>`_, in\n+ proc. of Machine Learning Research, 2016.\n+ .. [2] L. Li, K. Jamieson, G. DeSalvo, A. Rostamizadeh, A. Talwalkar,\n+ `Hyperband: A Novel Bandit-Based Approach to Hyperparameter Optimization\n+ <https://arxiv.org/abs/1603.06560>`_, in Machine Learning Research\n+ 18, 2018.\n+\n .. _grid_search_tips:\n \n Tips for parameter search\n@@ -183,18 +554,16 @@ to evaluate a parameter setting. These are the\n :func:`sklearn.metrics.r2_score` for regression. For some applications,\n other scoring functions are better suited (for example in unbalanced\n classification, the accuracy score is often uninformative). An alternative\n-scoring function can be specified via the ``scoring`` parameter to\n-:class:`GridSearchCV`, :class:`RandomizedSearchCV` and many of the\n-specialized cross-validation tools described below.\n-See :ref:`scoring_parameter` for more details.\n+scoring function can be specified via the ``scoring`` parameter of most\n+parameter search tools. See :ref:`scoring_parameter` for more details.\n \n .. _multimetric_grid_search:\n \n Specifying multiple metrics for evaluation\n ------------------------------------------\n \n-``GridSearchCV`` and ``RandomizedSearchCV`` allow specifying multiple metrics\n-for the ``scoring`` parameter.\n+:class:`GridSearchCV` and :class:`RandomizedSearchCV` allow specifying\n+multiple metrics for the ``scoring`` parameter.\n \n Multimetric scoring can either be specified as a list of strings of predefined\n scores names or a dict mapping the scorer name to the scorer function and/or\n@@ -209,6 +578,9 @@ result in an error when using multiple metrics.\n See :ref:`sphx_glr_auto_examples_model_selection_plot_multi_metric_evaluation.py`\n for an example usage.\n \n+:class:`HalvingRandomSearchCV` and :class:`HalvingGridSearchCV` do not support\n+multimetric scoring.\n+\n .. _composite_grid_search:\n \n Composite estimators and parameter spaces\n@@ -253,6 +625,8 @@ levels of nesting::\n ... 'model__base_estimator__max_depth': [2, 4, 6, 8]}\n >>> search = GridSearchCV(pipe, param_grid, cv=5).fit(X, y)\n \n+Please refer to :ref:`pipeline` for performing parameter searches over\n+pipelines.\n \n Model selection: development and evaluation\n -------------------------------------------\n@@ -263,7 +637,7 @@ to use the labeled data to \"train\" the parameters of the grid.\n When evaluating the resulting model it is important to do it on\n held-out samples that were not seen during the grid search process:\n it is recommended to split the data into a **development set** (to\n-be fed to the ``GridSearchCV`` instance) and an **evaluation set**\n+be fed to the :class:`GridSearchCV` instance) and an **evaluation set**\n to compute performance metrics.\n \n This can be done by using the :func:`train_test_split`\n@@ -272,10 +646,10 @@ utility function.\n Parallelism\n -----------\n \n-:class:`GridSearchCV` and :class:`RandomizedSearchCV` evaluate each parameter\n-setting independently. Computations can be run in parallel if your OS\n-supports it, by using the keyword ``n_jobs=-1``. See function signature for\n-more details.\n+The parameter search tools evaluate each parameter combination on each data\n+fold independently. Computations can be run in parallel by using the keyword\n+``n_jobs=-1``. See function signature for more details, and also the Glossary\n+entry for :term:`n_jobs`.\n \n Robustness to failure\n ---------------------\n" }, { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex c57f097ec3218..e757fee299af7 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -412,6 +412,14 @@ Changelog\n :pr:`17478` by :user:`Teon Brooks <teonbrooks>` and\n :user:`Mohamed Maskani <maskani-moh>`.\n \n+- |Feature| Added (experimental) parameter search estimators\n+ :class:`model_selection.HalvingRandomSearchCV` and\n+ :class:`model_selection.HalvingGridSearchCV` which implement Successive\n+ Halving, and can be used as a drop-in replacements for\n+ :class:`model_selection.RandomizedSearchCV` and\n+ :class:`model_selection.GridSearchCV`. :pr:`13900` by `Nicolas Hug`_, `Joel\n+ Nothman`_ and `Andreas Müller`_.\n+\n - |Fix| Fixed the `len` of :class:`model_selection.ParameterSampler` when\n all distributions are lists and `n_iter` is more than the number of unique\n parameter combinations. :pr:`18222` by `Nicolas Hug`_.\n" } ]
0.24
5b29166fe975dd7f21eec137d8e54c0e926d6b8f
[]
[ "sklearn/model_selection/tests/test_split.py::test_random_state_shuffle_false[KFold]", "sklearn/model_selection/tests/test_successive_halving.py::test_min_max_resources[exhaust-auto-2-2-expected_n_resources3-HalvingGridSearchCV]", "sklearn/model_selection/tests/test_successive_halving.py::test_input_errors[params3-max_resources must be either-HalvingRandomSearchCV]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_list_input", "sklearn/model_selection/tests/test_split.py::test_train_test_split_default_test_size[None-7-3]", "sklearn/model_selection/tests/test_split.py::test_shuffle_split_default_test_size[8-8-2-ShuffleSplit]", "sklearn/model_selection/tests/test_successive_halving.py::test_min_max_resources[exhaust-auto-2-2-expected_n_resources3-HalvingRandomSearchCV]", "sklearn/model_selection/tests/test_successive_halving.py::test_aggressive_elimination[True-limited-4-4-3-1-expected_n_candidates0-expected_n_resources0-HalvingRandomSearchCV]", "sklearn/model_selection/tests/test_split.py::test_repeated_cv_repr[RepeatedKFold]", "sklearn/model_selection/tests/test_successive_halving.py::test_min_max_resources[smallest-30-1-1-expected_n_resources2-HalvingGridSearchCV]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv11-True]", "sklearn/model_selection/tests/test_split.py::test_get_n_splits_for_repeated_kfold", "sklearn/model_selection/tests/test_successive_halving.py::test_min_max_resources[exhaust-600-2-2-expected_n_resources6-HalvingRandomSearchCV]", "sklearn/model_selection/tests/test_successive_halving.py::test_min_max_resources[exhaust-999-2-2-expected_n_resources5-HalvingRandomSearchCV]", "sklearn/model_selection/tests/test_successive_halving.py::test_aggressive_elimination[False-limited-3-4-3-3-expected_n_candidates1-expected_n_resources1-HalvingGridSearchCV]", "sklearn/model_selection/tests/test_successive_halving.py::test_min_max_resources[50-auto-2-3-expected_n_resources1-HalvingRandomSearchCV]", "sklearn/model_selection/tests/test_successive_halving.py::test_input_errors[params0-Multimetric scoring is not supported-HalvingRandomSearchCV]", "sklearn/model_selection/tests/test_split.py::test_shuffle_split_empty_trainset[ShuffleSplit]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_label_invariance[6-False]", "sklearn/model_selection/tests/test_split.py::test_build_repr", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[8-True]", "sklearn/model_selection/tests/test_successive_halving.py::test_resource_parameter[HalvingRandomSearchCV]", "sklearn/model_selection/tests/test_successive_halving.py::test_input_errors[params6-min_resources must be either-HalvingRandomSearchCV]", "sklearn/model_selection/tests/test_successive_halving.py::test_input_errors[params12-must yield consistent folds-HalvingRandomSearchCV]", "sklearn/model_selection/tests/test_successive_halving.py::test_subsample_splitter_shapes[0.2-True-16-4]", "sklearn/model_selection/tests/test_split.py::test_stratified_shuffle_split_respects_test_size", "sklearn/model_selection/tests/test_successive_halving.py::test_min_max_resources[exhaust-1000-2-2-expected_n_resources4-HalvingRandomSearchCV]", "sklearn/model_selection/tests/test_successive_halving.py::test_aggressive_elimination[True-limited-4-4-3-1-expected_n_candidates0-expected_n_resources0-HalvingGridSearchCV]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_default_test_size[0.8-8-2]", "sklearn/model_selection/tests/test_successive_halving.py::test_subsample_splitter_shapes[0.5-False-40-20]", "sklearn/model_selection/tests/test_split.py::test_shufflesplit_errors[2.0-None]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv3-True]", "sklearn/model_selection/tests/test_successive_halving.py::test_min_max_resources[smallest-30-1-1-expected_n_resources2-HalvingRandomSearchCV]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv16-False]", "sklearn/model_selection/tests/test_successive_halving.py::test_input_errors[params0-Multimetric scoring is not supported-HalvingGridSearchCV]", "sklearn/model_selection/tests/test_split.py::test_kfold_indices", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv21-False]", "sklearn/model_selection/tests/test_successive_halving.py::test_aggressive_elimination[False-unlimited-4-4-4-1-expected_n_candidates3-expected_n_resources3-HalvingRandomSearchCV]", "sklearn/model_selection/tests/test_successive_halving.py::test_subsample_splitter_determinism[False]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_label_invariance[7-False]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_label_invariance[7-True]", "sklearn/model_selection/tests/test_split.py::test_group_shuffle_split_default_test_size[7-7-3]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[6-False]", "sklearn/model_selection/tests/test_successive_halving.py::test_input_errors[params9-max_resources can only be 'auto' if resource='n_samples'-HalvingRandomSearchCV]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv26-False]", "sklearn/model_selection/tests/test_successive_halving.py::test_input_errors[params4-max_resources must be either-HalvingGridSearchCV]", "sklearn/model_selection/tests/test_successive_halving.py::test_input_errors_randomized[params0-cannot be both set to 'exhaust']", "sklearn/model_selection/tests/test_successive_halving.py::test_base_estimator_inputs[HalvingGridSearchCV]", "sklearn/model_selection/tests/test_successive_halving.py::test_random_search[512-exhaust-128]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes1[0.8-1.2]", "sklearn/model_selection/tests/test_successive_halving.py::test_aggressive_elimination[False-unlimited-4-4-4-1-expected_n_candidates3-expected_n_resources3-HalvingGridSearchCV]", "sklearn/model_selection/tests/test_successive_halving.py::test_top_k[1-2-expected7]", "sklearn/model_selection/tests/test_successive_halving.py::test_min_max_resources[exhaust-999-2-2-expected_n_resources5-HalvingGridSearchCV]", "sklearn/model_selection/tests/test_split.py::test_shuffle_split_default_test_size[None-9-1-ShuffleSplit]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[6-True]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes2[0-0.8]", "sklearn/model_selection/tests/test_split.py::test_kfold_no_shuffle", "sklearn/model_selection/tests/test_split.py::test_leave_one_p_group_out_error_on_fewer_number_of_groups", "sklearn/model_selection/tests/test_split.py::test_kfold_can_detect_dependent_samples_on_digits", "sklearn/model_selection/tests/test_split.py::test_check_cv", "sklearn/model_selection/tests/test_split.py::test_repeated_cv_repr[RepeatedStratifiedKFold]", "sklearn/model_selection/tests/test_successive_halving.py::test_n_iterations[32-4-4-HalvingGridSearchCV]", "sklearn/model_selection/tests/test_successive_halving.py::test_random_search[32-8-8]", "sklearn/model_selection/tests/test_split.py::test_leave_one_out_empty_trainset", "sklearn/model_selection/tests/test_successive_halving.py::test_input_errors[params2-Cannot use parameter a as the resource since it is part of-HalvingGridSearchCV]", "sklearn/model_selection/tests/test_split.py::test_repeated_kfold_determinstic_split", "sklearn/model_selection/tests/test_successive_halving.py::test_input_errors[params1-Cannot use resource=not_a_parameter which is not supported-HalvingGridSearchCV]", "sklearn/model_selection/tests/test_split.py::test_predefinedsplit_with_kfold_split", "sklearn/model_selection/tests/test_successive_halving.py::test_n_iterations[512-5-8-HalvingRandomSearchCV]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes2[0.8-0]", "sklearn/model_selection/tests/test_split.py::test_stratifiedkfold_balance", "sklearn/model_selection/tests/test_split.py::test_group_shuffle_split_default_test_size[0.7-7-3]", "sklearn/model_selection/tests/test_split.py::test_shuffle_stratifiedkfold", "sklearn/model_selection/tests/test_split.py::test_stratified_shuffle_split_iter", "sklearn/model_selection/tests/test_split.py::test_leave_one_p_group_out", "sklearn/model_selection/tests/test_split.py::test_shufflesplit_errors[1.0-None]", "sklearn/model_selection/tests/test_successive_halving.py::test_random_search[32-exhaust-8]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv28-False]", "sklearn/model_selection/tests/test_successive_halving.py::test_input_errors[params11-must yield consistent folds-HalvingGridSearchCV]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_mock_pandas", "sklearn/model_selection/tests/test_successive_halving.py::test_input_errors[params8-min_resources must be either-HalvingGridSearchCV]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_no_shuffle", "sklearn/model_selection/tests/test_split.py::test_stratified_shuffle_split_even", "sklearn/model_selection/tests/test_split.py::test_2d_y", "sklearn/model_selection/tests/test_split.py::test_group_shuffle_split_default_test_size[None-8-2]", "sklearn/model_selection/tests/test_successive_halving.py::test_n_iterations[16-3-3-HalvingGridSearchCV]", "sklearn/model_selection/tests/test_successive_halving.py::test_n_iterations[31-3-3-HalvingRandomSearchCV]", "sklearn/model_selection/tests/test_split.py::test_stratified_shuffle_split_init", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[4-False]", "sklearn/model_selection/tests/test_split.py::test_shuffle_split", "sklearn/model_selection/tests/test_split.py::test_shuffle_split_default_test_size[None-9-1-StratifiedShuffleSplit]", "sklearn/model_selection/tests/test_successive_halving.py::test_min_max_resources[exhaust-300-2-2-expected_n_resources8-HalvingRandomSearchCV]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes1[0.8-0.0]", "sklearn/model_selection/tests/test_successive_halving.py::test_random_search_discrete_distributions[param_distributions1-10]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv8-True]", "sklearn/model_selection/tests/test_successive_halving.py::test_min_max_resources[exhaust-60-2-2-expected_n_resources9-HalvingGridSearchCV]", "sklearn/model_selection/tests/test_successive_halving.py::test_n_iterations[1024-5-9-HalvingRandomSearchCV]", "sklearn/model_selection/tests/test_successive_halving.py::test_cv_results[HalvingRandomSearchCV]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv15-False]", "sklearn/model_selection/tests/test_successive_halving.py::test_top_k[1-0-expected0]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv27-False]", "sklearn/model_selection/tests/test_successive_halving.py::test_input_errors[params5-max_resources must be either-HalvingRandomSearchCV]", "sklearn/model_selection/tests/test_successive_halving.py::test_top_k[4-0-expected2]", "sklearn/model_selection/tests/test_successive_halving.py::test_input_errors[params8-min_resources must be either-HalvingRandomSearchCV]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv0-True]", "sklearn/model_selection/tests/test_split.py::test_random_state_shuffle_false[StratifiedKFold]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_pandas", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv17-False]", "sklearn/model_selection/tests/test_successive_halving.py::test_random_search_discrete_distributions[param_distributions0-2]", "sklearn/model_selection/tests/test_successive_halving.py::test_n_iterations[511-5-7-HalvingGridSearchCV]", "sklearn/model_selection/tests/test_successive_halving.py::test_top_k[10-1-expected6]", "sklearn/model_selection/tests/test_successive_halving.py::test_input_errors[params4-max_resources must be either-HalvingRandomSearchCV]", "sklearn/model_selection/tests/test_split.py::test_stratified_shuffle_split_multilabel_many_labels", "sklearn/model_selection/tests/test_split.py::test_get_n_splits_for_repeated_stratified_kfold", "sklearn/model_selection/tests/test_split.py::test_group_kfold", "sklearn/model_selection/tests/test_successive_halving.py::test_n_iterations[31-3-3-HalvingGridSearchCV]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv5-True]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_label_invariance[4-True]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes1[-0.2-0.8]", "sklearn/tests/test_docstring_parameters.py::test_tabs", "sklearn/model_selection/tests/test_successive_halving.py::test_cv_results[HalvingGridSearchCV]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[7-True]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[10-False]", "sklearn/model_selection/tests/test_split.py::test_kfold_balance", "sklearn/model_selection/tests/test_successive_halving.py::test_input_errors[params1-Cannot use resource=not_a_parameter which is not supported-HalvingRandomSearchCV]", "sklearn/model_selection/tests/test_successive_halving.py::test_base_estimator_inputs[HalvingRandomSearchCV]", "sklearn/model_selection/tests/test_split.py::test_shufflesplit_errors[10-None]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes1[0.0-0.8]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_default_test_size[8-8-2]", "sklearn/model_selection/tests/test_successive_halving.py::test_input_errors[params5-max_resources must be either-HalvingGridSearchCV]", "sklearn/model_selection/tests/test_successive_halving.py::test_input_errors[params6-min_resources must be either-HalvingGridSearchCV]", "sklearn/model_selection/tests/test_split.py::test_train_test_split", "sklearn/model_selection/tests/test_successive_halving.py::test_n_iterations[auto-5-9-HalvingGridSearchCV]", "sklearn/model_selection/tests/test_split.py::test_leave_group_out_changing_groups", "sklearn/model_selection/tests/test_split.py::test_shufflesplit_errors[0.1-0.95]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv12-True]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv13-True]", "sklearn/model_selection/tests/test_successive_halving.py::test_n_iterations[512-5-8-HalvingGridSearchCV]", "sklearn/model_selection/tests/test_successive_halving.py::test_min_max_resources[exhaust-600-2-2-expected_n_resources6-HalvingGridSearchCV]", "sklearn/model_selection/tests/test_successive_halving.py::test_top_k[1-1-expected4]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv25-False]", "sklearn/model_selection/tests/test_successive_halving.py::test_top_k[10-2-expected8]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_label_invariance[6-True]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_label_invariance[4-False]", "sklearn/model_selection/tests/test_split.py::test_shuffle_split_default_test_size[0.8-8-2-ShuffleSplit]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv20-False]", "sklearn/model_selection/tests/test_split.py::test_time_series_test_size", "sklearn/model_selection/tests/test_split.py::test_time_series_cv", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv24-False]", "sklearn/model_selection/tests/test_successive_halving.py::test_aggressive_elimination[True-unlimited-4-4-4-1-expected_n_candidates2-expected_n_resources2-HalvingGridSearchCV]", "sklearn/model_selection/tests/test_successive_halving.py::test_min_max_resources[50-auto-2-3-expected_n_resources1-HalvingGridSearchCV]", "sklearn/model_selection/tests/test_successive_halving.py::test_n_iterations[16-3-3-HalvingRandomSearchCV]", "sklearn/model_selection/tests/test_successive_halving.py::test_top_k[2-0-expected1]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv4-True]", "sklearn/model_selection/tests/test_successive_halving.py::test_top_k[10-0-expected3]", "sklearn/model_selection/tests/test_split.py::test_leave_p_out_empty_trainset", "sklearn/model_selection/tests/test_successive_halving.py::test_min_max_resources[exhaust-50-1-1-expected_n_resources10-HalvingGridSearchCV]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes1[1.0-0.8]", "sklearn/model_selection/tests/test_successive_halving.py::test_input_errors[params2-Cannot use parameter a as the resource since it is part of-HalvingRandomSearchCV]", "sklearn/model_selection/tests/test_successive_halving.py::test_min_max_resources[exhaust-1000-2-2-expected_n_resources4-HalvingGridSearchCV]", "sklearn/model_selection/tests/test_successive_halving.py::test_aggressive_elimination[True-unlimited-4-4-4-1-expected_n_candidates2-expected_n_resources2-HalvingRandomSearchCV]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv1-True]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[10-True]", "sklearn/model_selection/tests/test_successive_halving.py::test_min_max_resources[exhaust-599-2-2-expected_n_resources7-HalvingGridSearchCV]", "sklearn/model_selection/tests/test_successive_halving.py::test_min_max_resources[exhaust-20-1-1-expected_n_resources11-HalvingRandomSearchCV]", "sklearn/model_selection/tests/test_successive_halving.py::test_min_max_resources[exhaust-20-1-1-expected_n_resources11-HalvingGridSearchCV]", "sklearn/model_selection/tests/test_split.py::test_stratifiedshufflesplit_list_input", "sklearn/model_selection/tests/test_split.py::test_shuffle_split_default_test_size[8-8-2-StratifiedShuffleSplit]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv7-True]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes1[0.8--0.2]", "sklearn/model_selection/tests/test_split.py::test_shuffle_kfold_stratifiedkfold_reproducibility", "sklearn/model_selection/tests/test_split.py::test_cv_iterable_wrapper", "sklearn/model_selection/tests/test_split.py::test_shuffle_kfold", "sklearn/model_selection/tests/test_split.py::test_time_series_max_train_size", "sklearn/model_selection/tests/test_successive_halving.py::test_n_iterations[1024-5-9-HalvingGridSearchCV]", "sklearn/model_selection/tests/test_successive_halving.py::test_n_iterations[4-1-1-HalvingGridSearchCV]", "sklearn/model_selection/tests/test_successive_halving.py::test_n_iterations[511-5-7-HalvingRandomSearchCV]", "sklearn/model_selection/tests/test_successive_halving.py::test_subsample_splitter_shapes[0.5-True-40-10]", "sklearn/model_selection/tests/test_successive_halving.py::test_input_errors[params3-max_resources must be either-HalvingGridSearchCV]", "sklearn/model_selection/tests/test_split.py::test_repeated_cv_value_errors", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[8-False]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes1[1.2-0.8]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv9-True]", "sklearn/model_selection/tests/test_split.py::test_shuffle_split_empty_trainset[GroupShuffleSplit]", "sklearn/model_selection/tests/test_successive_halving.py::test_input_errors_randomized[params1-either 'exhaust' or a positive integer]", "sklearn/model_selection/tests/test_successive_halving.py::test_subsample_splitter_shapes[0.2-False-16-20]", "sklearn/model_selection/tests/test_successive_halving.py::test_random_search[32-7-7]", "sklearn/model_selection/tests/test_successive_halving.py::test_random_search[32-9-9]", "sklearn/model_selection/tests/test_successive_halving.py::test_input_errors[params7-min_resources must be either-HalvingRandomSearchCV]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[9-True]", "sklearn/model_selection/tests/test_split.py::test_kfold_valueerrors", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[9-False]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv14-True]", "sklearn/model_selection/tests/test_successive_halving.py::test_refit_callable", "sklearn/model_selection/tests/test_successive_halving.py::test_min_max_resources[exhaust-50-1-1-expected_n_resources10-HalvingRandomSearchCV]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes2[11-0.8]", "sklearn/model_selection/tests/test_successive_halving.py::test_n_iterations[32-4-4-HalvingRandomSearchCV]", "sklearn/model_selection/tests/test_split.py::test_shuffle_split_default_test_size[0.8-8-2-StratifiedShuffleSplit]", "sklearn/model_selection/tests/test_successive_halving.py::test_min_max_resources[smallest-auto-2-4-expected_n_resources0-HalvingGridSearchCV]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[4-True]", "sklearn/model_selection/tests/test_split.py::test_repeated_stratified_kfold_determinstic_split", "sklearn/model_selection/tests/test_successive_halving.py::test_resource_parameter[HalvingGridSearchCV]", "sklearn/model_selection/tests/test_successive_halving.py::test_aggressive_elimination[False-limited-3-4-3-3-expected_n_candidates1-expected_n_resources1-HalvingRandomSearchCV]", "sklearn/model_selection/tests/test_successive_halving.py::test_n_iterations[700-5-8-HalvingRandomSearchCV]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[7-False]", "sklearn/model_selection/tests/test_split.py::test_group_shuffle_split", "sklearn/model_selection/tests/test_split.py::test_train_test_split_errors", "sklearn/model_selection/tests/test_split.py::test_stratified_shuffle_split_overlap_train_test_bug", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv6-True]", "sklearn/model_selection/tests/test_successive_halving.py::test_subsample_splitter_determinism[True]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_allow_nans", "sklearn/model_selection/tests/test_successive_halving.py::test_n_iterations[auto-5-9-HalvingRandomSearchCV]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_sparse", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv19-False]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv18-False]", "sklearn/model_selection/tests/test_successive_halving.py::test_min_max_resources[smallest-auto-2-4-expected_n_resources0-HalvingRandomSearchCV]", "sklearn/model_selection/tests/test_successive_halving.py::test_input_errors[params7-min_resources must be either-HalvingGridSearchCV]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv22-False]", "sklearn/experimental/tests/test_enable_successive_halving.py::test_imports_strategies", "sklearn/model_selection/tests/test_split.py::test_nested_cv", "sklearn/model_selection/tests/test_split.py::test_time_series_gap", "sklearn/model_selection/tests/test_successive_halving.py::test_n_iterations[700-5-8-HalvingGridSearchCV]", "sklearn/model_selection/tests/test_successive_halving.py::test_top_k[2-1-expected5]", "sklearn/model_selection/tests/test_split.py::test_cross_validator_with_default_params", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes2[-10-0.8]", "sklearn/model_selection/tests/test_split.py::test_shufflesplit_reproducible", "sklearn/model_selection/tests/test_split.py::test_shufflesplit_errors[8-3]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[5-False]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_empty_trainset", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[5-True]", "sklearn/model_selection/tests/test_split.py::test_shufflesplit_errors[None-1j]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv2-True]", "sklearn/model_selection/tests/test_successive_halving.py::test_input_errors[params10-min_resources_=15 is greater than max_resources_=14-HalvingGridSearchCV]", "sklearn/model_selection/tests/test_successive_halving.py::test_input_errors[params10-min_resources_=15 is greater than max_resources_=14-HalvingRandomSearchCV]", "sklearn/model_selection/tests/test_successive_halving.py::test_input_errors[params12-must yield consistent folds-HalvingGridSearchCV]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv10-True]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes2[0.8--10]", "sklearn/model_selection/tests/test_split.py::test_stratified_shuffle_split_multilabel", "sklearn/model_selection/tests/test_successive_halving.py::test_n_iterations[4-1-1-HalvingRandomSearchCV]", "sklearn/model_selection/tests/test_split.py::test_shuffle_split_empty_trainset[StratifiedShuffleSplit]", "sklearn/model_selection/tests/test_successive_halving.py::test_input_errors_randomized[params2-either 'exhaust' or a positive integer]", "sklearn/model_selection/tests/test_successive_halving.py::test_min_max_resources[exhaust-60-2-2-expected_n_resources9-HalvingRandomSearchCV]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes1[0.8-1.0]", "sklearn/model_selection/tests/test_successive_halving.py::test_input_errors[params9-max_resources can only be 'auto' if resource='n_samples'-HalvingGridSearchCV]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes2[0.8-11]", "sklearn/model_selection/tests/test_split.py::test_yields_constant_splits[cv23-False]", "sklearn/model_selection/tests/test_successive_halving.py::test_input_errors[params11-must yield consistent folds-HalvingRandomSearchCV]", "sklearn/model_selection/tests/test_successive_halving.py::test_min_max_resources[exhaust-300-2-2-expected_n_resources8-HalvingGridSearchCV]", "sklearn/model_selection/tests/test_successive_halving.py::test_min_max_resources[exhaust-599-2-2-expected_n_resources7-HalvingRandomSearchCV]", "sklearn/model_selection/tests/test_split.py::test_shufflesplit_errors[11-None]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [ { "type": "file", "name": "examples/model_selection/plot_successive_halving_iterations.py" }, { "type": "file", "name": "sklearn/experimental/enable_successive_halving.py" }, { "type": "file", "name": "examples/model_selection/plot_successive_halving_heatmap.py" }, { "type": "file", "name": "sklearn/model_selection/_search_successive_halving.py" } ] }
[ { "path": "doc/conf.py", "old_path": "a/doc/conf.py", "new_path": "b/doc/conf.py", "metadata": "diff --git a/doc/conf.py b/doc/conf.py\nindex ccf5dcd068131..b09c5a15b133d 100644\n--- a/doc/conf.py\n+++ b/doc/conf.py\n@@ -356,6 +356,7 @@ def __call__(self, directory):\n # discovered properly by sphinx\n from sklearn.experimental import enable_hist_gradient_boosting # noqa\n from sklearn.experimental import enable_iterative_imputer # noqa\n+from sklearn.experimental import enable_successive_halving # noqa\n \n \n def make_carousel_thumbs(app, exception):\n" }, { "path": "doc/conftest.py", "old_path": "a/doc/conftest.py", "new_path": "b/doc/conftest.py", "metadata": "diff --git a/doc/conftest.py b/doc/conftest.py\nindex eacd469f2e52f..96d42fd96066d 100644\n--- a/doc/conftest.py\n+++ b/doc/conftest.py\n@@ -57,6 +57,13 @@ def setup_impute():\n raise SkipTest(\"Skipping impute.rst, pandas not installed\")\n \n \n+def setup_grid_search():\n+ try:\n+ import pandas # noqa\n+ except ImportError:\n+ raise SkipTest(\"Skipping grid_search.rst, pandas not installed\")\n+\n+\n def setup_unsupervised_learning():\n try:\n import skimage # noqa\n@@ -86,5 +93,7 @@ def pytest_runtest_setup(item):\n raise SkipTest('FeatureHasher is not compatible with PyPy')\n elif fname.endswith('modules/impute.rst'):\n setup_impute()\n+ elif fname.endswith('modules/grid_search.rst'):\n+ setup_grid_search()\n elif fname.endswith('statistical_inference/unsupervised_learning.rst'):\n setup_unsupervised_learning()\n" }, { "path": "doc/modules/classes.rst", "old_path": "a/doc/modules/classes.rst", "new_path": "b/doc/modules/classes.rst", "metadata": "diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst\nindex a0ee97aed260a..07fbaf384efd9 100644\n--- a/doc/modules/classes.rst\n+++ b/doc/modules/classes.rst\n@@ -1194,9 +1194,11 @@ Hyper-parameter optimizers\n :template: class.rst\n \n model_selection.GridSearchCV\n+ model_selection.HalvingGridSearchCV\n model_selection.ParameterGrid\n model_selection.ParameterSampler\n model_selection.RandomizedSearchCV\n+ model_selection.HalvingRandomSearchCV\n \n \n Model validation\n" }, { "path": "doc/modules/grid_search.rst", "old_path": "a/doc/modules/grid_search.rst", "new_path": "b/doc/modules/grid_search.rst", "metadata": "diff --git a/doc/modules/grid_search.rst b/doc/modules/grid_search.rst\nindex 9d6c1c7e58170..c88a6eb986b5a 100644\n--- a/doc/modules/grid_search.rst\n+++ b/doc/modules/grid_search.rst\n@@ -30,14 +30,18 @@ A search consists of:\n - a cross-validation scheme; and\n - a :ref:`score function <gridsearch_scoring>`.\n \n-Some models allow for specialized, efficient parameter search strategies,\n-:ref:`outlined below <alternative_cv>`.\n-Two generic approaches to sampling search candidates are provided in\n+Two generic approaches to parameter search are provided in\n scikit-learn: for given values, :class:`GridSearchCV` exhaustively considers\n all parameter combinations, while :class:`RandomizedSearchCV` can sample a\n given number of candidates from a parameter space with a specified\n-distribution. After describing these tools we detail\n-:ref:`best practice <grid_search_tips>` applicable to both approaches.\n+distribution. Both these tools have successive halving counterparts\n+:class:`HalvingGridSearchCV` and :class:`HalvingRandomSearchCV`, which can be\n+much faster at finding a good parameter combination.\n+\n+After describing these tools we detail :ref:`best practices\n+<grid_search_tips>` applicable to these approaches. Some models allow for\n+specialized, efficient parameter search strategies, outlined in\n+:ref:`alternative_cv`.\n \n Note that it is common that a small subset of those parameters can have a large\n impact on the predictive or computation performance of the model while others\n@@ -167,6 +171,373 @@ variable that is log-uniformly distributed between ``1e0`` and ``1e3``::\n Random search for hyper-parameter optimization,\n The Journal of Machine Learning Research (2012)\n \n+.. _successive_halving_user_guide:\n+\n+Searching for optimal parameters with successive halving\n+========================================================\n+\n+Scikit-learn also provides the :class:`HalvingGridSearchCV` and\n+:class:`HalvingRandomSearchCV` estimators that can be used to\n+search a parameter space using successive halving [1]_ [2]_. Successive\n+halving (SH) is like a tournament among candidate parameter combinations.\n+SH is an iterative selection process where all candidates (the\n+parameter combinations) are evaluated with a small amount of resources at\n+the first iteration. Only some of these candidates are selected for the next\n+iteration, which will be allocated more resources. For parameter tuning, the\n+resource is typically the number of training samples, but it can also be an\n+arbitrary numeric parameter such as `n_estimators` in a random forest.\n+\n+As illustrated in the figure below, only a subset of candidates\n+'survive' until the last iteration. These are the candidates that have\n+consistently ranked among the top-scoring candidates across all iterations.\n+Each iteration is allocated an increasing amount of resources per candidate,\n+here the number of samples.\n+\n+.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_successive_halving_iterations_001.png\n+ :target: ../auto_examples/model_selection/plot_successive_halving_iterations.html\n+ :align: center\n+\n+We here briefly describe the main parameters, but each parameter and their\n+interactions are described in more details in the sections below. The\n+``factor`` (> 1) parameter controls the rate at which the resources grow, and\n+the rate at which the number of candidates decreases. In each iteration, the\n+number of resources per candidate is multiplied by ``factor`` and the number\n+of candidates is divided by the same factor. Along with ``resource`` and\n+``min_resources``, ``factor`` is the most important parameter to control the\n+search in our implementation, though a value of 3 usually works well.\n+``factor`` effectively controls the number of iterations in\n+:class:`HalvingGridSearchCV` and the number of candidates (by default) and\n+iterations in :class:`HalvingRandomSearchCV`. ``aggressive_elimination=True``\n+can also be used if the number of available resources is small. More control\n+is available through tuning the ``min_resources`` parameter.\n+\n+These estimators are still **experimental**: their predictions\n+and their API might change without any deprecation cycle. To use them, you\n+need to explicitly import ``enable_successive_halving``::\n+\n+ >>> # explicitly require this experimental feature\n+ >>> from sklearn.experimental import enable_successive_halving # noqa\n+ >>> # now you can import normally from model_selection\n+ >>> from sklearn.model_selection import HalvingGridSearchCV\n+ >>> from sklearn.model_selection import HalvingRandomSearchCV\n+\n+.. topic:: Examples:\n+\n+ * :ref:`sphx_glr_auto_examples_model_selection_plot_successive_halving_heatmap.py`\n+ * :ref:`sphx_glr_auto_examples_model_selection_plot_successive_halving_iterations.py`\n+\n+Choosing ``min_resources`` and the number of candidates\n+-------------------------------------------------------\n+\n+Beside ``factor``, the two main parameters that influence the behaviour of a\n+successive halving search are the ``min_resources`` parameter, and the\n+number of candidates (or parameter combinations) that are evaluated.\n+``min_resources`` is the amount of resources allocated at the first\n+iteration for each candidate. The number of candidates is specified directly\n+in :class:`HalvingRandomSearchCV`, and is determined from the ``param_grid``\n+parameter of :class:`HalvingGridSearchCV`.\n+\n+Consider a case where the resource is the number of samples, and where we\n+have 1000 samples. In theory, with ``min_resources=10`` and ``factor=2``, we\n+are able to run **at most** 7 iterations with the following number of\n+samples: ``[10, 20, 40, 80, 160, 320, 640]``.\n+\n+But depending on the number of candidates, we might run less than 7\n+iterations: if we start with a **small** number of candidates, the last\n+iteration might use less than 640 samples, which means not using all the\n+available resources (samples). For example if we start with 5 candidates, we\n+only need 2 iterations: 5 candidates for the first iteration, then\n+`5 // 2 = 2` candidates at the second iteration, after which we know which\n+candidate performs the best (so we don't need a third one). We would only be\n+using at most 20 samples which is a waste since we have 1000 samples at our\n+disposal. On the other hand, if we start with a **high** number of\n+candidates, we might end up with a lot of candidates at the last iteration,\n+which may not always be ideal: it means that many candidates will run with\n+the full resources, basically reducing the procedure to standard search.\n+\n+In the case of :class:`HalvingRandomSearchCV`, the number of candidates is set\n+by default such that the last iteration uses as much of the available\n+resources as possible. For :class:`HalvingGridSearchCV`, the number of\n+candidates is determined by the `param_grid` parameter. Changing the value of\n+``min_resources`` will impact the number of possible iterations, and as a\n+result will also have an effect on the ideal number of candidates.\n+\n+Another consideration when choosing ``min_resources`` is whether or not it\n+is easy to discriminate between good and bad candidates with a small amount\n+of resources. For example, if you need a lot of samples to distinguish\n+between good and bad parameters, a high ``min_resources`` is recommended. On\n+the other hand if the distinction is clear even with a small amount of\n+samples, then a small ``min_resources`` may be preferable since it would\n+speed up the computation.\n+\n+Notice in the example above that the last iteration does not use the maximum\n+amount of resources available: 1000 samples are available, yet only 640 are\n+used, at most. By default, both :class:`HalvingRandomSearchCV` and\n+:class:`HalvingGridSearchCV` try to use as many resources as possible in the\n+last iteration, with the constraint that this amount of resources must be a\n+multiple of both `min_resources` and `factor` (this constraint will be clear\n+in the next section). :class:`HalvingRandomSearchCV` achieves this by\n+sampling the right amount of candidates, while :class:`HalvingGridSearchCV`\n+achieves this by properly setting `min_resources`. Please see\n+:ref:`exhausting_the_resources` for details.\n+\n+.. _amount_of_resource_and_number_of_candidates:\n+\n+Amount of resource and number of candidates at each iteration\n+-------------------------------------------------------------\n+\n+At any iteration `i`, each candidate is allocated a given amount of resources\n+which we denote `n_resources_i`. This quantity is controlled by the\n+parameters ``factor`` and ``min_resources`` as follows (`factor` is strictly\n+greater than 1)::\n+\n+ n_resources_i = factor**i * min_resources,\n+\n+or equivalently::\n+\n+ n_resources_{i+1} = n_resources_i * factor\n+\n+where ``min_resources == n_resources_0`` is the amount of resources used at\n+the first iteration. ``factor`` also defines the proportions of candidates\n+that will be selected for the next iteration::\n+\n+ n_candidates_i = n_candidates // (factor ** i)\n+\n+or equivalently::\n+\n+ n_candidates_0 = n_candidates\n+ n_candidates_{i+1} = n_candidates_i // factor\n+\n+So in the first iteration, we use ``min_resources`` resources\n+``n_candidates`` times. In the second iteration, we use ``min_resources *\n+factor`` resources ``n_candidates // factor`` times. The third again\n+multiplies the resources per candidate and divides the number of candidates.\n+This process stops when the maximum amount of resource per candidate is\n+reached, or when we have identified the best candidate. The best candidate\n+is identified at the iteration that is evaluating `factor` or less candidates\n+(see just below for an explanation).\n+\n+Here is an example with ``min_resources=3`` and ``factor=2``, starting with\n+70 candidates:\n+\n++-----------------------+-----------------------+\n+| ``n_resources_i`` | ``n_candidates_i`` |\n++=======================+=======================+\n+| 3 (=min_resources) | 70 (=n_candidates) |\n++-----------------------+-----------------------+\n+| 3 * 2 = 6 | 70 // 2 = 35 |\n++-----------------------+-----------------------+\n+| 6 * 2 = 12 | 35 // 2 = 17 |\n++-----------------------+-----------------------+\n+| 12 * 2 = 24 | 17 // 2 = 8 |\n++-----------------------+-----------------------+\n+| 24 * 2 = 48 | 8 // 2 = 4 |\n++-----------------------+-----------------------+\n+| 48 * 2 = 96 | 4 // 2 = 2 |\n++-----------------------+-----------------------+\n+\n+We can note that:\n+\n+- the process stops at the first iteration which evaluates `factor=2`\n+ candidates: the best candidate is the best out of these 2 candidates. It\n+ is not necessary to run an additional iteration, since it would only\n+ evaluate one candidate (namely the best one, which we have already\n+ identified). For this reason, in general, we want the last iteration to\n+ run at most ``factor`` candidates. If the last iteration evaluates more\n+ than `factor` candidates, then this last iteration reduces to a regular\n+ search (as in :class:`RandomizedSearchCV` or :class:`GridSearchCV`).\n+- each ``n_resources_i`` is a multiple of both ``factor`` and\n+ ``min_resources`` (which is confirmed by its definition above).\n+\n+The amount of resources that is used at each iteration can be found in the\n+`n_resources_` attribute.\n+\n+Choosing a resource\n+-------------------\n+\n+By default, the resource is defined in terms of number of samples. That is,\n+each iteration will use an increasing amount of samples to train on. You can\n+however manually specify a parameter to use as the resource with the\n+``resource`` parameter. Here is an example where the resource is defined in\n+terms of the number of estimators of a random forest::\n+\n+ >>> from sklearn.datasets import make_classification\n+ >>> from sklearn.ensemble import RandomForestClassifier\n+ >>> from sklearn.experimental import enable_successive_halving # noqa\n+ >>> from sklearn.model_selection import HalvingGridSearchCV\n+ >>> import pandas as pd\n+ >>>\n+ >>> param_grid = {'max_depth': [3, 5, 10],\n+ ... 'min_samples_split': [2, 5, 10]}\n+ >>> base_estimator = RandomForestClassifier(random_state=0)\n+ >>> X, y = make_classification(n_samples=1000, random_state=0)\n+ >>> sh = HalvingGridSearchCV(base_estimator, param_grid, cv=5,\n+ ... factor=2, resource='n_estimators',\n+ ... max_resources=30).fit(X, y)\n+ >>> sh.best_estimator_\n+ RandomForestClassifier(max_depth=5, n_estimators=24, random_state=0)\n+\n+Note that it is not possible to budget on a parameter that is part of the\n+parameter grid.\n+\n+.. _exhausting_the_resources:\n+\n+Exhausting the available resources\n+----------------------------------\n+\n+As mentioned above, the number of resources that is used at each iteration\n+depends on the `min_resources` parameter.\n+If you have a lot of resources available but start with a low number of\n+resources, some of them might be wasted (i.e. not used)::\n+\n+ >>> from sklearn.datasets import make_classification\n+ >>> from sklearn.svm import SVC\n+ >>> from sklearn.experimental import enable_successive_halving # noqa\n+ >>> from sklearn.model_selection import HalvingGridSearchCV\n+ >>> import pandas as pd\n+ >>> param_grid= {'kernel': ('linear', 'rbf'),\n+ ... 'C': [1, 10, 100]}\n+ >>> base_estimator = SVC(gamma='scale')\n+ >>> X, y = make_classification(n_samples=1000)\n+ >>> sh = HalvingGridSearchCV(base_estimator, param_grid, cv=5,\n+ ... factor=2, min_resources=20).fit(X, y)\n+ >>> sh.n_resources_\n+ [20, 40, 80]\n+\n+The search process will only use 80 resources at most, while our maximum\n+amount of available resources is ``n_samples=1000``. Here, we have\n+``min_resources = r_0 = 20``.\n+\n+For :class:`HalvingGridSearchCV`, by default, the `min_resources` parameter\n+is set to 'exhaust'. This means that `min_resources` is automatically set\n+such that the last iteration can use as many resources as possible, within\n+the `max_resources` limit::\n+\n+ >>> sh = HalvingGridSearchCV(base_estimator, param_grid, cv=5,\n+ ... factor=2, min_resources='exhaust').fit(X, y)\n+ >>> sh.n_resources_\n+ [250, 500, 1000]\n+\n+`min_resources` was here automatically set to 250, which results in the last\n+iteration using all the resources. The exact value that is used depends on\n+the number of candidate parameter, on `max_resources` and on `factor`.\n+\n+For :class:`HalvingRandomSearchCV`, exhausting the resources can be done in 2\n+ways:\n+\n+- by setting `min_resources='exhaust'`, just like for\n+ :class:`HalvingGridSearchCV`;\n+- by setting `n_candidates='exhaust'`.\n+\n+Both options are mutally exclusive: using `min_resources='exhaust'` requires\n+knowing the number of candidates, and symmetrically `n_candidates='exhaust'`\n+requires knowing `min_resources`.\n+\n+In general, exhausting the total number of resources leads to a better final\n+candidate parameter, and is slightly more time-intensive.\n+\n+.. _aggressive_elimination:\n+\n+Aggressive elimination of candidates\n+------------------------------------\n+\n+Ideally, we want the last iteration to evaluate ``factor`` candidates (see\n+:ref:`amount_of_resource_and_number_of_candidates`). We then just have to\n+pick the best one. When the number of available resources is small with\n+respect to the number of candidates, the last iteration may have to evaluate\n+more than ``factor`` candidates::\n+\n+ >>> from sklearn.datasets import make_classification\n+ >>> from sklearn.svm import SVC\n+ >>> from sklearn.experimental import enable_successive_halving # noqa\n+ >>> from sklearn.model_selection import HalvingGridSearchCV\n+ >>> import pandas as pd\n+ >>>\n+ >>>\n+ >>> param_grid = {'kernel': ('linear', 'rbf'),\n+ ... 'C': [1, 10, 100]}\n+ >>> base_estimator = SVC(gamma='scale')\n+ >>> X, y = make_classification(n_samples=1000)\n+ >>> sh = HalvingGridSearchCV(base_estimator, param_grid, cv=5,\n+ ... factor=2, max_resources=40,\n+ ... aggressive_elimination=False).fit(X, y)\n+ >>> sh.n_resources_\n+ [20, 40]\n+ >>> sh.n_candidates_\n+ [6, 3]\n+\n+Since we cannot use more than ``max_resources=40`` resources, the process\n+has to stop at the second iteration which evaluates more than ``factor=2``\n+candidates.\n+\n+Using the ``aggressive_elimination`` parameter, you can force the search\n+process to end up with less than ``factor`` candidates at the last\n+iteration. To do this, the process will eliminate as many candidates as\n+necessary using ``min_resources`` resources::\n+\n+ >>> sh = HalvingGridSearchCV(base_estimator, param_grid, cv=5,\n+ ... factor=2,\n+ ... max_resources=40,\n+ ... aggressive_elimination=True,\n+ ... ).fit(X, y)\n+ >>> sh.n_resources_\n+ [20, 20, 40]\n+ >>> sh.n_candidates_\n+ [6, 3, 2]\n+\n+Notice that we end with 2 candidates at the last iteration since we have\n+eliminated enough candidates during the first iterations, using ``n_resources =\n+min_resources = 20``.\n+\n+.. _successive_halving_cv_results:\n+\n+Analysing results with the `cv_results_` attribute\n+--------------------------------------------------\n+\n+The ``cv_results_`` attribute contains useful information for analysing the\n+results of a search. It can be converted to a pandas dataframe with ``df =\n+pd.DataFrame(est.cv_results_)``. The ``cv_results_`` attribute of\n+:class:`HalvingGridSearchCV` and :class:`HalvingRandomSearchCV` is similar\n+to that of :class:`GridSearchCV` and :class:`RandomizedSearchCV`, with\n+additional information related to the successive halving process.\n+\n+Here is an example with some of the columns of a (truncated) dataframe:\n+\n+==== ====== =============== ================= =======================================================================================\n+ .. iter n_resources mean_test_score params\n+==== ====== =============== ================= =======================================================================================\n+ 0 0 125 0.983667 {'criterion': 'entropy', 'max_depth': None, 'max_features': 9, 'min_samples_split': 5}\n+ 1 0 125 0.983667 {'criterion': 'gini', 'max_depth': None, 'max_features': 8, 'min_samples_split': 7}\n+ 2 0 125 0.983667 {'criterion': 'gini', 'max_depth': None, 'max_features': 10, 'min_samples_split': 10}\n+ 3 0 125 0.983667 {'criterion': 'entropy', 'max_depth': None, 'max_features': 6, 'min_samples_split': 6}\n+ ... ... ... ... ...\n+ 15 2 500 0.951958 {'criterion': 'entropy', 'max_depth': None, 'max_features': 9, 'min_samples_split': 10}\n+ 16 2 500 0.947958 {'criterion': 'gini', 'max_depth': None, 'max_features': 10, 'min_samples_split': 10}\n+ 17 2 500 0.951958 {'criterion': 'gini', 'max_depth': None, 'max_features': 10, 'min_samples_split': 4}\n+ 18 3 1000 0.961009 {'criterion': 'entropy', 'max_depth': None, 'max_features': 9, 'min_samples_split': 10}\n+ 19 3 1000 0.955989 {'criterion': 'gini', 'max_depth': None, 'max_features': 10, 'min_samples_split': 4}\n+==== ====== =============== ================= =======================================================================================\n+\n+Each row corresponds to a given parameter combination (a candidate) and a given\n+iteration. The iteration is given by the ``iter`` column. The ``n_resources``\n+column tells you how many resources were used.\n+\n+In the example above, the best parameter combination is ``{'criterion':\n+'entropy', 'max_depth': None, 'max_features': 9, 'min_samples_split': 10}``\n+since it has reached the last iteration (3) with the highest score:\n+0.96.\n+\n+.. topic:: References:\n+\n+ .. [1] K. Jamieson, A. Talwalkar,\n+ `Non-stochastic Best Arm Identification and Hyperparameter\n+ Optimization <http://proceedings.mlr.press/v51/jamieson16.html>`_, in\n+ proc. of Machine Learning Research, 2016.\n+ .. [2] L. Li, K. Jamieson, G. DeSalvo, A. Rostamizadeh, A. Talwalkar,\n+ `Hyperband: A Novel Bandit-Based Approach to Hyperparameter Optimization\n+ <https://arxiv.org/abs/1603.06560>`_, in Machine Learning Research\n+ 18, 2018.\n+\n .. _grid_search_tips:\n \n Tips for parameter search\n@@ -183,18 +554,16 @@ to evaluate a parameter setting. These are the\n :func:`sklearn.metrics.r2_score` for regression. For some applications,\n other scoring functions are better suited (for example in unbalanced\n classification, the accuracy score is often uninformative). An alternative\n-scoring function can be specified via the ``scoring`` parameter to\n-:class:`GridSearchCV`, :class:`RandomizedSearchCV` and many of the\n-specialized cross-validation tools described below.\n-See :ref:`scoring_parameter` for more details.\n+scoring function can be specified via the ``scoring`` parameter of most\n+parameter search tools. See :ref:`scoring_parameter` for more details.\n \n .. _multimetric_grid_search:\n \n Specifying multiple metrics for evaluation\n ------------------------------------------\n \n-``GridSearchCV`` and ``RandomizedSearchCV`` allow specifying multiple metrics\n-for the ``scoring`` parameter.\n+:class:`GridSearchCV` and :class:`RandomizedSearchCV` allow specifying\n+multiple metrics for the ``scoring`` parameter.\n \n Multimetric scoring can either be specified as a list of strings of predefined\n scores names or a dict mapping the scorer name to the scorer function and/or\n@@ -209,6 +578,9 @@ result in an error when using multiple metrics.\n See :ref:`sphx_glr_auto_examples_model_selection_plot_multi_metric_evaluation.py`\n for an example usage.\n \n+:class:`HalvingRandomSearchCV` and :class:`HalvingGridSearchCV` do not support\n+multimetric scoring.\n+\n .. _composite_grid_search:\n \n Composite estimators and parameter spaces\n@@ -253,6 +625,8 @@ levels of nesting::\n ... 'model__base_estimator__max_depth': [2, 4, 6, 8]}\n >>> search = GridSearchCV(pipe, param_grid, cv=5).fit(X, y)\n \n+Please refer to :ref:`pipeline` for performing parameter searches over\n+pipelines.\n \n Model selection: development and evaluation\n -------------------------------------------\n@@ -263,7 +637,7 @@ to use the labeled data to \"train\" the parameters of the grid.\n When evaluating the resulting model it is important to do it on\n held-out samples that were not seen during the grid search process:\n it is recommended to split the data into a **development set** (to\n-be fed to the ``GridSearchCV`` instance) and an **evaluation set**\n+be fed to the :class:`GridSearchCV` instance) and an **evaluation set**\n to compute performance metrics.\n \n This can be done by using the :func:`train_test_split`\n@@ -272,10 +646,10 @@ utility function.\n Parallelism\n -----------\n \n-:class:`GridSearchCV` and :class:`RandomizedSearchCV` evaluate each parameter\n-setting independently. Computations can be run in parallel if your OS\n-supports it, by using the keyword ``n_jobs=-1``. See function signature for\n-more details.\n+The parameter search tools evaluate each parameter combination on each data\n+fold independently. Computations can be run in parallel by using the keyword\n+``n_jobs=-1``. See function signature for more details, and also the Glossary\n+entry for :term:`n_jobs`.\n \n Robustness to failure\n ---------------------\n" }, { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex c57f097ec3218..e757fee299af7 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -412,6 +412,14 @@ Changelog\n :pr:`<PRID>` by :user:`<NAME>` and\n :user:`<NAME>`.\n \n+- |Feature| Added (experimental) parameter search estimators\n+ :class:`model_selection.HalvingRandomSearchCV` and\n+ :class:`model_selection.HalvingGridSearchCV` which implement Successive\n+ Halving, and can be used as a drop-in replacements for\n+ :class:`model_selection.RandomizedSearchCV` and\n+ :class:`model_selection.GridSearchCV`. :pr:`<PRID>` by `<NAME>`_, `Joel\n+ Nothman`_ and `Andreas Müller`_.\n+\n - |Fix| Fixed the `len` of :class:`model_selection.ParameterSampler` when\n all distributions are lists and `n_iter` is more than the number of unique\n parameter combinations. :pr:`<PRID>` by `<NAME>`_.\n" } ]
diff --git a/doc/conf.py b/doc/conf.py index ccf5dcd068131..b09c5a15b133d 100644 --- a/doc/conf.py +++ b/doc/conf.py @@ -356,6 +356,7 @@ def __call__(self, directory): # discovered properly by sphinx from sklearn.experimental import enable_hist_gradient_boosting # noqa from sklearn.experimental import enable_iterative_imputer # noqa +from sklearn.experimental import enable_successive_halving # noqa def make_carousel_thumbs(app, exception): diff --git a/doc/conftest.py b/doc/conftest.py index eacd469f2e52f..96d42fd96066d 100644 --- a/doc/conftest.py +++ b/doc/conftest.py @@ -57,6 +57,13 @@ def setup_impute(): raise SkipTest("Skipping impute.rst, pandas not installed") +def setup_grid_search(): + try: + import pandas # noqa + except ImportError: + raise SkipTest("Skipping grid_search.rst, pandas not installed") + + def setup_unsupervised_learning(): try: import skimage # noqa @@ -86,5 +93,7 @@ def pytest_runtest_setup(item): raise SkipTest('FeatureHasher is not compatible with PyPy') elif fname.endswith('modules/impute.rst'): setup_impute() + elif fname.endswith('modules/grid_search.rst'): + setup_grid_search() elif fname.endswith('statistical_inference/unsupervised_learning.rst'): setup_unsupervised_learning() diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst index a0ee97aed260a..07fbaf384efd9 100644 --- a/doc/modules/classes.rst +++ b/doc/modules/classes.rst @@ -1194,9 +1194,11 @@ Hyper-parameter optimizers :template: class.rst model_selection.GridSearchCV + model_selection.HalvingGridSearchCV model_selection.ParameterGrid model_selection.ParameterSampler model_selection.RandomizedSearchCV + model_selection.HalvingRandomSearchCV Model validation diff --git a/doc/modules/grid_search.rst b/doc/modules/grid_search.rst index 9d6c1c7e58170..c88a6eb986b5a 100644 --- a/doc/modules/grid_search.rst +++ b/doc/modules/grid_search.rst @@ -30,14 +30,18 @@ A search consists of: - a cross-validation scheme; and - a :ref:`score function <gridsearch_scoring>`. -Some models allow for specialized, efficient parameter search strategies, -:ref:`outlined below <alternative_cv>`. -Two generic approaches to sampling search candidates are provided in +Two generic approaches to parameter search are provided in scikit-learn: for given values, :class:`GridSearchCV` exhaustively considers all parameter combinations, while :class:`RandomizedSearchCV` can sample a given number of candidates from a parameter space with a specified -distribution. After describing these tools we detail -:ref:`best practice <grid_search_tips>` applicable to both approaches. +distribution. Both these tools have successive halving counterparts +:class:`HalvingGridSearchCV` and :class:`HalvingRandomSearchCV`, which can be +much faster at finding a good parameter combination. + +After describing these tools we detail :ref:`best practices +<grid_search_tips>` applicable to these approaches. Some models allow for +specialized, efficient parameter search strategies, outlined in +:ref:`alternative_cv`. Note that it is common that a small subset of those parameters can have a large impact on the predictive or computation performance of the model while others @@ -167,6 +171,373 @@ variable that is log-uniformly distributed between ``1e0`` and ``1e3``:: Random search for hyper-parameter optimization, The Journal of Machine Learning Research (2012) +.. _successive_halving_user_guide: + +Searching for optimal parameters with successive halving +======================================================== + +Scikit-learn also provides the :class:`HalvingGridSearchCV` and +:class:`HalvingRandomSearchCV` estimators that can be used to +search a parameter space using successive halving [1]_ [2]_. Successive +halving (SH) is like a tournament among candidate parameter combinations. +SH is an iterative selection process where all candidates (the +parameter combinations) are evaluated with a small amount of resources at +the first iteration. Only some of these candidates are selected for the next +iteration, which will be allocated more resources. For parameter tuning, the +resource is typically the number of training samples, but it can also be an +arbitrary numeric parameter such as `n_estimators` in a random forest. + +As illustrated in the figure below, only a subset of candidates +'survive' until the last iteration. These are the candidates that have +consistently ranked among the top-scoring candidates across all iterations. +Each iteration is allocated an increasing amount of resources per candidate, +here the number of samples. + +.. figure:: ../auto_examples/model_selection/images/sphx_glr_plot_successive_halving_iterations_001.png + :target: ../auto_examples/model_selection/plot_successive_halving_iterations.html + :align: center + +We here briefly describe the main parameters, but each parameter and their +interactions are described in more details in the sections below. The +``factor`` (> 1) parameter controls the rate at which the resources grow, and +the rate at which the number of candidates decreases. In each iteration, the +number of resources per candidate is multiplied by ``factor`` and the number +of candidates is divided by the same factor. Along with ``resource`` and +``min_resources``, ``factor`` is the most important parameter to control the +search in our implementation, though a value of 3 usually works well. +``factor`` effectively controls the number of iterations in +:class:`HalvingGridSearchCV` and the number of candidates (by default) and +iterations in :class:`HalvingRandomSearchCV`. ``aggressive_elimination=True`` +can also be used if the number of available resources is small. More control +is available through tuning the ``min_resources`` parameter. + +These estimators are still **experimental**: their predictions +and their API might change without any deprecation cycle. To use them, you +need to explicitly import ``enable_successive_halving``:: + + >>> # explicitly require this experimental feature + >>> from sklearn.experimental import enable_successive_halving # noqa + >>> # now you can import normally from model_selection + >>> from sklearn.model_selection import HalvingGridSearchCV + >>> from sklearn.model_selection import HalvingRandomSearchCV + +.. topic:: Examples: + + * :ref:`sphx_glr_auto_examples_model_selection_plot_successive_halving_heatmap.py` + * :ref:`sphx_glr_auto_examples_model_selection_plot_successive_halving_iterations.py` + +Choosing ``min_resources`` and the number of candidates +------------------------------------------------------- + +Beside ``factor``, the two main parameters that influence the behaviour of a +successive halving search are the ``min_resources`` parameter, and the +number of candidates (or parameter combinations) that are evaluated. +``min_resources`` is the amount of resources allocated at the first +iteration for each candidate. The number of candidates is specified directly +in :class:`HalvingRandomSearchCV`, and is determined from the ``param_grid`` +parameter of :class:`HalvingGridSearchCV`. + +Consider a case where the resource is the number of samples, and where we +have 1000 samples. In theory, with ``min_resources=10`` and ``factor=2``, we +are able to run **at most** 7 iterations with the following number of +samples: ``[10, 20, 40, 80, 160, 320, 640]``. + +But depending on the number of candidates, we might run less than 7 +iterations: if we start with a **small** number of candidates, the last +iteration might use less than 640 samples, which means not using all the +available resources (samples). For example if we start with 5 candidates, we +only need 2 iterations: 5 candidates for the first iteration, then +`5 // 2 = 2` candidates at the second iteration, after which we know which +candidate performs the best (so we don't need a third one). We would only be +using at most 20 samples which is a waste since we have 1000 samples at our +disposal. On the other hand, if we start with a **high** number of +candidates, we might end up with a lot of candidates at the last iteration, +which may not always be ideal: it means that many candidates will run with +the full resources, basically reducing the procedure to standard search. + +In the case of :class:`HalvingRandomSearchCV`, the number of candidates is set +by default such that the last iteration uses as much of the available +resources as possible. For :class:`HalvingGridSearchCV`, the number of +candidates is determined by the `param_grid` parameter. Changing the value of +``min_resources`` will impact the number of possible iterations, and as a +result will also have an effect on the ideal number of candidates. + +Another consideration when choosing ``min_resources`` is whether or not it +is easy to discriminate between good and bad candidates with a small amount +of resources. For example, if you need a lot of samples to distinguish +between good and bad parameters, a high ``min_resources`` is recommended. On +the other hand if the distinction is clear even with a small amount of +samples, then a small ``min_resources`` may be preferable since it would +speed up the computation. + +Notice in the example above that the last iteration does not use the maximum +amount of resources available: 1000 samples are available, yet only 640 are +used, at most. By default, both :class:`HalvingRandomSearchCV` and +:class:`HalvingGridSearchCV` try to use as many resources as possible in the +last iteration, with the constraint that this amount of resources must be a +multiple of both `min_resources` and `factor` (this constraint will be clear +in the next section). :class:`HalvingRandomSearchCV` achieves this by +sampling the right amount of candidates, while :class:`HalvingGridSearchCV` +achieves this by properly setting `min_resources`. Please see +:ref:`exhausting_the_resources` for details. + +.. _amount_of_resource_and_number_of_candidates: + +Amount of resource and number of candidates at each iteration +------------------------------------------------------------- + +At any iteration `i`, each candidate is allocated a given amount of resources +which we denote `n_resources_i`. This quantity is controlled by the +parameters ``factor`` and ``min_resources`` as follows (`factor` is strictly +greater than 1):: + + n_resources_i = factor**i * min_resources, + +or equivalently:: + + n_resources_{i+1} = n_resources_i * factor + +where ``min_resources == n_resources_0`` is the amount of resources used at +the first iteration. ``factor`` also defines the proportions of candidates +that will be selected for the next iteration:: + + n_candidates_i = n_candidates // (factor ** i) + +or equivalently:: + + n_candidates_0 = n_candidates + n_candidates_{i+1} = n_candidates_i // factor + +So in the first iteration, we use ``min_resources`` resources +``n_candidates`` times. In the second iteration, we use ``min_resources * +factor`` resources ``n_candidates // factor`` times. The third again +multiplies the resources per candidate and divides the number of candidates. +This process stops when the maximum amount of resource per candidate is +reached, or when we have identified the best candidate. The best candidate +is identified at the iteration that is evaluating `factor` or less candidates +(see just below for an explanation). + +Here is an example with ``min_resources=3`` and ``factor=2``, starting with +70 candidates: + ++-----------------------+-----------------------+ +| ``n_resources_i`` | ``n_candidates_i`` | ++=======================+=======================+ +| 3 (=min_resources) | 70 (=n_candidates) | ++-----------------------+-----------------------+ +| 3 * 2 = 6 | 70 // 2 = 35 | ++-----------------------+-----------------------+ +| 6 * 2 = 12 | 35 // 2 = 17 | ++-----------------------+-----------------------+ +| 12 * 2 = 24 | 17 // 2 = 8 | ++-----------------------+-----------------------+ +| 24 * 2 = 48 | 8 // 2 = 4 | ++-----------------------+-----------------------+ +| 48 * 2 = 96 | 4 // 2 = 2 | ++-----------------------+-----------------------+ + +We can note that: + +- the process stops at the first iteration which evaluates `factor=2` + candidates: the best candidate is the best out of these 2 candidates. It + is not necessary to run an additional iteration, since it would only + evaluate one candidate (namely the best one, which we have already + identified). For this reason, in general, we want the last iteration to + run at most ``factor`` candidates. If the last iteration evaluates more + than `factor` candidates, then this last iteration reduces to a regular + search (as in :class:`RandomizedSearchCV` or :class:`GridSearchCV`). +- each ``n_resources_i`` is a multiple of both ``factor`` and + ``min_resources`` (which is confirmed by its definition above). + +The amount of resources that is used at each iteration can be found in the +`n_resources_` attribute. + +Choosing a resource +------------------- + +By default, the resource is defined in terms of number of samples. That is, +each iteration will use an increasing amount of samples to train on. You can +however manually specify a parameter to use as the resource with the +``resource`` parameter. Here is an example where the resource is defined in +terms of the number of estimators of a random forest:: + + >>> from sklearn.datasets import make_classification + >>> from sklearn.ensemble import RandomForestClassifier + >>> from sklearn.experimental import enable_successive_halving # noqa + >>> from sklearn.model_selection import HalvingGridSearchCV + >>> import pandas as pd + >>> + >>> param_grid = {'max_depth': [3, 5, 10], + ... 'min_samples_split': [2, 5, 10]} + >>> base_estimator = RandomForestClassifier(random_state=0) + >>> X, y = make_classification(n_samples=1000, random_state=0) + >>> sh = HalvingGridSearchCV(base_estimator, param_grid, cv=5, + ... factor=2, resource='n_estimators', + ... max_resources=30).fit(X, y) + >>> sh.best_estimator_ + RandomForestClassifier(max_depth=5, n_estimators=24, random_state=0) + +Note that it is not possible to budget on a parameter that is part of the +parameter grid. + +.. _exhausting_the_resources: + +Exhausting the available resources +---------------------------------- + +As mentioned above, the number of resources that is used at each iteration +depends on the `min_resources` parameter. +If you have a lot of resources available but start with a low number of +resources, some of them might be wasted (i.e. not used):: + + >>> from sklearn.datasets import make_classification + >>> from sklearn.svm import SVC + >>> from sklearn.experimental import enable_successive_halving # noqa + >>> from sklearn.model_selection import HalvingGridSearchCV + >>> import pandas as pd + >>> param_grid= {'kernel': ('linear', 'rbf'), + ... 'C': [1, 10, 100]} + >>> base_estimator = SVC(gamma='scale') + >>> X, y = make_classification(n_samples=1000) + >>> sh = HalvingGridSearchCV(base_estimator, param_grid, cv=5, + ... factor=2, min_resources=20).fit(X, y) + >>> sh.n_resources_ + [20, 40, 80] + +The search process will only use 80 resources at most, while our maximum +amount of available resources is ``n_samples=1000``. Here, we have +``min_resources = r_0 = 20``. + +For :class:`HalvingGridSearchCV`, by default, the `min_resources` parameter +is set to 'exhaust'. This means that `min_resources` is automatically set +such that the last iteration can use as many resources as possible, within +the `max_resources` limit:: + + >>> sh = HalvingGridSearchCV(base_estimator, param_grid, cv=5, + ... factor=2, min_resources='exhaust').fit(X, y) + >>> sh.n_resources_ + [250, 500, 1000] + +`min_resources` was here automatically set to 250, which results in the last +iteration using all the resources. The exact value that is used depends on +the number of candidate parameter, on `max_resources` and on `factor`. + +For :class:`HalvingRandomSearchCV`, exhausting the resources can be done in 2 +ways: + +- by setting `min_resources='exhaust'`, just like for + :class:`HalvingGridSearchCV`; +- by setting `n_candidates='exhaust'`. + +Both options are mutally exclusive: using `min_resources='exhaust'` requires +knowing the number of candidates, and symmetrically `n_candidates='exhaust'` +requires knowing `min_resources`. + +In general, exhausting the total number of resources leads to a better final +candidate parameter, and is slightly more time-intensive. + +.. _aggressive_elimination: + +Aggressive elimination of candidates +------------------------------------ + +Ideally, we want the last iteration to evaluate ``factor`` candidates (see +:ref:`amount_of_resource_and_number_of_candidates`). We then just have to +pick the best one. When the number of available resources is small with +respect to the number of candidates, the last iteration may have to evaluate +more than ``factor`` candidates:: + + >>> from sklearn.datasets import make_classification + >>> from sklearn.svm import SVC + >>> from sklearn.experimental import enable_successive_halving # noqa + >>> from sklearn.model_selection import HalvingGridSearchCV + >>> import pandas as pd + >>> + >>> + >>> param_grid = {'kernel': ('linear', 'rbf'), + ... 'C': [1, 10, 100]} + >>> base_estimator = SVC(gamma='scale') + >>> X, y = make_classification(n_samples=1000) + >>> sh = HalvingGridSearchCV(base_estimator, param_grid, cv=5, + ... factor=2, max_resources=40, + ... aggressive_elimination=False).fit(X, y) + >>> sh.n_resources_ + [20, 40] + >>> sh.n_candidates_ + [6, 3] + +Since we cannot use more than ``max_resources=40`` resources, the process +has to stop at the second iteration which evaluates more than ``factor=2`` +candidates. + +Using the ``aggressive_elimination`` parameter, you can force the search +process to end up with less than ``factor`` candidates at the last +iteration. To do this, the process will eliminate as many candidates as +necessary using ``min_resources`` resources:: + + >>> sh = HalvingGridSearchCV(base_estimator, param_grid, cv=5, + ... factor=2, + ... max_resources=40, + ... aggressive_elimination=True, + ... ).fit(X, y) + >>> sh.n_resources_ + [20, 20, 40] + >>> sh.n_candidates_ + [6, 3, 2] + +Notice that we end with 2 candidates at the last iteration since we have +eliminated enough candidates during the first iterations, using ``n_resources = +min_resources = 20``. + +.. _successive_halving_cv_results: + +Analysing results with the `cv_results_` attribute +-------------------------------------------------- + +The ``cv_results_`` attribute contains useful information for analysing the +results of a search. It can be converted to a pandas dataframe with ``df = +pd.DataFrame(est.cv_results_)``. The ``cv_results_`` attribute of +:class:`HalvingGridSearchCV` and :class:`HalvingRandomSearchCV` is similar +to that of :class:`GridSearchCV` and :class:`RandomizedSearchCV`, with +additional information related to the successive halving process. + +Here is an example with some of the columns of a (truncated) dataframe: + +==== ====== =============== ================= ======================================================================================= + .. iter n_resources mean_test_score params +==== ====== =============== ================= ======================================================================================= + 0 0 125 0.983667 {'criterion': 'entropy', 'max_depth': None, 'max_features': 9, 'min_samples_split': 5} + 1 0 125 0.983667 {'criterion': 'gini', 'max_depth': None, 'max_features': 8, 'min_samples_split': 7} + 2 0 125 0.983667 {'criterion': 'gini', 'max_depth': None, 'max_features': 10, 'min_samples_split': 10} + 3 0 125 0.983667 {'criterion': 'entropy', 'max_depth': None, 'max_features': 6, 'min_samples_split': 6} + ... ... ... ... ... + 15 2 500 0.951958 {'criterion': 'entropy', 'max_depth': None, 'max_features': 9, 'min_samples_split': 10} + 16 2 500 0.947958 {'criterion': 'gini', 'max_depth': None, 'max_features': 10, 'min_samples_split': 10} + 17 2 500 0.951958 {'criterion': 'gini', 'max_depth': None, 'max_features': 10, 'min_samples_split': 4} + 18 3 1000 0.961009 {'criterion': 'entropy', 'max_depth': None, 'max_features': 9, 'min_samples_split': 10} + 19 3 1000 0.955989 {'criterion': 'gini', 'max_depth': None, 'max_features': 10, 'min_samples_split': 4} +==== ====== =============== ================= ======================================================================================= + +Each row corresponds to a given parameter combination (a candidate) and a given +iteration. The iteration is given by the ``iter`` column. The ``n_resources`` +column tells you how many resources were used. + +In the example above, the best parameter combination is ``{'criterion': +'entropy', 'max_depth': None, 'max_features': 9, 'min_samples_split': 10}`` +since it has reached the last iteration (3) with the highest score: +0.96. + +.. topic:: References: + + .. [1] K. Jamieson, A. Talwalkar, + `Non-stochastic Best Arm Identification and Hyperparameter + Optimization <http://proceedings.mlr.press/v51/jamieson16.html>`_, in + proc. of Machine Learning Research, 2016. + .. [2] L. Li, K. Jamieson, G. DeSalvo, A. Rostamizadeh, A. Talwalkar, + `Hyperband: A Novel Bandit-Based Approach to Hyperparameter Optimization + <https://arxiv.org/abs/1603.06560>`_, in Machine Learning Research + 18, 2018. + .. _grid_search_tips: Tips for parameter search @@ -183,18 +554,16 @@ to evaluate a parameter setting. These are the :func:`sklearn.metrics.r2_score` for regression. For some applications, other scoring functions are better suited (for example in unbalanced classification, the accuracy score is often uninformative). An alternative -scoring function can be specified via the ``scoring`` parameter to -:class:`GridSearchCV`, :class:`RandomizedSearchCV` and many of the -specialized cross-validation tools described below. -See :ref:`scoring_parameter` for more details. +scoring function can be specified via the ``scoring`` parameter of most +parameter search tools. See :ref:`scoring_parameter` for more details. .. _multimetric_grid_search: Specifying multiple metrics for evaluation ------------------------------------------ -``GridSearchCV`` and ``RandomizedSearchCV`` allow specifying multiple metrics -for the ``scoring`` parameter. +:class:`GridSearchCV` and :class:`RandomizedSearchCV` allow specifying +multiple metrics for the ``scoring`` parameter. Multimetric scoring can either be specified as a list of strings of predefined scores names or a dict mapping the scorer name to the scorer function and/or @@ -209,6 +578,9 @@ result in an error when using multiple metrics. See :ref:`sphx_glr_auto_examples_model_selection_plot_multi_metric_evaluation.py` for an example usage. +:class:`HalvingRandomSearchCV` and :class:`HalvingGridSearchCV` do not support +multimetric scoring. + .. _composite_grid_search: Composite estimators and parameter spaces @@ -253,6 +625,8 @@ levels of nesting:: ... 'model__base_estimator__max_depth': [2, 4, 6, 8]} >>> search = GridSearchCV(pipe, param_grid, cv=5).fit(X, y) +Please refer to :ref:`pipeline` for performing parameter searches over +pipelines. Model selection: development and evaluation ------------------------------------------- @@ -263,7 +637,7 @@ to use the labeled data to "train" the parameters of the grid. When evaluating the resulting model it is important to do it on held-out samples that were not seen during the grid search process: it is recommended to split the data into a **development set** (to -be fed to the ``GridSearchCV`` instance) and an **evaluation set** +be fed to the :class:`GridSearchCV` instance) and an **evaluation set** to compute performance metrics. This can be done by using the :func:`train_test_split` @@ -272,10 +646,10 @@ utility function. Parallelism ----------- -:class:`GridSearchCV` and :class:`RandomizedSearchCV` evaluate each parameter -setting independently. Computations can be run in parallel if your OS -supports it, by using the keyword ``n_jobs=-1``. See function signature for -more details. +The parameter search tools evaluate each parameter combination on each data +fold independently. Computations can be run in parallel by using the keyword +``n_jobs=-1``. See function signature for more details, and also the Glossary +entry for :term:`n_jobs`. Robustness to failure --------------------- diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index c57f097ec3218..e757fee299af7 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -412,6 +412,14 @@ Changelog :pr:`<PRID>` by :user:`<NAME>` and :user:`<NAME>`. +- |Feature| Added (experimental) parameter search estimators + :class:`model_selection.HalvingRandomSearchCV` and + :class:`model_selection.HalvingGridSearchCV` which implement Successive + Halving, and can be used as a drop-in replacements for + :class:`model_selection.RandomizedSearchCV` and + :class:`model_selection.GridSearchCV`. :pr:`<PRID>` by `<NAME>`_, `Joel + Nothman`_ and `Andreas Müller`_. + - |Fix| Fixed the `len` of :class:`model_selection.ParameterSampler` when all distributions are lists and `n_iter` is more than the number of unique parameter combinations. :pr:`<PRID>` by `<NAME>`_. If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names: [{'type': 'file', 'name': 'examples/model_selection/plot_successive_halving_iterations.py'}, {'type': 'file', 'name': 'sklearn/experimental/enable_successive_halving.py'}, {'type': 'file', 'name': 'examples/model_selection/plot_successive_halving_heatmap.py'}, {'type': 'file', 'name': 'sklearn/model_selection/_search_successive_halving.py'}]
scikit-learn/scikit-learn
scikit-learn__scikit-learn-13204
https://github.com/scikit-learn/scikit-learn/pull/13204
diff --git a/doc/modules/cross_validation.rst b/doc/modules/cross_validation.rst index ed014cea6f2ff..61ea8c7ef4248 100644 --- a/doc/modules/cross_validation.rst +++ b/doc/modules/cross_validation.rst @@ -782,7 +782,7 @@ Example of 3-split time series cross-validation on a dataset with 6 samples:: >>> y = np.array([1, 2, 3, 4, 5, 6]) >>> tscv = TimeSeriesSplit(n_splits=3) >>> print(tscv) - TimeSeriesSplit(max_train_size=None, n_splits=3) + TimeSeriesSplit(gap=0, max_train_size=None, n_splits=3, test_size=None) >>> for train, test in tscv.split(X): ... print("%s %s" % (train, test)) [0 1 2] [3] diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index dd4ab30a7f2ff..2554d136c13ea 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -47,6 +47,15 @@ Changelog :mod:`sklearn.module` ..................... +:mod:`sklearn.model_selection` +.............................. + +- |Enhancement| :class:`model_selection.TimeSeriesSplit` has two new keyword + arguments `test_size` and `gap`. `test_size` allows the out-of-sample + time series length to be fixed for all folds. `gap` removes a fixed number of + samples between the train and test set on each fold. + :pr:`13204` by :user:`Kyle Kosic <kykosic>`. + Code and Documentation Contributors ----------------------------------- diff --git a/sklearn/model_selection/_split.py b/sklearn/model_selection/_split.py index 9b2087e039f40..75a4b865fda62 100644 --- a/sklearn/model_selection/_split.py +++ b/sklearn/model_selection/_split.py @@ -766,6 +766,15 @@ class TimeSeriesSplit(_BaseKFold): max_train_size : int, default=None Maximum size for a single training set. + test_size : int, default=None + Used to limit the size of the test set. Defaults to + ``n_samples // (n_splits + 1)``, which is the maximum allowed value + with ``gap=0``. + + gap : int, default=0 + Number of samples to exclude from the end of each train set before + the test set. + Examples -------- >>> import numpy as np @@ -774,7 +783,7 @@ class TimeSeriesSplit(_BaseKFold): >>> y = np.array([1, 2, 3, 4, 5, 6]) >>> tscv = TimeSeriesSplit() >>> print(tscv) - TimeSeriesSplit(max_train_size=None, n_splits=5) + TimeSeriesSplit(gap=0, max_train_size=None, n_splits=5, test_size=None) >>> for train_index, test_index in tscv.split(X): ... print("TRAIN:", train_index, "TEST:", test_index) ... X_train, X_test = X[train_index], X[test_index] @@ -784,18 +793,45 @@ class TimeSeriesSplit(_BaseKFold): TRAIN: [0 1 2] TEST: [3] TRAIN: [0 1 2 3] TEST: [4] TRAIN: [0 1 2 3 4] TEST: [5] + >>> # Fix test_size to 2 with 12 samples + >>> X = np.random.randn(12, 2) + >>> y = np.random.randint(0, 2, 12) + >>> tscv = TimeSeriesSplit(n_splits=3, test_size=2) + >>> for train_index, test_index in tscv.split(X): + ... print("TRAIN:", train_index, "TEST:", test_index) + ... X_train, X_test = X[train_index], X[test_index] + ... y_train, y_test = y[train_index], y[test_index] + TRAIN: [0 1 2 3 4 5] TEST: [6 7] + TRAIN: [0 1 2 3 4 5 6 7] TEST: [8 9] + TRAIN: [0 1 2 3 4 5 6 7 8 9] TEST: [10 11] + >>> # Add in a 2 period gap + >>> tscv = TimeSeriesSplit(n_splits=3, test_size=2, gap=2) + >>> for train_index, test_index in tscv.split(X): + ... print("TRAIN:", train_index, "TEST:", test_index) + ... X_train, X_test = X[train_index], X[test_index] + ... y_train, y_test = y[train_index], y[test_index] + TRAIN: [0 1 2 3] TEST: [6 7] + TRAIN: [0 1 2 3 4 5] TEST: [8 9] + TRAIN: [0 1 2 3 4 5 6 7] TEST: [10 11] Notes ----- The training set has size ``i * n_samples // (n_splits + 1) + n_samples % (n_splits + 1)`` in the ``i``th split, - with a test set of size ``n_samples//(n_splits + 1)``, + with a test set of size ``n_samples//(n_splits + 1)`` by default, where ``n_samples`` is the number of samples. """ @_deprecate_positional_args - def __init__(self, n_splits=5, *, max_train_size=None): + def __init__(self, + n_splits=5, + *, + max_train_size=None, + test_size=None, + gap=0): super().__init__(n_splits, shuffle=False, random_state=None) self.max_train_size = max_train_size + self.test_size = test_size + self.gap = gap def split(self, X, y=None, groups=None): """Generate indices to split data into training and test set. @@ -824,21 +860,31 @@ def split(self, X, y=None, groups=None): n_samples = _num_samples(X) n_splits = self.n_splits n_folds = n_splits + 1 + gap = self.gap + test_size = self.test_size if self.test_size is not None \ + else n_samples // n_folds + + # Make sure we have enough samples for the given split parameters if n_folds > n_samples: raise ValueError( - ("Cannot have number of folds ={0} greater" - " than the number of samples: {1}.").format(n_folds, - n_samples)) + (f"Cannot have number of folds={n_folds} greater" + f" than the number of samples={n_samples}.")) + if n_samples - gap - (test_size * n_splits) <= 0: + raise ValueError( + (f"Too many splits={n_splits} for number of samples" + f"={n_samples} with test_size={test_size} and gap={gap}.")) + indices = np.arange(n_samples) - test_size = (n_samples // n_folds) - test_starts = range(test_size + n_samples % n_folds, + test_starts = range(n_samples - n_splits * test_size, n_samples, test_size) + for test_start in test_starts: - if self.max_train_size and self.max_train_size < test_start: - yield (indices[test_start - self.max_train_size:test_start], + train_end = test_start - gap + if self.max_train_size and self.max_train_size < train_end: + yield (indices[train_end - self.max_train_size:train_end], indices[test_start:test_start + test_size]) else: - yield (indices[:test_start], + yield (indices[:train_end], indices[test_start:test_start + test_size])
diff --git a/sklearn/model_selection/tests/test_split.py b/sklearn/model_selection/tests/test_split.py index 3b984745420f1..b89571ba085dd 100644 --- a/sklearn/model_selection/tests/test_split.py +++ b/sklearn/model_selection/tests/test_split.py @@ -1440,6 +1440,100 @@ def test_time_series_max_train_size(): _check_time_series_max_train_size(splits, check_splits, max_train_size=2) +def test_time_series_test_size(): + X = np.zeros((10, 1)) + + # Test alone + splits = TimeSeriesSplit(n_splits=3, test_size=3).split(X) + + train, test = next(splits) + assert_array_equal(train, [0]) + assert_array_equal(test, [1, 2, 3]) + + train, test = next(splits) + assert_array_equal(train, [0, 1, 2, 3]) + assert_array_equal(test, [4, 5, 6]) + + train, test = next(splits) + assert_array_equal(train, [0, 1, 2, 3, 4, 5, 6]) + assert_array_equal(test, [7, 8, 9]) + + # Test with max_train_size + splits = TimeSeriesSplit(n_splits=2, test_size=2, + max_train_size=4).split(X) + + train, test = next(splits) + assert_array_equal(train, [2, 3, 4, 5]) + assert_array_equal(test, [6, 7]) + + train, test = next(splits) + assert_array_equal(train, [4, 5, 6, 7]) + assert_array_equal(test, [8, 9]) + + # Should fail with not enough data points for configuration + with pytest.raises(ValueError, match="Too many splits.*with test_size"): + splits = TimeSeriesSplit(n_splits=5, test_size=2).split(X) + next(splits) + + +def test_time_series_gap(): + X = np.zeros((10, 1)) + + # Test alone + splits = TimeSeriesSplit(n_splits=2, gap=2).split(X) + + train, test = next(splits) + assert_array_equal(train, [0, 1]) + assert_array_equal(test, [4, 5, 6]) + + train, test = next(splits) + assert_array_equal(train, [0, 1, 2, 3, 4]) + assert_array_equal(test, [7, 8, 9]) + + # Test with max_train_size + splits = TimeSeriesSplit(n_splits=3, gap=2, max_train_size=2).split(X) + + train, test = next(splits) + assert_array_equal(train, [0, 1]) + assert_array_equal(test, [4, 5]) + + train, test = next(splits) + assert_array_equal(train, [2, 3]) + assert_array_equal(test, [6, 7]) + + train, test = next(splits) + assert_array_equal(train, [4, 5]) + assert_array_equal(test, [8, 9]) + + # Test with test_size + splits = TimeSeriesSplit(n_splits=2, gap=2, + max_train_size=4, test_size=2).split(X) + + train, test = next(splits) + assert_array_equal(train, [0, 1, 2, 3]) + assert_array_equal(test, [6, 7]) + + train, test = next(splits) + assert_array_equal(train, [2, 3, 4, 5]) + assert_array_equal(test, [8, 9]) + + # Test with additional test_size + splits = TimeSeriesSplit(n_splits=2, gap=2, test_size=3).split(X) + + train, test = next(splits) + assert_array_equal(train, [0, 1]) + assert_array_equal(test, [4, 5, 6]) + + train, test = next(splits) + assert_array_equal(train, [0, 1, 2, 3, 4]) + assert_array_equal(test, [7, 8, 9]) + + # Verify proper error is thrown + with pytest.raises(ValueError, match="Too many splits.*and gap"): + splits = TimeSeriesSplit(n_splits=4, gap=2).split(X) + next(splits) + + def test_nested_cv(): # Test if nested cross validation works with different combinations of cv rng = np.random.RandomState(0)
[ { "path": "doc/modules/cross_validation.rst", "old_path": "a/doc/modules/cross_validation.rst", "new_path": "b/doc/modules/cross_validation.rst", "metadata": "diff --git a/doc/modules/cross_validation.rst b/doc/modules/cross_validation.rst\nindex ed014cea6f2ff..61ea8c7ef4248 100644\n--- a/doc/modules/cross_validation.rst\n+++ b/doc/modules/cross_validation.rst\n@@ -782,7 +782,7 @@ Example of 3-split time series cross-validation on a dataset with 6 samples::\n >>> y = np.array([1, 2, 3, 4, 5, 6])\n >>> tscv = TimeSeriesSplit(n_splits=3)\n >>> print(tscv)\n- TimeSeriesSplit(max_train_size=None, n_splits=3)\n+ TimeSeriesSplit(gap=0, max_train_size=None, n_splits=3, test_size=None)\n >>> for train, test in tscv.split(X):\n ... print(\"%s %s\" % (train, test))\n [0 1 2] [3]\n" }, { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex dd4ab30a7f2ff..2554d136c13ea 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -47,6 +47,15 @@ Changelog\n :mod:`sklearn.module`\n .....................\n \n+:mod:`sklearn.model_selection`\n+..............................\n+\n+- |Enhancement| :class:`model_selection.TimeSeriesSplit` has two new keyword\n+ arguments `test_size` and `gap`. `test_size` allows the out-of-sample\n+ time series length to be fixed for all folds. `gap` removes a fixed number of\n+ samples between the train and test set on each fold.\n+ :pr:`13204` by :user:`Kyle Kosic <kykosic>`.\n+\n \n Code and Documentation Contributors\n -----------------------------------\n" } ]
0.24
192109af3d65559d1e26887d35a21aa396af920f
[ "sklearn/model_selection/tests/test_split.py::test_train_test_split_mock_pandas", "sklearn/model_selection/tests/test_split.py::test_stratified_shuffle_split_multilabel_many_labels", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_label_invariance[7-False]", "sklearn/model_selection/tests/test_split.py::test_repeated_cv_value_errors", "sklearn/model_selection/tests/test_split.py::test_shuffle_split_default_test_size[0.8-8-2-StratifiedShuffleSplit]", "sklearn/model_selection/tests/test_split.py::test_kfold_indices", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[9-True]", "sklearn/model_selection/tests/test_split.py::test_predefinedsplit_with_kfold_split", "sklearn/model_selection/tests/test_split.py::test_train_test_split_default_test_size[8-8-2]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[5-True]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_default_test_size[None-7-3]", "sklearn/model_selection/tests/test_split.py::test_shuffle_split_empty_trainset[GroupShuffleSplit]", "sklearn/model_selection/tests/test_split.py::test_leave_one_p_group_out", "sklearn/model_selection/tests/test_split.py::test_2d_y", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes1[0.0-0.8]", "sklearn/model_selection/tests/test_split.py::test_group_kfold", "sklearn/model_selection/tests/test_split.py::test_shuffle_split_default_test_size[None-9-1-ShuffleSplit]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[9-False]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_pandas", "sklearn/model_selection/tests/test_split.py::test_group_shuffle_split", "sklearn/model_selection/tests/test_split.py::test_shufflesplit_errors[8-3]", "sklearn/model_selection/tests/test_split.py::test_leave_group_out_changing_groups", "sklearn/model_selection/tests/test_split.py::test_train_test_split_list_input", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes1[1.0-0.8]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_no_shuffle", "sklearn/model_selection/tests/test_split.py::test_cross_validator_with_default_params", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[4-True]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[5-False]", "sklearn/model_selection/tests/test_split.py::test_train_test_split", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes1[0.8-1.0]", "sklearn/model_selection/tests/test_split.py::test_kfold_no_shuffle", "sklearn/model_selection/tests/test_split.py::test_stratifiedshufflesplit_list_input", "sklearn/model_selection/tests/test_split.py::test_repeated_stratified_kfold_determinstic_split", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes2[0.8--10]", "sklearn/model_selection/tests/test_split.py::test_stratified_shuffle_split_multilabel", "sklearn/model_selection/tests/test_split.py::test_stratified_shuffle_split_respects_test_size", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[6-False]", "sklearn/model_selection/tests/test_split.py::test_build_repr", "sklearn/model_selection/tests/test_split.py::test_shuffle_stratifiedkfold", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes1[1.2-0.8]", "sklearn/model_selection/tests/test_split.py::test_leave_one_out_empty_trainset", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[4-False]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_allow_nans", "sklearn/model_selection/tests/test_split.py::test_random_state_shuffle_false[StratifiedKFold]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes2[0.8-11]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_label_invariance[6-True]", "sklearn/model_selection/tests/test_split.py::test_shufflesplit_errors[2.0-None]", "sklearn/model_selection/tests/test_split.py::test_stratifiedkfold_balance", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_label_invariance[4-False]", "sklearn/model_selection/tests/test_split.py::test_shuffle_kfold", "sklearn/model_selection/tests/test_split.py::test_shufflesplit_errors[1.0-None]", "sklearn/model_selection/tests/test_split.py::test_random_state_shuffle_false[KFold]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_label_invariance[4-True]", "sklearn/model_selection/tests/test_split.py::test_shuffle_split", "sklearn/model_selection/tests/test_split.py::test_time_series_cv", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes1[0.8--0.2]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes2[-10-0.8]", "sklearn/model_selection/tests/test_split.py::test_shuffle_split_empty_trainset[StratifiedShuffleSplit]", "sklearn/model_selection/tests/test_split.py::test_cv_iterable_wrapper", "sklearn/model_selection/tests/test_split.py::test_train_test_split_sparse", "sklearn/model_selection/tests/test_split.py::test_shufflesplit_reproducible", "sklearn/model_selection/tests/test_split.py::test_group_shuffle_split_default_test_size[None-8-2]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[10-True]", "sklearn/model_selection/tests/test_split.py::test_time_series_max_train_size", "sklearn/model_selection/tests/test_split.py::test_nested_cv", "sklearn/model_selection/tests/test_split.py::test_check_cv", "sklearn/model_selection/tests/test_split.py::test_train_test_split_default_test_size[0.8-8-2]", "sklearn/model_selection/tests/test_split.py::test_stratified_shuffle_split_even", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_label_invariance[6-False]", "sklearn/model_selection/tests/test_split.py::test_group_shuffle_split_default_test_size[0.7-7-3]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[10-False]", "sklearn/model_selection/tests/test_split.py::test_leave_one_p_group_out_error_on_fewer_number_of_groups", "sklearn/model_selection/tests/test_split.py::test_stratified_shuffle_split_overlap_train_test_bug", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[8-True]", "sklearn/model_selection/tests/test_split.py::test_shuffle_split_default_test_size[None-9-1-StratifiedShuffleSplit]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes2[0.8-0]", "sklearn/model_selection/tests/test_split.py::test_kfold_balance", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_label_invariance[7-True]", "sklearn/model_selection/tests/test_split.py::test_shuffle_split_default_test_size[8-8-2-ShuffleSplit]", "sklearn/model_selection/tests/test_split.py::test_shuffle_split_default_test_size[8-8-2-StratifiedShuffleSplit]", "sklearn/model_selection/tests/test_split.py::test_stratified_shuffle_split_init", "sklearn/model_selection/tests/test_split.py::test_shuffle_kfold_stratifiedkfold_reproducibility", "sklearn/model_selection/tests/test_split.py::test_train_test_split_empty_trainset", "sklearn/model_selection/tests/test_split.py::test_train_test_split_errors", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes1[0.8-0.0]", "sklearn/model_selection/tests/test_split.py::test_shuffle_split_default_test_size[0.8-8-2-ShuffleSplit]", "sklearn/model_selection/tests/test_split.py::test_shufflesplit_errors[10-None]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes1[-0.2-0.8]", "sklearn/model_selection/tests/test_split.py::test_get_n_splits_for_repeated_kfold", "sklearn/model_selection/tests/test_split.py::test_shufflesplit_errors[None-1j]", "sklearn/model_selection/tests/test_split.py::test_get_n_splits_for_repeated_stratified_kfold", "sklearn/model_selection/tests/test_split.py::test_stratified_shuffle_split_iter", "sklearn/model_selection/tests/test_split.py::test_repeated_cv_repr[RepeatedStratifiedKFold]", "sklearn/model_selection/tests/test_split.py::test_repeated_kfold_determinstic_split", "sklearn/model_selection/tests/test_split.py::test_kfold_can_detect_dependent_samples_on_digits", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes2[11-0.8]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[8-False]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes2[0-0.8]", "sklearn/model_selection/tests/test_split.py::test_shufflesplit_errors[0.1-0.95]", "sklearn/model_selection/tests/test_split.py::test_leave_p_out_empty_trainset", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[6-True]", "sklearn/model_selection/tests/test_split.py::test_shufflesplit_errors[11-None]", "sklearn/model_selection/tests/test_split.py::test_repeated_cv_repr[RepeatedKFold]", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[7-True]", "sklearn/model_selection/tests/test_split.py::test_train_test_split_invalid_sizes1[0.8-1.2]", "sklearn/model_selection/tests/test_split.py::test_kfold_valueerrors", "sklearn/model_selection/tests/test_split.py::test_stratified_kfold_ratios[7-False]", "sklearn/model_selection/tests/test_split.py::test_shuffle_split_empty_trainset[ShuffleSplit]", "sklearn/model_selection/tests/test_split.py::test_group_shuffle_split_default_test_size[7-7-3]" ]
[ "sklearn/model_selection/tests/test_split.py::test_time_series_test_size", "sklearn/model_selection/tests/test_split.py::test_time_series_gap" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/modules/cross_validation.rst", "old_path": "a/doc/modules/cross_validation.rst", "new_path": "b/doc/modules/cross_validation.rst", "metadata": "diff --git a/doc/modules/cross_validation.rst b/doc/modules/cross_validation.rst\nindex ed014cea6f2ff..61ea8c7ef4248 100644\n--- a/doc/modules/cross_validation.rst\n+++ b/doc/modules/cross_validation.rst\n@@ -782,7 +782,7 @@ Example of 3-split time series cross-validation on a dataset with 6 samples::\n >>> y = np.array([1, 2, 3, 4, 5, 6])\n >>> tscv = TimeSeriesSplit(n_splits=3)\n >>> print(tscv)\n- TimeSeriesSplit(max_train_size=None, n_splits=3)\n+ TimeSeriesSplit(gap=0, max_train_size=None, n_splits=3, test_size=None)\n >>> for train, test in tscv.split(X):\n ... print(\"%s %s\" % (train, test))\n [0 1 2] [3]\n" }, { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex dd4ab30a7f2ff..2554d136c13ea 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -47,6 +47,15 @@ Changelog\n :mod:`sklearn.module`\n .....................\n \n+:mod:`sklearn.model_selection`\n+..............................\n+\n+- |Enhancement| :class:`model_selection.TimeSeriesSplit` has two new keyword\n+ arguments `test_size` and `gap`. `test_size` allows the out-of-sample\n+ time series length to be fixed for all folds. `gap` removes a fixed number of\n+ samples between the train and test set on each fold.\n+ :pr:`<PRID>` by :user:`<NAME>`.\n+\n \n Code and Documentation Contributors\n -----------------------------------\n" } ]
diff --git a/doc/modules/cross_validation.rst b/doc/modules/cross_validation.rst index ed014cea6f2ff..61ea8c7ef4248 100644 --- a/doc/modules/cross_validation.rst +++ b/doc/modules/cross_validation.rst @@ -782,7 +782,7 @@ Example of 3-split time series cross-validation on a dataset with 6 samples:: >>> y = np.array([1, 2, 3, 4, 5, 6]) >>> tscv = TimeSeriesSplit(n_splits=3) >>> print(tscv) - TimeSeriesSplit(max_train_size=None, n_splits=3) + TimeSeriesSplit(gap=0, max_train_size=None, n_splits=3, test_size=None) >>> for train, test in tscv.split(X): ... print("%s %s" % (train, test)) [0 1 2] [3] diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index dd4ab30a7f2ff..2554d136c13ea 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -47,6 +47,15 @@ Changelog :mod:`sklearn.module` ..................... +:mod:`sklearn.model_selection` +.............................. + +- |Enhancement| :class:`model_selection.TimeSeriesSplit` has two new keyword + arguments `test_size` and `gap`. `test_size` allows the out-of-sample + time series length to be fixed for all folds. `gap` removes a fixed number of + samples between the train and test set on each fold. + :pr:`<PRID>` by :user:`<NAME>`. + Code and Documentation Contributors -----------------------------------
scikit-learn/scikit-learn
scikit-learn__scikit-learn-18527
https://github.com/scikit-learn/scikit-learn/pull/18527
diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index 424178e77c4b2..1b8b94ef5c87f 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -450,6 +450,12 @@ Changelog :pr:`18266` by :user:`Subrat Sahu <subrat93>`, :user:`Nirvan <Nirvan101>` and :user:`Arthur Book <ArthurBook>`. +- |Enhancement| :func:`model_selection.permutation_test_score` and + :func:`model_selection.validation_curve` now accept fit_params + to pass additional estimator parameters. + :pr:`18527` by :user:`Gaurav Dhingra <gxyd>`, + :user:`Julien Jerphanion <jjerphan>` and :user:`Amanda Dsouza <amy12xx>`. + - |Enhancement| :func:`model_selection.cross_val_score`, :func:`model_selection.cross_validate`, :class:`model_selection.GridSearchCV`, and diff --git a/sklearn/model_selection/_validation.py b/sklearn/model_selection/_validation.py index 7236f02fdc8f2..df9d873fe1fd4 100644 --- a/sklearn/model_selection/_validation.py +++ b/sklearn/model_selection/_validation.py @@ -1048,8 +1048,8 @@ def _check_is_permutation(indices, n_samples): @_deprecate_positional_args def permutation_test_score(estimator, X, y, *, groups=None, cv=None, n_permutations=100, n_jobs=None, random_state=0, - verbose=0, scoring=None): - """Evaluates the significance of a cross-validated score using permutations + verbose=0, scoring=None, fit_params=None): + """Evaluate the significance of a cross-validated score with permutations Permutes targets to generate 'randomized data' and compute the empirical p-value against the null hypothesis that features and targets are @@ -1129,6 +1129,11 @@ def permutation_test_score(estimator, X, y, *, groups=None, cv=None, verbose : int, default=0 The verbosity level. + fit_params : dict, default=None + Parameters to pass to the fit method of the estimator. + + .. versionadded:: 0.24 + Returns ------- score : float @@ -1165,24 +1170,29 @@ def permutation_test_score(estimator, X, y, *, groups=None, cv=None, # We clone the estimator to make sure that all the folds are # independent, and that it is pickle-able. - score = _permutation_test_score(clone(estimator), X, y, groups, cv, scorer) + score = _permutation_test_score(clone(estimator), X, y, groups, cv, scorer, + fit_params=fit_params) permutation_scores = Parallel(n_jobs=n_jobs, verbose=verbose)( delayed(_permutation_test_score)( clone(estimator), X, _shuffle(y, groups, random_state), - groups, cv, scorer) + groups, cv, scorer, fit_params=fit_params) for _ in range(n_permutations)) permutation_scores = np.array(permutation_scores) pvalue = (np.sum(permutation_scores >= score) + 1.0) / (n_permutations + 1) return score, permutation_scores, pvalue -def _permutation_test_score(estimator, X, y, groups, cv, scorer): +def _permutation_test_score(estimator, X, y, groups, cv, scorer, + fit_params): """Auxiliary function for permutation_test_score""" + # Adjust length of sample weights + fit_params = fit_params if fit_params is not None else {} avg_score = [] for train, test in cv.split(X, y, groups): X_train, y_train = _safe_split(estimator, X, y, train) X_test, y_test = _safe_split(estimator, X, y, test, train) - estimator.fit(X_train, y_train) + fit_params = _check_fit_params(X, fit_params, train) + estimator.fit(X_train, y_train, **fit_params) avg_score.append(scorer(estimator, X_test, y_test)) return np.mean(avg_score) @@ -1204,7 +1214,8 @@ def learning_curve(estimator, X, y, *, groups=None, train_sizes=np.linspace(0.1, 1.0, 5), cv=None, scoring=None, exploit_incremental_learning=False, n_jobs=None, pre_dispatch="all", verbose=0, shuffle=False, - random_state=None, error_score=np.nan, return_times=False): + random_state=None, error_score=np.nan, + return_times=False): """Learning curve. Determines cross-validated training and test scores for different training @@ -1501,7 +1512,7 @@ def _incremental_fit_estimator(estimator, X, y, classes, train, test, @_deprecate_positional_args def validation_curve(estimator, X, y, *, param_name, param_range, groups=None, cv=None, scoring=None, n_jobs=None, pre_dispatch="all", - verbose=0, error_score=np.nan): + verbose=0, error_score=np.nan, fit_params=None): """Validation curve. Determine training and test scores for varying parameter values. @@ -1577,6 +1588,11 @@ def validation_curve(estimator, X, y, *, param_name, param_range, groups=None, verbose : int, default=0 Controls the verbosity: the higher, the more messages. + fit_params : dict, default=None + Parameters to pass to the fit method of the estimator. + + .. versionadded:: 0.24 + error_score : 'raise' or numeric, default=np.nan Value to assign to the score if an error occurs in estimator fitting. If set to 'raise', the error is raised. @@ -1606,8 +1622,9 @@ def validation_curve(estimator, X, y, *, param_name, param_range, groups=None, verbose=verbose) results = parallel(delayed(_fit_and_score)( clone(estimator), X, y, scorer, train, test, verbose, - parameters={param_name: v}, fit_params=None, return_train_score=True, - error_score=error_score) + parameters={param_name: v}, fit_params=fit_params, + return_train_score=True, error_score=error_score) + # NOTE do not change order of iteration to allow one time cv splitters for train, test in cv.split(X, y, groups) for v in param_range) n_params = len(param_range)
diff --git a/sklearn/model_selection/tests/test_validation.py b/sklearn/model_selection/tests/test_validation.py index 9283aeee0f012..510811dfc4474 100644 --- a/sklearn/model_selection/tests/test_validation.py +++ b/sklearn/model_selection/tests/test_validation.py @@ -754,6 +754,23 @@ def test_permutation_test_score_allow_nans(): permutation_test_score(p, X, y) +def test_permutation_test_score_fit_params(): + X = np.arange(100).reshape(10, 10) + y = np.array([0] * 5 + [1] * 5) + clf = CheckingClassifier(expected_fit_params=['sample_weight']) + + err_msg = r"Expected fit parameter\(s\) \['sample_weight'\] not seen." + with pytest.raises(AssertionError, match=err_msg): + permutation_test_score(clf, X, y) + + err_msg = "Fit parameter sample_weight has length 1; expected" + with pytest.raises(AssertionError, match=err_msg): + permutation_test_score(clf, X, y, + fit_params={'sample_weight': np.ones(1)}) + permutation_test_score(clf, X, y, + fit_params={'sample_weight': np.ones(10)}) + + def test_cross_val_score_allow_nans(): # Check that cross_val_score allows input data with NaNs X = np.arange(200, dtype=np.float64).reshape(10, -1) @@ -1298,6 +1315,26 @@ def test_validation_curve_cv_splits_consistency(): assert_array_almost_equal(np.array(scores3), np.array(scores1)) +def test_validation_curve_fit_params(): + X = np.arange(100).reshape(10, 10) + y = np.array([0] * 5 + [1] * 5) + clf = CheckingClassifier(expected_fit_params=['sample_weight']) + + err_msg = r"Expected fit parameter\(s\) \['sample_weight'\] not seen." + with pytest.raises(AssertionError, match=err_msg): + validation_curve(clf, X, y, param_name='foo_param', + param_range=[1, 2, 3], error_score='raise') + + err_msg = "Fit parameter sample_weight has length 1; expected" + with pytest.raises(AssertionError, match=err_msg): + validation_curve(clf, X, y, param_name='foo_param', + param_range=[1, 2, 3], error_score='raise', + fit_params={'sample_weight': np.ones(1)}) + validation_curve(clf, X, y, param_name='foo_param', + param_range=[1, 2, 3], error_score='raise', + fit_params={'sample_weight': np.ones(10)}) + + def test_check_is_permutation(): rng = np.random.RandomState(0) p = np.arange(100)
[ { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex 424178e77c4b2..1b8b94ef5c87f 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -450,6 +450,12 @@ Changelog\n :pr:`18266` by :user:`Subrat Sahu <subrat93>`,\n :user:`Nirvan <Nirvan101>` and :user:`Arthur Book <ArthurBook>`.\n \n+- |Enhancement| :func:`model_selection.permutation_test_score` and\n+ :func:`model_selection.validation_curve` now accept fit_params\n+ to pass additional estimator parameters.\n+ :pr:`18527` by :user:`Gaurav Dhingra <gxyd>`,\n+ :user:`Julien Jerphanion <jjerphan>` and :user:`Amanda Dsouza <amy12xx>`.\n+\n - |Enhancement| :func:`model_selection.cross_val_score`,\n :func:`model_selection.cross_validate`,\n :class:`model_selection.GridSearchCV`, and\n" } ]
0.24
06c710ade0a800aeae6ad5f37418edbdeb618ade
[ "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_predict_proba_shape", "sklearn/model_selection/tests/test_validation.py::test_score_memmap", "sklearn/model_selection/tests/test_validation.py::test_validation_curve_clone_estimator", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[True-True-0]", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[False-False-nan]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_pandas", "sklearn/model_selection/tests/test_validation.py::test_fit_and_score_verbosity[False-scorer2-10-split_prg2-cdt_prg2-\\\\[CV 2/3; 1/1\\\\] END ....... sc1: \\\\(test=3.421\\\\) sc2: \\\\(test=3.421\\\\) total time= 0.\\\\ds]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_sparse_fit_params", "sklearn/model_selection/tests/test_validation.py::test_validation_curve_cv_splits_consistency", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_verbose", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[True-False-raise]", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_invalid_scoring_param", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[True-False-0]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_class_subset", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_batch_and_incremental_learning_are_equal", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_score_func", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_y_none", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_failing_scorer[raise]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_with_method", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_predict_groups", "sklearn/model_selection/tests/test_validation.py::test_permutation_test_score_pandas", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_failing_scorer[0]", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[False-True-nan]", "sklearn/model_selection/tests/test_validation.py::test_fit_and_score_working", "sklearn/model_selection/tests/test_validation.py::test_permutation_test_score_allow_nans", "sklearn/model_selection/tests/test_validation.py::test_fit_and_score_failing", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_many_jobs", "sklearn/model_selection/tests/test_validation.py::test_fit_and_score_verbosity[True-scorer1-3-split_prg1-cdt_prg1-\\\\[CV 2/3\\\\] END sc1: \\\\(train=3.421, test=3.421\\\\) sc2: \\\\(train=3.421, test=3.421\\\\) total time= 0.\\\\ds]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_fit_params", "sklearn/model_selection/tests/test_validation.py::test_permutation_score", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_allow_nans", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_with_score_func_regression", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_nested_estimator", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_with_method_multilabel_ovr", "sklearn/model_selection/tests/test_validation.py::test_gridsearchcv_cross_val_predict_with_method", "sklearn/model_selection/tests/test_validation.py::test_cross_validate", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_n_sample_range_out_of_bounds", "sklearn/model_selection/tests/test_validation.py::test_learning_curve", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_with_method_rare_class", "sklearn/model_selection/tests/test_validation.py::test_score", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_incremental_learning", "sklearn/model_selection/tests/test_validation.py::test_callable_multimetric_confusion_matrix_cross_validate", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[False-False-raise]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_decision_function_shape", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_with_shuffle", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_incremental_learning_unsupervised", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_precomputed", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[False-True-0]", "sklearn/model_selection/tests/test_validation.py::test_check_is_permutation", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_with_score_func_classification", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_with_method_multilabel_rf", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_pandas", "sklearn/model_selection/tests/test_validation.py::test_fit_and_score_verbosity[False-three_params_scorer-2-split_prg0-cdt_prg0-\\\\[CV\\\\] END .................................................... total time= 0.\\\\ds]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_multilabel", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_unsupervised", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_predict_log_proba_shape", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_input_types", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_with_method_multilabel_rf_rare_class", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_mask", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_with_boolean_indices", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_errors", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_sparse_prediction", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_incremental_learning_not_possible", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[True-False-nan]", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[False-False-0]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_method_checking", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[False-True-raise]", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_remove_duplicate_sample_sizes", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_failing_scorer[nan]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_unbalanced", "sklearn/model_selection/tests/test_validation.py::test_validation_curve", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[True-True-raise]", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[True-True-nan]" ]
[ "sklearn/model_selection/tests/test_validation.py::test_validation_curve_fit_params", "sklearn/model_selection/tests/test_validation.py::test_permutation_test_score_fit_params" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex 424178e77c4b2..1b8b94ef5c87f 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -450,6 +450,12 @@ Changelog\n :pr:`<PRID>` by :user:`<NAME>`,\n :user:`<NAME>` and :user:`<NAME>`.\n \n+- |Enhancement| :func:`model_selection.permutation_test_score` and\n+ :func:`model_selection.validation_curve` now accept fit_params\n+ to pass additional estimator parameters.\n+ :pr:`<PRID>` by :user:`<NAME>`,\n+ :user:`<NAME>` and :user:`<NAME>`.\n+\n - |Enhancement| :func:`model_selection.cross_val_score`,\n :func:`model_selection.cross_validate`,\n :class:`model_selection.GridSearchCV`, and\n" } ]
diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index 424178e77c4b2..1b8b94ef5c87f 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -450,6 +450,12 @@ Changelog :pr:`<PRID>` by :user:`<NAME>`, :user:`<NAME>` and :user:`<NAME>`. +- |Enhancement| :func:`model_selection.permutation_test_score` and + :func:`model_selection.validation_curve` now accept fit_params + to pass additional estimator parameters. + :pr:`<PRID>` by :user:`<NAME>`, + :user:`<NAME>` and :user:`<NAME>`. + - |Enhancement| :func:`model_selection.cross_val_score`, :func:`model_selection.cross_validate`, :class:`model_selection.GridSearchCV`, and
scikit-learn/scikit-learn
scikit-learn__scikit-learn-18343
https://github.com/scikit-learn/scikit-learn/pull/18343
diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index c57f097ec3218..c44ba08f2f57b 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -422,6 +422,14 @@ Changelog :pr:`18266` by :user:`Subrat Sahu <subrat93>`, :user:`Nirvan <Nirvan101>` and :user:`Arthur Book <ArthurBook>`. +- |Enhancement| :func:`model_selection.cross_val_score`, + :func:`model_selection.cross_validate`, + :class:`model_selection.GridSearchCV`, and + :class:`model_selection.RandomizedSearchCV` allows estimator to fail scoring + and replace the score with `error_score`. If `error_score="raise"`, the error + will be raised. + :pr:`18343` by `Guillaume Lemaitre`_ and :user:`Devi Sandeep <dsandeep0138>`. + :mod:`sklearn.multiclass` ......................... diff --git a/sklearn/feature_selection/_rfe.py b/sklearn/feature_selection/_rfe.py index f1b5e4793c551..f85309ca2659c 100644 --- a/sklearn/feature_selection/_rfe.py +++ b/sklearn/feature_selection/_rfe.py @@ -32,8 +32,10 @@ def _rfe_single_fit(rfe, estimator, X, y, train, test, scorer): X_train, y_train = _safe_split(estimator, X, y, train) X_test, y_test = _safe_split(estimator, X, y, test, train) return rfe._fit( - X_train, y_train, lambda estimator, features: - _score(estimator, X_test[:, features], y_test, scorer)).scores_ + X_train, y_train, + lambda estimator, features: _score( + estimator, X_test[:, features], y_test, scorer + )).scores_ class RFE(SelectorMixin, MetaEstimatorMixin, BaseEstimator): diff --git a/sklearn/model_selection/_validation.py b/sklearn/model_selection/_validation.py index 1152e5661aa43..1b4f9f5e96fbb 100644 --- a/sklearn/model_selection/_validation.py +++ b/sklearn/model_selection/_validation.py @@ -542,6 +542,13 @@ def _fit_and_score(estimator, X, y, scorer, train, test, verbose, fit_failed : bool The estimator failed to fit. """ + if not isinstance(error_score, numbers.Number) and error_score != 'raise': + raise ValueError( + "error_score must be the string 'raise' or a numeric value. " + "(Hint: if using 'raise', please make sure that it has been " + "spelled correctly.)" + ) + progress_msg = "" if verbose > 2: if split_progress is not None: @@ -607,19 +614,17 @@ def _fit_and_score(estimator, X, y, scorer, train, test, verbose, "Details: \n%s" % (error_score, format_exc()), FitFailedWarning) - else: - raise ValueError("error_score must be the string 'raise' or a" - " numeric value. (Hint: if using 'raise', please" - " make sure that it has been spelled correctly.)") result["fit_failed"] = True else: result["fit_failed"] = False fit_time = time.time() - start_time - test_scores = _score(estimator, X_test, y_test, scorer) + test_scores = _score(estimator, X_test, y_test, scorer, error_score) score_time = time.time() - start_time - fit_time if return_train_score: - train_scores = _score(estimator, X_train, y_train, scorer) + train_scores = _score( + estimator, X_train, y_train, scorer, error_score + ) if verbose > 1: total_time = score_time + fit_time @@ -654,7 +659,7 @@ def _fit_and_score(estimator, X, y, scorer, train, test, verbose, return result -def _score(estimator, X_test, y_test, scorer): +def _score(estimator, X_test, y_test, scorer, error_score="raise"): """Compute the score(s) of an estimator on a given test set. Will return a dict of floats if `scorer` is a dict, otherwise a single @@ -663,13 +668,30 @@ def _score(estimator, X_test, y_test, scorer): if isinstance(scorer, dict): # will cache method calls if needed. scorer() returns a dict scorer = _MultimetricScorer(**scorer) - if y_test is None: - scores = scorer(estimator, X_test) - else: - scores = scorer(estimator, X_test, y_test) - error_msg = ("scoring must return a number, got %s (%s) " - "instead. (scorer=%s)") + try: + if y_test is None: + scores = scorer(estimator, X_test) + else: + scores = scorer(estimator, X_test, y_test) + except Exception: + if error_score == 'raise': + raise + else: + if isinstance(scorer, _MultimetricScorer): + scores = {name: error_score for name in scorer._scorers} + else: + scores = error_score + warnings.warn( + f"Scoring failed. The score on this train-test partition for " + f"these parameters will be set to {error_score}. Details: \n" + f"{format_exc()}", + UserWarning, + ) + + error_msg = ( + "scoring must return a number, got %s (%s) instead. (scorer=%s)" + ) if isinstance(scores, dict): for name, score in scores.items(): if hasattr(score, 'item'): @@ -1353,7 +1375,9 @@ def learning_curve(estimator, X, y, *, groups=None, classes = np.unique(y) if is_classifier(estimator) else None out = parallel(delayed(_incremental_fit_estimator)( clone(estimator), X, y, classes, train, test, train_sizes_abs, - scorer, verbose, return_times) for train, test in cv_iter) + scorer, verbose, return_times, error_score=error_score) + for train, test in cv_iter + ) out = np.asarray(out).transpose((2, 1, 0)) else: train_test_proportions = [] @@ -1365,7 +1389,8 @@ def learning_curve(estimator, X, y, *, groups=None, clone(estimator), X, y, scorer, train, test, verbose, parameters=None, fit_params=None, return_train_score=True, error_score=error_score, return_times=return_times) - for train, test in train_test_proportions) + for train, test in train_test_proportions + ) results = _aggregate_score_dicts(results) train_scores = results["train_scores"].reshape(-1, n_unique_ticks).T test_scores = results["test_scores"].reshape(-1, n_unique_ticks).T @@ -1444,7 +1469,8 @@ def _translate_train_sizes(train_sizes, n_max_training_samples): def _incremental_fit_estimator(estimator, X, y, classes, train, test, - train_sizes, scorer, verbose, return_times): + train_sizes, scorer, verbose, + return_times, error_score): """Train estimator on training subsets incrementally and compute scores.""" train_scores, test_scores, fit_times, score_times = [], [], [], [] partitions = zip(train_sizes, np.split(train, train_sizes)[:-1]) @@ -1465,8 +1491,12 @@ def _incremental_fit_estimator(estimator, X, y, classes, train, test, start_score = time.time() - test_scores.append(_score(estimator, X_test, y_test, scorer)) - train_scores.append(_score(estimator, X_train, y_train, scorer)) + test_scores.append( + _score(estimator, X_test, y_test, scorer, error_score) + ) + train_scores.append( + _score(estimator, X_train, y_train, scorer, error_score) + ) score_time = time.time() - start_score score_times.append(score_time)
diff --git a/sklearn/model_selection/tests/test_validation.py b/sklearn/model_selection/tests/test_validation.py index 82cd0159d305a..46fcec2941aba 100644 --- a/sklearn/model_selection/tests/test_validation.py +++ b/sklearn/model_selection/tests/test_validation.py @@ -1,10 +1,10 @@ """Test the validation module""" - -import sys -import warnings -import tempfile import os import re +import sys +import tempfile +import warnings +from functools import partial from time import sleep import pytest @@ -333,16 +333,16 @@ def test_cross_validate_invalid_scoring_param(): multiclass_scorer = make_scorer(precision_recall_fscore_support) # Multiclass Scorers that return multiple values are not supported yet - assert_raises_regex(ValueError, - "Classification metrics can't handle a mix of " - "binary and continuous targets", - cross_validate, estimator, X, y, - scoring=multiclass_scorer) - assert_raises_regex(ValueError, - "Classification metrics can't handle a mix of " - "binary and continuous targets", - cross_validate, estimator, X, y, - scoring={"foo": multiclass_scorer}) + # the warning message we're expecting to see + warning_message = ("Scoring failed. The score on this train-test " + "partition for these parameters will be set to %f. " + "Details: \n" % np.nan) + + with pytest.warns(UserWarning, match=warning_message): + cross_validate(estimator, X, y, scoring=multiclass_scorer) + + with pytest.warns(UserWarning, match=warning_message): + cross_validate(estimator, X, y, scoring={"foo": multiclass_scorer}) assert_raises_regex(ValueError, "'mse' is not a valid scoring value.", cross_validate, SVC(), X, y, scoring="mse") @@ -1612,7 +1612,6 @@ def test_score_memmap(): score = np.memmap(tf.name, shape=(), mode='r', dtype=np.float64) try: cross_val_score(clf, X, y, scoring=lambda est, X, y: score) - # non-scalar should still fail assert_raises(ValueError, cross_val_score, clf, X, y, scoring=lambda est, X, y: scores) finally: @@ -1719,6 +1718,89 @@ def test_fit_and_score_working(): assert result['parameters'] == fit_and_score_kwargs['parameters'] +def _failing_scorer(estimator, X, y, error_msg): + raise ValueError(error_msg) + + [email protected]("ignore:lbfgs failed to converge") [email protected]("error_score", [np.nan, 0, "raise"]) +def test_cross_val_score_failing_scorer(error_score): + # check that an estimator can fail during scoring in `cross_val_score` and + # that we can optionally replaced it with `error_score` + X, y = load_iris(return_X_y=True) + clf = LogisticRegression(max_iter=5).fit(X, y) + + error_msg = "This scorer is supposed to fail!!!" + failing_scorer = partial(_failing_scorer, error_msg=error_msg) + + if error_score == "raise": + with pytest.raises(ValueError, match=error_msg): + cross_val_score( + clf, X, y, cv=3, scoring=failing_scorer, + error_score=error_score + ) + else: + warning_msg = ( + f"Scoring failed. The score on this train-test partition for " + f"these parameters will be set to {error_score}" + ) + with pytest.warns(UserWarning, match=warning_msg): + scores = cross_val_score( + clf, X, y, cv=3, scoring=failing_scorer, + error_score=error_score + ) + assert_allclose(scores, error_score) + + [email protected]("ignore:lbfgs failed to converge") [email protected]("error_score", [np.nan, 0, "raise"]) [email protected]("return_train_score", [True, False]) [email protected]("with_multimetric", [False, True]) +def test_cross_validate_failing_scorer( + error_score, return_train_score, with_multimetric +): + # check that an estimator can fail during scoring in `cross_validate` and + # that we can optionally replaced it with `error_score` + X, y = load_iris(return_X_y=True) + clf = LogisticRegression(max_iter=5).fit(X, y) + + error_msg = "This scorer is supposed to fail!!!" + failing_scorer = partial(_failing_scorer, error_msg=error_msg) + if with_multimetric: + scoring = {"score_1": failing_scorer, "score_2": failing_scorer} + else: + scoring = failing_scorer + + if error_score == "raise": + with pytest.raises(ValueError, match=error_msg): + cross_validate( + clf, X, y, + cv=3, + scoring=scoring, + return_train_score=return_train_score, + error_score=error_score + ) + else: + warning_msg = ( + f"Scoring failed. The score on this train-test partition for " + f"these parameters will be set to {error_score}" + ) + with pytest.warns(UserWarning, match=warning_msg): + results = cross_validate( + clf, X, y, + cv=3, + scoring=scoring, + return_train_score=return_train_score, + error_score=error_score + ) + for key in results: + if "_score" in key: + # check the test (and optionally train score) for all + # scorers that should be assigned to `error_score`. + assert_allclose(results[key], error_score) + + + def three_params_scorer(i, j, k): return 3.4213 @@ -1764,7 +1846,7 @@ def two_params_scorer(estimator, X_test): return None fit_and_score_args = [None, None, None, two_params_scorer] assert_raise_message(ValueError, error_message, - _score, *fit_and_score_args) + _score, *fit_and_score_args, error_score=np.nan) def test_callable_multimetric_confusion_matrix_cross_validate():
[ { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex c57f097ec3218..c44ba08f2f57b 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -422,6 +422,14 @@ Changelog\n :pr:`18266` by :user:`Subrat Sahu <subrat93>`,\n :user:`Nirvan <Nirvan101>` and :user:`Arthur Book <ArthurBook>`.\n \n+- |Enhancement| :func:`model_selection.cross_val_score`,\n+ :func:`model_selection.cross_validate`,\n+ :class:`model_selection.GridSearchCV`, and\n+ :class:`model_selection.RandomizedSearchCV` allows estimator to fail scoring\n+ and replace the score with `error_score`. If `error_score=\"raise\"`, the error\n+ will be raised.\n+ :pr:`18343` by `Guillaume Lemaitre`_ and :user:`Devi Sandeep <dsandeep0138>`.\n+\n :mod:`sklearn.multiclass`\n .........................\n \n" } ]
0.24
5a73abc3e93627b3ec0b55a9393faa9751cefd2b
[ "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[True-False-raise]", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_incremental_learning", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_predict_proba_shape", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_class_subset", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_batch_and_incremental_learning_are_equal", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_score_func", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_y_none", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_unsupervised", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_predict_log_proba_shape", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_failing_scorer[raise]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_input_types", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_with_method", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_with_method_multilabel_rf_rare_class", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_mask", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_predict_groups", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_with_boolean_indices", "sklearn/model_selection/tests/test_validation.py::test_permutation_test_score_pandas", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[False-False-raise]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_errors", "sklearn/model_selection/tests/test_validation.py::test_callable_multimetric_confusion_matrix_cross_validate", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_sparse_prediction", "sklearn/model_selection/tests/test_validation.py::test_score_memmap", "sklearn/model_selection/tests/test_validation.py::test_fit_and_score_working", "sklearn/model_selection/tests/test_validation.py::test_permutation_test_score_allow_nans", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_decision_function_shape", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_with_shuffle", "sklearn/model_selection/tests/test_validation.py::test_fit_and_score_failing", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_incremental_learning_not_possible", "sklearn/model_selection/tests/test_validation.py::test_validation_curve_clone_estimator", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_incremental_learning_unsupervised", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_precomputed", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_many_jobs", "sklearn/model_selection/tests/test_validation.py::test_fit_and_score_verbosity[True-scorer1-3-split_prg1-cdt_prg1-\\\\[CV 2/3\\\\] END sc1: \\\\(train=3.421, test=3.421\\\\) sc2: \\\\(train=3.421, test=3.421\\\\) total time= 0.\\\\ds]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_fit_params", "sklearn/model_selection/tests/test_validation.py::test_check_is_permutation", "sklearn/model_selection/tests/test_validation.py::test_fit_and_score_verbosity[False-three_params_scorer-2-split_prg0-cdt_prg0-\\\\[CV\\\\] END .................................................... total time= 0.\\\\ds]", "sklearn/model_selection/tests/test_validation.py::test_permutation_score", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_method_checking", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_allow_nans", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_pandas", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[False-True-raise]", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_remove_duplicate_sample_sizes", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_with_score_func_regression", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_unbalanced", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_with_score_func_classification", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_nested_estimator", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_with_method_multilabel_ovr", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_pandas", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_with_method_multilabel_rf", "sklearn/model_selection/tests/test_validation.py::test_fit_and_score_verbosity[False-scorer2-10-split_prg2-cdt_prg2-\\\\[CV 2/3; 1/1\\\\] END ....... sc1: \\\\(test=3.421\\\\) sc2: \\\\(test=3.421\\\\) total time= 0.\\\\ds]", "sklearn/model_selection/tests/test_validation.py::test_validation_curve", "sklearn/model_selection/tests/test_validation.py::test_gridsearchcv_cross_val_predict_with_method", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[True-True-raise]", "sklearn/model_selection/tests/test_validation.py::test_cross_validate", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_n_sample_range_out_of_bounds", "sklearn/model_selection/tests/test_validation.py::test_learning_curve", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_sparse_fit_params", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_with_method_rare_class", "sklearn/model_selection/tests/test_validation.py::test_validation_curve_cv_splits_consistency", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_verbose", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_multilabel" ]
[ "sklearn/model_selection/tests/test_validation.py::test_score", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_invalid_scoring_param", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[True-False-0]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_failing_scorer[0]", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[False-True-nan]", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[True-False-nan]", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[False-False-0]", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[False-True-0]", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[True-True-0]", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[False-False-nan]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_failing_scorer[nan]", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[True-True-nan]" ]
{ "header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [] }
[ { "path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex c57f097ec3218..c44ba08f2f57b 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -422,6 +422,14 @@ Changelog\n :pr:`<PRID>` by :user:`<NAME>`,\n :user:`<NAME>` and :user:`<NAME>`.\n \n+- |Enhancement| :func:`model_selection.cross_val_score`,\n+ :func:`model_selection.cross_validate`,\n+ :class:`model_selection.GridSearchCV`, and\n+ :class:`model_selection.RandomizedSearchCV` allows estimator to fail scoring\n+ and replace the score with `error_score`. If `error_score=\"raise\"`, the error\n+ will be raised.\n+ :pr:`<PRID>` by `<NAME>`_ and :user:`<NAME>`.\n+\n :mod:`sklearn.multiclass`\n .........................\n \n" } ]
diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index c57f097ec3218..c44ba08f2f57b 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -422,6 +422,14 @@ Changelog :pr:`<PRID>` by :user:`<NAME>`, :user:`<NAME>` and :user:`<NAME>`. +- |Enhancement| :func:`model_selection.cross_val_score`, + :func:`model_selection.cross_validate`, + :class:`model_selection.GridSearchCV`, and + :class:`model_selection.RandomizedSearchCV` allows estimator to fail scoring + and replace the score with `error_score`. If `error_score="raise"`, the error + will be raised. + :pr:`<PRID>` by `<NAME>`_ and :user:`<NAME>`. + :mod:`sklearn.multiclass` .........................